<?php

header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");

require_once("../config/db.php");

$query = "
SELECT 
    sr.id,
    sr.visitor_id,
    sr.reason,
    sr.status,
    sr.created_at,
    sr.document,

    v.name AS visitor_name,
    v.mobile,

    u.name AS requested_by_name,
    u.mobile AS requested_by_mobile,

    (
        SELECT GROUP_CONCAT(
            CONCAT(role, ':', action, ':', created_at)
            ORDER BY created_at ASC SEPARATOR '|'
        )
        FROM suspicious_history sh
        WHERE sh.request_id = sr.id
    ) AS timeline

FROM suspicious_requests sr

LEFT JOIN visitors v ON sr.visitor_id = v.id
LEFT JOIN users u ON sr.requested_by = u.id

ORDER BY sr.id DESC
";

$result = $conn->query($query);

$data = [];

if ($result) {
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
}

echo json_encode([
    "status" => true,
    "data" => $data
]);