<?php
$pageTitle = "Search Visitor";
require_once("includes/header.php");
require_once("../api/config/db.php");

$resultData = null;
$message = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $mobile = $conn->real_escape_string($_POST['mobile'] ?? '');

    if ($mobile) {
        $q = $conn->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
        ");

        if ($q && $q->num_rows > 0) {
            $resultData = $q->fetch_assoc();
        } else {
            $message = "No visitor found.";
        }
    }
}

if (isset($_POST['mark_visit'])) {
    $visitor_id = intval($_POST['visitor_id']);
    $village_id = intval($user['village_id']);
    $checked_by = intval($user['id']);

    $conn->query("INSERT INTO visitor_logs (visitor_id, village_id, checked_by, action)
        VALUES ('$visitor_id','$village_id','$checked_by','visited')");

    $message = "Visit marked successfully.";
}
?>

<div class="section-card">
    <h3>Search Visitor</h3>

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

    <form method="POST" class="search-box">
        <input type="text" name="mobile" maxlength="10" placeholder="Enter mobile number" required>
        <button class="btn-primary">Search</button>
    </form>
</div>

<?php if ($resultData): ?>
<div class="visitor-card">
    <?php if ($resultData['selfie']): ?>
        <img src="../<?= htmlspecialchars($resultData['selfie']) ?>" class="visitor-img">
    <?php endif; ?>

    <h3><?= htmlspecialchars($resultData['name']) ?></h3>
    <p>📱 <?= htmlspecialchars($resultData['mobile']) ?></p>
    <p>🏘️ Visited Villages: <?= intval($resultData['total_villages']) ?></p>

    <div class="action-row">
        <form method="POST">
            <input type="hidden" name="visitor_id" value="<?= $resultData['id'] ?>">
            <button name="mark_visit" class="btn-green">Mark Visit</button>
        </form>
        <a class="btn-warning" href="suspicious-requests.php?visitor_id=<?= $resultData['id'] ?>">Mark Suspicious</a>
    </div>
</div>
<?php endif; ?>

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