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

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

ob_start(); // ✅ Prevents accidental output before JSON

error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', 'check_book_on_status_error.log');

$conn = getDbConnection();

// ✅ Log received request
error_log("Received Check Book On Request: " . json_encode($_GET));

// ✅ Validate parameters
if (!isset($_GET['user_id'])) {
    error_log("Missing required parameter: user_id");
    echo json_encode(["success" => false, "message" => "Missing user_id"]);
    exit();
}

$user_id = intval($_GET['user_id']);
$date = date("Y-m-d");

// ✅ Check if user has a booking record for today
$stmt = $conn->prepare("
    SELECT site_id, clock_in_tag, clock_in_time 
    FROM clock_in 
    WHERE user_id = ? AND DATE(clock_in_time) = ? 
    ORDER BY clock_in_time DESC LIMIT 1
");
$stmt->bind_param("is", $user_id, $date);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();

if ($row) {
    $site_id = $row['site_id'];
    $clock_in_tag = $row['clock_in_tag'];
    $clock_in_time = $row['clock_in_time'];

    error_log("User found: user_id=$user_id, site_id=$site_id, tag=$clock_in_tag, time=$clock_in_time");

    echo json_encode([
        "success" => true,
        "is_booked_on" => true,
        "site_id" => $site_id,
        "clock_in_tag" => $clock_in_tag,
        "clock_in_time" => $clock_in_time
    ]);
} else {
    error_log("No booking record found for user_id=$user_id on $date");
    echo json_encode(["success" => true, "is_booked_on" => false]);
}

$conn->close();
ob_end_flush();
?>
