<?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 array into a string for SQL query
$placeholders = implode(',', array_fill(0, count($siteIds), '?'));

// ✅ Fetch Clock-Out records for given site IDs
$query = "
    SELECT 
        c.site_id, s.site_name, 
        u.real_name, 
        c.clock_out_time
    FROM clock_out c
    JOIN users u ON c.user_id = u.user_id
    JOIN sites s ON c.site_id = s.site_id
    WHERE c.site_id IN ($placeholders)
    ORDER BY c.clock_out_time DESC";

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

$clockOuts = [];
while ($row = $result->fetch_assoc()) {
    $clockOuts[] = [
        "site_name" => $row["site_name"],
        "real_name" => $row["real_name"],
        "clock_out_time" => $row["clock_out_time"]
    ];
}

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

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