<?php 
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) {
  session_start();
}

if (empty($_SESSION['user_id'])) {
  header('Location: executive_login.php'); 
  exit;
}

require __DIR__ . '/../includes/db.php';

/* ✅ Align timezone with IST for MySQL */
try { 
  $pdo->exec("SET time_zone = '+05:30'"); 
} catch (Throwable $e) {}

/* ✅ Current executive ID */
$eid = (int)$_SESSION['user_id'];

/*
  ✅ New Logic:
  - Get the latest attendance record for today (IST)
  - If no record → force to attendance.php (must check-in first)
  - If latest action = 'checkin' → allow access to index.php
  - If latest action = 'checkout' → force to attendance.php (must re-checkin)
*/
$st = $pdo->prepare("
  SELECT action 
  FROM attendance_logs
  WHERE executive_id = :eid
    AND DATE(CONVERT_TZ(created_at,'+00:00','+05:30')) = CURDATE()
  ORDER BY id DESC
  LIMIT 1
");
$st->execute([':eid' => $eid]);
$latestAction = $st->fetchColumn();

/* ✅ Decide next step */
if ($latestAction === false) {
  // No action for today
  $_SESSION['flash'] = 'Please check-in before starting data collection.';
  header('Location: attendance.php');
  exit;
}

if ($latestAction !== 'checkin') {
  // Last action is checkout → must check-in again
  $_SESSION['flash'] = 'Please check-in to continue.';
  header('Location: attendance.php');
  exit;
}

// ✅ If latest action is check-in, continue normally (stay on index.php)
