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

$conn = getDbConnection();

// ✅ Enable error logging (for debugging, remove in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', 'patrol_errors.log'); // Log errors to this file

// ✅ Read JSON Input
$data = json_decode(file_get_contents("php://input"), true);
$siteIds = $data['site_ids'] ?? [];

if (empty($siteIds)) {
    echo json_encode(["success" => false, "message" => "No site IDs provided"]);
    exit();
}

// ✅ Convert site IDs into SQL placeholders
$placeholders = implode(',', array_fill(0, count($siteIds), '?'));

// ✅ Debugging: Log the received site IDs
error_log("Received Site IDs: " . json_encode($siteIds));

// ✅ Fetch Patrol Summary with Full Timestamp
$query = "
    SELECT 
        p.site_id, s.site_name, 
        u.real_name, 
        p.tag_name, 
        DATE_FORMAT(p.patrol_time, '%Y-%m-%d') AS patrol_date,  
        DATE_FORMAT(p.patrol_time, '%H:%i:%s') AS patrol_time  
    FROM patrols p
    JOIN users u ON p.user_id = u.user_id
    JOIN sites s ON p.site_id = s.site_id
    WHERE p.site_id IN ($placeholders)
    ORDER BY p.site_id, p.patrol_time DESC";

$stmt = $conn->prepare($query);

// ✅ Debugging: Check if statement preparation fails
if (!$stmt) {
    echo json_encode(["success" => false, "message" => "SQL Error: " . $conn->error]);
    error_log("SQL Error: " . $conn->error);
    exit();
}

// ✅ Bind parameters dynamically
$types = str_repeat("i", count($siteIds)); // Create binding string "iii" for int values
$stmt->bind_param($types, ...$siteIds);
$stmt->execute();
$result = $stmt->get_result();

// ✅ Debugging: Log number of rows retrieved
$numRows = $result->num_rows;
error_log("Number of patrol records retrieved: " . $numRows);

$patrols = [];
while ($row = $result->fetch_assoc()) {
    $siteId = $row["site_id"];
    if (!isset($patrols[$siteId])) {
        $patrols[$siteId] = [
            "site_name" => $row["site_name"],
            "patrols" => []
        ];
    }

    $patrols[$siteId]["patrols"][] = [
        "real_name" => $row["real_name"],
        "tag_name" => $row["tag_name"],
        "patrol_date" => $row["patrol_date"],
        "patrol_time" => $row["patrol_time"]
    ];
}

// ✅ Return Data
echo json_encode(["success" => true, "patrols" => array_values($patrols)]);

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