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

$conn = getDbConnection();

// ✅ 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), '?'));

// ✅ Fetch Hourly Check records for given site IDs
$query = "
    SELECT 
        h.site_id, s.site_name, 
        h.real_name, 
        h.personal_safety, 
        h.site_secure, 
        h.equipment_functional, 
        h.comments, 
        h.check_time
    FROM hourly_check h
    JOIN sites s ON h.site_id = s.site_id
    WHERE h.site_id IN ($placeholders)
    ORDER BY h.check_time DESC";

$stmt = $conn->prepare($query);
$stmt->bind_param(str_repeat("i", count($siteIds)), ...$siteIds);
$stmt->execute();
$result = $stmt->get_result();

$hourlyChecks = [];
while ($row = $result->fetch_assoc()) {
    $hourlyChecks[] = [
        "site_name" => $row["site_name"],
        "real_name" => $row["real_name"],
        "personal_safety" => $row["personal_safety"],
        "site_secure" => $row["site_secure"],
        "equipment_functional" => $row["equipment_functional"],
        "comments" => $row["comments"],
        "check_time" => $row["check_time"]
    ];
}

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

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