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

header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
  http_response_code(403);
  echo json_encode(["error" => "Unauthorized"]);
  exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
    http_response_code(419);
    echo json_encode(["error" => "Invalid CSRF token"]);
    exit;
  }

  $id = $_POST['id'];
  $time_in  = $_POST['time_in'] ?? null;
  $time_out = $_POST['time_out'] ?? null;
  $gps_in   = $_POST['gps_in'] ?? null;
  $gps_out  = $_POST['gps_out'] ?? null;

  $stmt = $pdo->prepare("UPDATE attendance SET time_in = ?, time_out = ?, gps_in = ?, gps_out = ? WHERE id = ?");
  $stmt->execute([$time_in, $time_out, $gps_in, $gps_out, $id]);

  echo json_encode(["success" => true]);
  exit;
}
?>