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

require_once("../includes/session.php");
session_start();
require_once("../api/config/db.php");

if (!isset($_SESSION['sub_admin_id'])) {
    header("Location: login.php");
    exit;
}

$user_id = intval($_SESSION['sub_admin_id']);
$user_name = $_SESSION['sub_admin_name'] ?? 'Sub Admin';
$village_id = intval($_SESSION['sub_admin_village_id'] ?? 0);

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

function maskMobileForVillager($mobile) {
    $digits = preg_replace("/\D/", "", (string) $mobile);
    if (strlen($digits) <= 5) return $digits;
    return substr($digits, 0, 5) . "XXXXX";
}

function uploadVisitorImage($field) {
    if (empty($_FILES[$field]['name']) || $_FILES[$field]['error'] !== 0) 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)) return null;

    $filename = time() . "_" . rand(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;
}

/* SEARCH VISITOR */
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.";
        }
    }
}

/* MARK EXISTING 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', '$user_id', 'visited')
        ");

        if ($conn->error) {
            $err = "Visit log failed: " . $conn->error;
        } else {
            $msg = "Visitor marked as visited in your village.";
        }
    }
}

/* ADD NEW VISITOR */
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', '$user_id', 'visited')
            ");

            if ($conn->error) {
                $err = "Visit log failed: " . $conn->error;
            } else {
                $msg = "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', '$user_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', '$user_id', 'visited')
                    ");

                    if ($conn->error) {
                        $err = "Visitor saved but visit log failed: " . $conn->error;
                    } else {
                        $msg = "New visitor added successfully.";
                    }
                }
            }
        }
    }
}

$prefill_mobile = $searched_mobile;
if (!$prefill_mobile && isset($_POST['mobile'])) {
    $prefill_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">

<style>
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
html,body{margin:0;padding:0;width:100%;min-height:100%;font-family:Arial,sans-serif;background:#edf2f7;color:#0f172a}
body{overflow-x:hidden}
.app{max-width:520px;margin:0 auto;min-height:100vh;background:#f8fafc;padding-bottom:96px}
.header{
    background:linear-gradient(135deg,#07111f,#123c88,#0ea5e9);
    color:white;
    padding:24px 18px 34px;
    border-bottom-left-radius:32px;
    border-bottom-right-radius:32px;
}
.header h2{margin:0;font-size:26px;line-height:1.2}
.header p{margin:7px 0 0;color:#dbeafe;font-size:14px}
.card{
    background:white;
    margin:16px;
    padding:18px;
    border-radius:26px;
    box-shadow:0 14px 35px rgba(15,23,42,.08);
}
.card h3{margin:0 0 15px;font-size:20px}
label{display:block;margin:14px 0 8px;font-size:14px;font-weight:800;color:#334155}
input,textarea{
    width:100%;
    border:1px solid #dbeafe;
    border-radius:18px;
    padding:14px 16px;
    font-size:15px;
    outline:none;
    background:#f8fafc;
    color:#0f172a;
}
input{min-height:54px}
textarea{min-height:100px;resize:vertical}
input[type=file]{height:auto;background:white;padding:14px}
input:focus,textarea:focus{
    border-color:#2563eb;
    background:#fff;
    box-shadow:0 0 0 4px rgba(37,99,235,.12);
}
.btn{
    width:100%;
    min-height:56px;
    border:0;
    border-radius:20px;
    margin-top:16px;
    background:linear-gradient(135deg,#2563eb,#06b6d4);
    color:white;
    font-size:17px;
    font-weight:900;
    cursor:pointer;
    box-shadow:0 14px 30px rgba(37,99,235,.32);
}
.btn-green{background:linear-gradient(135deg,#16a34a,#22c55e);box-shadow:0 14px 30px rgba(22,163,74,.25)}
.alert{
    padding:14px 16px;
    border-radius:18px;
    margin:16px;
    font-size:14px;
    font-weight:800;
    text-align:center;
    line-height:1.4;
}
.success{background:#dcfce7;color:#166534}
.error{background:#fee2e2;color:#991b1b}
.note{margin-top:7px;font-size:12px;color:#64748b;line-height:1.4}
.search-row{display:grid;grid-template-columns:1fr 112px;gap:10px;align-items:end}
.search-row .btn{margin-top:0}
.visitor-box{display:flex;gap:14px;align-items:center}
.visitor-img{
    width:86px;
    height:86px;
    border-radius:26px;
    object-fit:cover;
    background:#e2e8f0;
    flex-shrink:0;
}
.visitor-info h4{margin:0 0 6px;font-size:20px}
.visitor-info p{margin:4px 0;color:#475569;font-size:14px}
.badge{
    display:inline-block;
    padding:7px 11px;
    border-radius:999px;
    background:#eff6ff;
    color:#1e40af;
    font-size:12px;
    font-weight:900;
    margin-top:6px;
}
.form-title{display:flex;justify-content:space-between;align-items:center;gap:10px;margin-bottom:4px}
.form-title h3{margin:0}
.form-title span{font-size:12px;color:#64748b;text-align:right}
.nav{
    position:fixed;
    bottom:0;
    left:50%;
    transform:translateX(-50%);
    max-width:520px;
    width:100%;
    background:white;
    display:grid;
    grid-template-columns:repeat(5,1fr);
    padding:10px 4px 12px;
    box-shadow:0 -10px 30px rgba(0,0,0,.08);
    z-index:10;
}
.nav a{text-align:center;text-decoration:none;color:#64748b;font-size:20px}
.nav span{display:block;font-size:11px;font-weight:700;margin-top:3px}
.nav a.active{color:#2563eb}
@media(max-width:480px){
    .app{max-width:100%}
    .header{border-bottom-left-radius:28px;border-bottom-right-radius:28px}
    .card{margin:14px;padding:18px;border-radius:24px}
    .search-row{grid-template-columns:1fr}
    .search-row .btn{width:100%}
    .visitor-box{align-items:flex-start}
}
</style>
<link rel="stylesheet" href="../assets/css/mobile-premium.css">
</head>

<body>
<div class="app">

<div class="header">
    <h2>Add Visitor</h2>
    <p><?= htmlspecialchars($user_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="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. If data already exists from another village, simply mark the visitor as visited in your village.
    </div>
</div>

<?php if ($foundVisitor): ?>
<div class="card">
    <h3>Existing Visitor Found</h3>

    <div class="visitor-box">
        <?php if (!empty($foundVisitor['selfie'])): ?>
            <img class="visitor-img" src="../<?= htmlspecialchars($foundVisitor['selfie']) ?>">
        <?php else: ?>
            <div class="visitor-img" style="display:grid;place-items:center;">👤</div>
        <?php endif; ?>

        <div class="visitor-info">
            <h4><?= htmlspecialchars($foundVisitor['name']) ?></h4>
            <p class="masked-mobile"><?= htmlspecialchars(maskMobileForVillager($foundVisitor['mobile'])) ?></p>
            <p>🏘️ Villages visited: <?= intval($foundVisitor['total_villages']) ?></p>
            <p>🕒 Last visit: <?= htmlspecialchars($foundVisitor['last_visit'] ?? '-') ?></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">
            He Visited My Village
        </button>
    </form>
</div>
<?php endif; ?>

<div class="card">
    <div class="form-title">
        <h3>Add New Visitor</h3>
        <span>Use only if not found</span>
    </div>

    <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="note 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="note 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="note upload-status" id="selfie_status">Selfie is required and will be compressed and uploaded 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>

<div class="nav">
    <a href="dashboard.php"><span class="nav-icon"><svg viewBox="0 0 24 24"><path d="M3 11l9-8 9 8"/><path d="M5 10v10h14V10"/><path d="M9 20v-6h6v6"/></svg></span><span>Home</span></a>
    <a href="add-visitor.php" class="active"><span class="nav-icon"><svg viewBox="0 0 24 24"><path d="M12 5v14"/><path d="M5 12h14"/></svg></span><span>Add</span></a>
    <a href="search-visitor.php"><span class="nav-icon"><svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="7"/><path d="M20 20l-3.5-3.5"/></svg></span><span>Search</span></a>
    <a href="my-visitors.php"><span class="nav-icon"><svg viewBox="0 0 24 24"><path d="M8 6h13"/><path d="M8 12h13"/><path d="M8 18h13"/><path d="M3 6h.01"/><path d="M3 12h.01"/><path d="M3 18h.01"/></svg></span><span>List</span></a>
    <a href="profile.php"><span class="nav-icon"><svg viewBox="0 0 24 24"><path d="M20 21a8 8 0 0 0-16 0"/><circle cx="12" cy="7" r="4"/></svg></span><span>Profile</span></a>
</div>

</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>
