<?php
require '../includes/config.php';

$data = json_decode(file_get_contents("php://input"), true);

$officer_id = $data['officer_id'];
$gps = $data['gps'];
$type = $data['type']; // in or out
$currentDate = date('Y-m-d');
$currentTime = date('Y-m-d H:i:s');

$stmt = $pdo->prepare("SELECT * FROM attendance WHERE officer_id = ? AND date = ?");
$stmt->execute([$officer_id, $currentDate]);
$attendance = $stmt->fetch();

if (!$attendance && $type === 'in') {
    $pdo->prepare("INSERT INTO attendance (officer_id, date, time_in, gps_in) VALUES (?, ?, ?, ?)")
        ->execute([$officer_id, $currentDate, $currentTime, $gps]);
    echo json_encode(["status" => "success", "message" => "Checked In"]);
} elseif ($attendance && $type === 'out' && !$attendance['time_out']) {
    $pdo->prepare("UPDATE attendance SET time_out = ?, gps_out = ? WHERE id = ?")
        ->execute([$currentTime, $gps, $attendance['id']]);
    echo json_encode(["status" => "success", "message" => "Checked Out"]);
} else {
    echo json_encode(["status" => "error", "message" => "Invalid state"]);
}
