<?php
require 'config.php'; // Include database connection

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

// Establish database connection
$conn = getDbConnection();
if (!$conn) {
    echo json_encode(["success" => false, "message" => "Database connection failed"]);
    exit();
}

// ✅ Enable error logging
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', 'patrol_log_debug.log');

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

$user_id = intval($_GET['user_id']);
$book_on_time = $_GET['book_on_time']; // Format: YYYY-MM-DD HH:MM:SS

// ✅ Fetch patrol records filtered by `user_id` and `book_on_time`
$query = "SELECT id, user_id, site_id, org_id, tag_name, patrol_time 
          FROM patrols 
          WHERE user_id = ? AND patrol_time >= ? 
          ORDER BY patrol_time DESC";

$stmt = $conn->prepare($query);
$stmt->bind_param("is", $user_id, $book_on_time);
$stmt->execute();
$result = $stmt->get_result();

$patrols = [];
while ($row = $result->fetch_assoc()) {
    $patrols[] = [
        "id" => $row["id"],
        "user_id" => $row["user_id"],
        "site_id" => $row["site_id"],
        "org_id" => $row["org_id"],
        "tag_name" => $row["tag_name"],
        "patrol_time" => $row["patrol_time"]
    ];
}

// ✅ Send response
echo json_encode(["success" => true, "patrols" => $patrols]);

$conn->close();
?>
