<?php
ini_set("display_errors", 1);
error_reporting(E_ALL);

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

$msg = "";
$err = "";
$searched_mobile = "";
$foundVisitor = null;

function uploadVisitorImage($field) {
    if (empty($_FILES[$field]["name"]) || $_FILES[$field]["error"] !== UPLOAD_ERR_OK) return null;

    $folder = "../uploads/";
    if (!is_dir($folder)) mkdir($folder, 0777, true);

    $ext = strtolower(pathinfo($_FILES[$field]["name"], PATHINFO_EXTENSION));
    $allowed = ["jpg", "jpeg", "png", "webp"];
    if (!in_array($ext, $allowed, true)) return null;

    $filename = time() . "_" . random_int(1000, 9999) . "_" . $field . "." . $ext;
    if (move_uploaded_file($_FILES[$field]["tmp_name"], $folder . $filename)) {
        return "uploads/" . $filename;
    }

    return null;
}

function postedImagePath($field) {
    $path = trim($_POST[$field . "_path"] ?? "");
    if ($path === "") return null;
    if (!preg_match('/^uploads\/[a-zA-Z0-9._-]+$/', $path)) return null;
    return $path;
}

if (isset($_POST["search_mobile"])) {
    $searched_mobile = $conn->real_escape_string(trim($_POST["search_mobile"] ?? ""));

    if (!preg_match('/^[0-9]{10}$/', $searched_mobile)) {
        $err = "Please enter valid 10 digit mobile number.";
    } else {
        $q = $conn->query("
            SELECT v.*, COUNT(DISTINCT vl.village_id) AS total_villages, MAX(vl.created_at) AS last_visit
            FROM visitors v
            LEFT JOIN visitor_logs vl ON v.id = vl.visitor_id
            WHERE v.mobile='$searched_mobile'
            GROUP BY v.id
            LIMIT 1
        ");

        if ($q && $q->num_rows > 0) {
            $foundVisitor = $q->fetch_assoc();
        } else {
            $msg = "No existing visitor found. Add as new visitor.";
        }
    }
}

if (isset($_POST["mark_existing_visit"])) {
    $visitor_id = intval($_POST["visitor_id"] ?? 0);

    if (!$visitor_id) {
        $err = "Invalid visitor.";
    } else {
        $conn->query("
            INSERT INTO visitor_logs (visitor_id, village_id, checked_by, action)
            VALUES ('$visitor_id', '$village_id', '$admin_id', 'visited')
        ");
        $msg = $conn->error ? "Visit log failed: " . $conn->error : "Visitor marked as visited in your village.";
    }
}

if (isset($_POST["add_new_visitor"])) {
    $name = $conn->real_escape_string(trim($_POST["name"] ?? ""));
    $mobile = $conn->real_escape_string(trim($_POST["mobile"] ?? ""));
    $description = $conn->real_escape_string(trim($_POST["description"] ?? ""));

    if (!$name || !$mobile) {
        $err = "Name and mobile are required.";
    } elseif (!preg_match('/^[0-9]{10}$/', $mobile)) {
        $err = "Please enter valid 10 digit mobile number.";
    } else {
        $check = $conn->query("SELECT id FROM visitors WHERE mobile='$mobile' LIMIT 1");

        if ($check && $check->num_rows > 0) {
            $visitor_id = intval($check->fetch_assoc()["id"]);
            $conn->query("
                INSERT INTO visitor_logs (visitor_id, village_id, checked_by, action)
                VALUES ('$visitor_id', '$village_id', '$admin_id', 'visited')
            ");
            $msg = $conn->error ? "Visit log failed: " . $conn->error : "Visitor already existed. Marked as visited in your village.";
        } else {
            $aadhaar_front = postedImagePath("aadhaar_front") ?: uploadVisitorImage("aadhaar_front");
            $aadhaar_back = postedImagePath("aadhaar_back") ?: uploadVisitorImage("aadhaar_back");
            $selfie = postedImagePath("selfie") ?: uploadVisitorImage("selfie");

            if (!$selfie) {
                $err = "Selfie is required.";
            } else {
                $insert = $conn->query("
                    INSERT INTO visitors (name, mobile, aadhaar_front, aadhaar_back, selfie, village_id, entry_by, description)
                    VALUES ('$name', '$mobile', '$aadhaar_front', '$aadhaar_back', '$selfie', '$village_id', '$admin_id', '$description')
                ");

                if (!$insert) {
                    $err = "Database error: " . $conn->error;
                } else {
                    $visitor_id = intval($conn->insert_id);
                    $conn->query("
                        INSERT INTO visitor_logs (visitor_id, village_id, checked_by, action)
                        VALUES ('$visitor_id', '$village_id', '$admin_id', 'visited')
                    ");
                    $msg = $conn->error ? "Visitor saved but visit log failed: " . $conn->error : "New visitor added successfully.";
                }
            }
        }
    }
}

$prefill_mobile = $searched_mobile ?: trim($_POST["mobile"] ?? "");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Visitor</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../assets/css/mobile-premium.css">
</head>
<body>
<div class="mobile-shell">
    <div class="mobile-header">
        <h2>Add Visitor</h2>
        <p><?= htmlspecialchars($admin_name) ?></p>
    </div>

    <?php if ($msg): ?><div class="alert success"><?= htmlspecialchars($msg) ?></div><?php endif; ?>
    <?php if ($err): ?><div class="alert error"><?= htmlspecialchars($err) ?></div><?php endif; ?>

    <div class="premium-card">
        <h3>Search Visitor First</h3>
        <form method="POST">
            <label>Mobile Number</label>
            <div class="search-row">
                <input type="text" name="search_mobile" maxlength="10" inputmode="numeric" placeholder="Enter visitor mobile" value="<?= htmlspecialchars($searched_mobile) ?>" required>
                <button type="submit" class="btn">Search</button>
            </div>
        </form>
        <div class="note">Search by mobile first. Existing records can be marked as visited without creating duplicates.</div>
    </div>

    <?php if ($foundVisitor): ?>
    <div class="premium-card">
        <h3>Existing Visitor Found</h3>
        <div class="visitor-box">
            <?php if (!empty($foundVisitor["selfie"])): ?>
                <img class="visitor-img" src="../<?= htmlspecialchars($foundVisitor["selfie"]) ?>" alt="">
            <?php else: ?>
                <div class="visitor-img" style="display:grid;place-items:center;">User</div>
            <?php endif; ?>
            <div>
                <h3 style="margin:0 0 6px;"><?= htmlspecialchars($foundVisitor["name"]) ?></h3>
                <p style="margin:4px 0;color:#667085;"><?= htmlspecialchars($foundVisitor["mobile"]) ?></p>
                <p style="margin:4px 0;color:#667085;">Villages visited: <?= intval($foundVisitor["total_villages"]) ?></p>
                <span class="badge">Existing record</span>
            </div>
        </div>

        <form method="POST">
            <input type="hidden" name="visitor_id" value="<?= intval($foundVisitor["id"]) ?>">
            <button type="submit" name="mark_existing_visit" class="btn btn-green">Mark Visit In My Village</button>
        </form>
    </div>
    <?php endif; ?>

    <div class="premium-card">
        <h3>Add New Visitor</h3>
        <form method="POST" enctype="multipart/form-data" id="visitorForm">
            <input type="hidden" name="add_new_visitor" value="1">

            <label>Visitor Name *</label>
            <input type="text" name="name" placeholder="Enter visitor name" required>

            <label>Mobile Number *</label>
            <input type="text" name="mobile" maxlength="10" inputmode="numeric" placeholder="10 digit mobile number" value="<?= htmlspecialchars($prefill_mobile) ?>" required>

            <label>Aadhaar Front</label>
            <input type="file" name="aadhaar_front" id="aadhaar_front" accept="image/*" class="js-image-upload" data-target="#aadhaar_front_path" data-status="#aadhaar_front_status">
            <input type="hidden" name="aadhaar_front_path" id="aadhaar_front_path">
            <div class="upload-status" id="aadhaar_front_status">Image will be compressed and uploaded instantly.</div>

            <label>Aadhaar Back</label>
            <input type="file" name="aadhaar_back" id="aadhaar_back" accept="image/*" class="js-image-upload" data-target="#aadhaar_back_path" data-status="#aadhaar_back_status">
            <input type="hidden" name="aadhaar_back_path" id="aadhaar_back_path">
            <div class="upload-status" id="aadhaar_back_status">Image will be compressed and uploaded instantly.</div>

            <label>Selfie *</label>
            <input type="file" name="selfie" id="selfie" accept="image/*" class="js-image-upload" data-target="#selfie_path" data-status="#selfie_status" required>
            <input type="hidden" name="selfie_path" id="selfie_path">
            <div class="upload-status" id="selfie_status">Selfie is required and uploads instantly.</div>

            <label>Description</label>
            <textarea name="description" placeholder="Purpose / note"></textarea>

            <button type="submit" class="btn" id="submitBtn">Save New Visitor</button>
        </form>
    </div>

    <?php require_once("includes/bottom-nav.php"); ?>
</div>

<script src="../assets/js/mobile-app.js"></script>
<script>
document.getElementById("visitorForm").addEventListener("submit", function(e) {
    const selfiePath = document.getElementById("selfie_path").value;
    const selfieInput = document.getElementById("selfie");
    if (selfieInput.files.length && !selfiePath) {
        e.preventDefault();
        alert("Please wait for selfie upload to complete.");
        return;
    }

    const btn = document.getElementById("submitBtn");
    btn.innerText = "Saving...";
    btn.disabled = true;
});
</script>
</body>
</html>
