<?php

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

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

// 🔹 GET INPUT
$name        = $conn->real_escape_string($_POST['name'] ?? '');
$mobile      = $conn->real_escape_string($_POST['mobile'] ?? '');
$village_id  = intval($_POST['village_id'] ?? 0);
$entry_by    = intval($_POST['entry_by'] ?? 0);
$description = $conn->real_escape_string($_POST['description'] ?? '');

// ✅ FIX: map created_by from entry_by
$created_by = $entry_by ?: 1; // fallback if empty

// 🔹 VALIDATION
if (empty($name) || empty($mobile) || !$village_id) {
    echo json_encode([
        "status" => false,
        "message" => "Name, mobile and village required"
    ]);
    exit;
}

// 🔹 IMAGE UPLOAD FUNCTION
function uploadImage($file, $folder = "../../uploads/")
{
    if (!isset($file) || $file['error'] !== 0) {
        return null;
    }

    if (!file_exists($folder)) {
        mkdir($folder, 0777, true);
    }

    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = time() . "_" . rand(1000, 9999) . "." . $ext;

    $path = $folder . $filename;

    if (move_uploaded_file($file['tmp_name'], $path)) {
        return "uploads/" . $filename;
    }

    return null;
}

// 🔹 UPLOAD IMAGES
$aadhaar_front = uploadImage($_FILES['aadhaar_front'] ?? null);
$aadhaar_back  = uploadImage($_FILES['aadhaar_back'] ?? null);
$selfie        = uploadImage($_FILES['selfie'] ?? null);

// 🔹 SELFIE REQUIRED
if (!$selfie) {
    echo json_encode([
        "status" => false,
        "message" => "Selfie is required"
    ]);
    exit;
}

// 🔍 CHECK IF VISITOR EXISTS
$checkQuery = "SELECT id FROM visitors WHERE mobile = '$mobile' LIMIT 1";
$checkResult = $conn->query($checkQuery);

if ($checkResult && $checkResult->num_rows > 0) {

    // 👉 EXISTING VISITOR
    $existing = $checkResult->fetch_assoc();
    $visitor_id = $existing['id'];

} else {

    // 👉 NEW VISITOR INSERT (✅ FIX ADDED created_by)
    $insertQuery = "INSERT INTO visitors 
    (name, mobile, aadhaar_front, aadhaar_back, selfie, village_id, entry_by, created_by, description) 
    VALUES 
    ('$name', '$mobile', '$aadhaar_front', '$aadhaar_back', '$selfie', '$village_id', '$entry_by', '$created_by', '$description')";

    if (!$conn->query($insertQuery)) {
        echo json_encode([
            "status" => false,
            "message" => "Database error: " . $conn->error
        ]);
        exit;
    }

    $visitor_id = $conn->insert_id;
}

// 🔥 INSERT INTO LOGS
$logQuery = "INSERT INTO visitor_logs 
(visitor_id, village_id, checked_by, action) 
VALUES 
('$visitor_id', '$village_id', '$entry_by', 'visited')";

$conn->query($logQuery);

// 🔁 RESPONSE
echo json_encode([
    "status" => true,
    "message" => "Visitor added to your village successfully"
]);