<?php

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

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

// 🔹 GET INPUT
$data = json_decode(file_get_contents("php://input"), true);

$mobile = $conn->real_escape_string($data['mobile'] ?? '');

if (empty($mobile)) {
    echo json_encode([
        "status" => false,
        "message" => "Mobile required"
    ]);
    exit;
}

// 🔍 SEARCH WITH VILLAGE COUNT
$query = "SELECT 
v.*,
COUNT(DISTINCT vl.village_id) as total_villages
FROM visitors v
LEFT JOIN visitor_logs vl ON v.id = vl.visitor_id
WHERE v.mobile = '$mobile'
GROUP BY v.id
LIMIT 1";

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

if ($result->num_rows > 0) {
    $visitor = $result->fetch_assoc();

    echo json_encode([
        "status" => true,
        "found" => true,
        "data" => $visitor
    ]);
} else {
    echo json_encode([
        "status" => true,
        "found" => false
    ]);
}