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

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

// Check if officer is logged in (replace with your session check)
if (!isset($_SESSION['officer_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

$officer_id = $_SESSION['officer_id'];
$type = $_POST['type'] ?? '';
$gps = $_POST['gps'] ?? '';
$currentDate = date('Y-m-d');
$currentTime = date('Y-m-d H:i:s');

try {
    // Check if attendance already exists today
    $stmt = $pdo->prepare("SELECT * FROM attendance WHERE officer_id = ? AND date = ?");
    $stmt->execute([$officer_id, $currentDate]);
    $attendance = $stmt->fetch();

    if (!$attendance) {
        // First time in, insert
        if ($type === 'in') {
            $stmt = $pdo->prepare("INSERT INTO attendance (officer_id, date, time_in, gps_in) VALUES (?, ?, ?, ?)");
            $stmt->execute([$officer_id, $currentDate, $currentTime, $gps]);
            echo json_encode(['status' => 'success', 'message' => 'Time In recorded']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'You must Time In before Time Out']);
        }
    } else {
        if ($type === 'out') {
            if ($attendance['time_out']) {
                echo json_encode(['status' => 'error', 'message' => 'Time Out already recorded']);
            } else {
                $stmt = $pdo->prepare("UPDATE attendance SET time_out = ?, gps_out = ? WHERE id = ?");
                $stmt->execute([$currentTime, $gps, $attendance['id']]);
                echo json_encode(['status' => 'success', 'message' => 'Time Out recorded']);
            }
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Already Time In recorded']);
        }
    }
} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
