<?php
session_start();
require_once '../includes/config.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'controller') {
    header("Location: ../auth/login.php");
    exit;
}

$controller_id = $_SESSION['user_id'];
$action = $_POST['action'] ?? '';
$today = date('Y-m-d');

// Check if today's attendance exists
$stmt = $pdo->prepare("SELECT * FROM controller_attendance WHERE controller_id = ? AND date = ?");
$stmt->execute([$controller_id, $today]);
$attendance = $stmt->fetch();

if ($action === 'in') {
    if ($attendance && $attendance['time_in']) {
        $_SESSION['message'] = "✅ You already checked in today.";
    } elseif ($attendance) {
        $pdo->prepare("UPDATE controller_attendance SET time_in = NOW() WHERE id = ?")
            ->execute([$attendance['id']]);
        $_SESSION['message'] = "🕒 Check-in time updated.";
    } else {
        $pdo->prepare("INSERT INTO controller_attendance (controller_id, date, time_in) VALUES (?, ?, NOW())")
            ->execute([$controller_id, $today]);
        $_SESSION['message'] = "✅ Check-in recorded.";
    }

} elseif ($action === 'out') {
    if (!$attendance || $attendance['time_out']) {
        $_SESSION['message'] = "⚠️ Already checked out or not checked in yet.";
    } else {
        $pdo->prepare("UPDATE controller_attendance SET time_out = NOW() WHERE id = ?")
            ->execute([$attendance['id']]);
        $_SESSION['message'] = "⏰ Check-out completed.";
    }
}

header("Location: dashboard.php");
exit;
