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

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 for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', 'patrol_log_debug.log');

// ✅ Fetch ALL patrol logs
$query = "SELECT id, user_id, site_id, org_id, tag_name, patrol_time FROM patrols ORDER BY patrol_time DESC";
$result = $conn->query($query);

if ($result === false) {
    echo json_encode(["success" => false, "message" => "Query failed: " . $conn->error]);
    exit();
}

$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();
?>
