<?php
require 'config.php';
header("Content-Type: application/json");

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

// ✅ Log Incoming Request Data
$data = json_decode(file_get_contents("php://input"), true);
file_put_contents('patrol_fetch_debug.log', "Received Data:\n" . print_r($data, true), FILE_APPEND);

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

$user_id = intval($data['user_id']);
$book_on_time = $data['book_on_time'];

// ✅ Query: Fetch patrol logs AFTER the user booked on
$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']
    ];
}

// ✅ Log Retrieved Data for Debugging
file_put_contents('patrol_fetch_debug.log', "Retrieved Data:\n" . print_r($patrols, true), FILE_APPEND);

if (count($patrols) > 0) {
    echo json_encode(["success" => true, "patrols" => $patrols]);
} else {
    echo json_encode(["success" => false, "message" => "No patrol records found"]);
}

$conn->close();
?>
