<?php

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

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

// 🔹 GET VISITOR ID
$visitor_id = intval($_GET['visitor_id'] ?? 0);

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

/* =====================================================
   🔥 MAIN VISITOR DATA
===================================================== */

$query = "SELECT 
    v.id,
    v.name,
    v.mobile,
    v.selfie,
    v.aadhaar_front,
    v.aadhaar_back,
    v.description,
    v.is_suspicious,
    v.suspicious_note,

    v.entry_by,
    v.suspicious_by,

    u1.name AS entry_by_name,
    u2.name AS suspicious_by_name,

    vg.village_name

FROM visitors v

LEFT JOIN users u1 ON v.entry_by = u1.id
LEFT JOIN users u2 ON v.suspicious_by = u2.id
LEFT JOIN villages vg ON v.village_id = vg.id

WHERE v.id = '$visitor_id'
LIMIT 1";

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

if (!$result || $result->num_rows == 0) {
    echo json_encode([
        "status" => false,
        "message" => "Visitor not found"
    ]);
    exit;
}

$data = $result->fetch_assoc();

/* 🔹 NULL HANDLING */
if (!$data['selfie']) $data['selfie'] = "";
if (!$data['aadhaar_front']) $data['aadhaar_front'] = "";
if (!$data['aadhaar_back']) $data['aadhaar_back'] = "";
if (!$data['description']) $data['description'] = "";
if (!$data['suspicious_note']) $data['suspicious_note'] = "";
if (!$data['entry_by_name']) $data['entry_by_name'] = "Unknown";
if (!$data['suspicious_by_name']) $data['suspicious_by_name'] = "Unknown";
if (!$data['village_name']) $data['village_name'] = "Unknown Village";

/* =====================================================
   🔥 TIMELINE (VISIT HISTORY)
===================================================== */

$timeline = [];

$timeline_query = $conn->query("
SELECT 
    vl.id,
    vl.created_at,
    vl.village_id,
    vl.checked_by,

    vlg.village_name,
    u.name AS user_name

FROM visitor_logs vl

LEFT JOIN villages vlg ON vl.village_id = vlg.id
LEFT JOIN users u ON vl.checked_by = u.id

WHERE vl.visitor_id = '$visitor_id'

ORDER BY vl.created_at DESC
");

if ($timeline_query && $timeline_query->num_rows > 0) {
    while ($row = $timeline_query->fetch_assoc()) {

        if (!$row['village_name']) $row['village_name'] = "Unknown";
        if (!$row['user_name']) $row['user_name'] = "Unknown";

        $timeline[] = $row;
    }
}

/* =====================================================
   🔁 FINAL RESPONSE
===================================================== */

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