<?php

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

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

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

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

// 🔍 FINAL OPTIMIZED QUERY (UPDATED)
$query = "SELECT 
    v.id AS visitor_id,
    v.name,
    v.mobile,
    v.aadhaar_front,
    v.aadhaar_back,
    v.selfie,
    v.description,
    v.is_suspicious,
    v.suspicious_note, -- ✅ ADDED

    COUNT(DISTINCT vl.village_id) AS total_villages,
    MAX(vl.created_at) AS last_visit,

    -- 🆕 TODAY VISITED VILLAGES
    GROUP_CONCAT(
        DISTINCT CASE 
            WHEN DATE(vl.created_at) = CURDATE() 
            THEN vg.village_name 
        END
    ) AS villages_today

FROM visitors v

JOIN visitor_logs vl ON v.id = vl.visitor_id

LEFT JOIN villages vg ON vl.village_id = vg.id

WHERE vl.village_id = '$village_id'

GROUP BY v.id

ORDER BY last_visit DESC";

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

$data = [];

if ($result) {
    while ($row = $result->fetch_assoc()) {

        // 🔹 NULL HANDLE
        if (!$row['villages_today']) {
            $row['villages_today'] = "";
        }

        if (!$row['selfie']) {
            $row['selfie'] = "";
        }

        if (!$row['suspicious_note']) {
            $row['suspicious_note'] = ""; // ✅ IMPORTANT
        }

        $data[] = $row;
    }
}

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