<?php

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

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

$user_id = intval($_GET['user_id'] ?? 0);

if (!$user_id) {
    echo json_encode(["status" => false, "message" => "User ID required"]);
    exit;
}

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

    v.name AS visitor_name,
    v.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

WHERE sr.requested_by = '$user_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
]);