<?php
require_once("includes/auth.php");
require_once("../api/config/db.php");
require_once("../includes/visitor_qr.php");

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

$visitor_id = intval($_GET["id"] ?? 0);
$user_id = intval($user["id"] ?? 0);
$village_id = intval($user["village_id"] ?? 0);

if (!$visitor_id) {
    die("Visitor ID required");
}

$q = $conn->query("
SELECT
    v.*,
    u1.name AS entry_by_name,
    vg.village_name
FROM visitors v
LEFT JOIN users u1 ON v.entry_by = u1.id
LEFT JOIN villages vg ON v.village_id = vg.id
LEFT JOIN visitor_logs own_log ON own_log.visitor_id = v.id AND own_log.village_id = '$village_id'
WHERE v.id='$visitor_id'
AND (v.village_id='$village_id' OR v.entry_by='$user_id' OR own_log.id IS NOT NULL)
LIMIT 1
");

if (!$q || $q->num_rows === 0) {
    die("Visitor not found");
}

$data = $q->fetch_assoc();

$canManageQr = intval($data["entry_by"] ?? 0) === $user_id;
$qrMessage = "";
if ($canManageQr && $_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["verify_mobile"])) {
    if (visitorQrColumnExists($conn, "mobile_verified_at")) {
        $conn->query("UPDATE visitors SET mobile_verified_at=NOW() WHERE id='$visitor_id' LIMIT 1");
        $qrMessage = $conn->error ? "Mobile verification update failed." : "Visitor mobile marked as verified.";
        $q = $conn->query("
        SELECT
            v.*,
            u1.name AS entry_by_name,
            vg.village_name
        FROM visitors v
        LEFT JOIN users u1 ON v.entry_by = u1.id
        LEFT JOIN villages vg ON v.village_id = vg.id
        LEFT JOIN visitor_logs own_log ON own_log.visitor_id = v.id AND own_log.village_id = '$village_id'
        WHERE v.id='$visitor_id'
        AND (v.village_id='$village_id' OR v.entry_by='$user_id' OR own_log.id IS NOT NULL)
        LIMIT 1
        ");
        $data = $q->fetch_assoc();
    } else {
        $qrMessage = "Please run database_updates_visitor_qr.sql first.";
    }
}

$qrToken = $canManageQr ? visitorQrEnsureToken($conn, $visitor_id) : "";
$qrReady = $qrToken !== "";
$qrImageUrl = $qrReady ? visitorQrImageUrl($qrToken) : "";
$qrScanUrl = $qrReady ? visitorQrScanUrl($qrToken) : "";
$qrWhatsappUrl = $qrReady ? visitorQrWhatsappShareUrl($data["mobile"], $data["name"], $qrToken) : "";

$timeline = $conn->query("
SELECT
    vl.created_at,
    vl.action,
    vlg.village_name,
    u.name AS checked_by_name
FROM visitor_logs vl
LEFT JOIN villages vlg ON vl.village_id = vlg.id
LEFT JOIN users u ON vl.checked_by = u.id
WHERE vl.visitor_id='$visitor_id'
ORDER BY vl.created_at DESC
");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Visitor Detail</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../assets/css/mobile-premium.css">
<style>
.selfie{width:120px;height:120px;border-radius:32px;object-fit:cover;background:#e2e8f0;margin:0 auto 12px;display:block}
.doc-img{width:100%;height:150px;object-fit:cover;border-radius:18px;background:#e2e8f0}
.img-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px}
.timeline{position:relative;padding-left:18px}
.timeline:before{content:"";position:absolute;left:5px;top:4px;bottom:4px;width:2px;background:#bfdbfe}
.t-item{position:relative;margin-bottom:14px;background:#f8fafc;padding:12px;border-radius:16px}
.t-item:before{content:"";position:absolute;left:-17px;top:16px;width:10px;height:10px;background:#2563eb;border-radius:50%}
.qr-img{width:220px;height:220px;display:block;margin:10px auto;border-radius:18px;background:#fff;border:1px solid #e5e7eb}
.share-row{display:grid;grid-template-columns:1fr;gap:10px}
</style>
</head>
<body>
<div class="mobile-shell">
    <div class="mobile-header">
        <a href="my-visitors.php" style="color:#fff;font-weight:800;">Back</a>
        <h2>Visitor Detail</h2>
        <p>Private documents are blurred for Villagers</p>
    </div>

    <div class="premium-card" style="text-align:center;">
        <?php if (!empty($data["selfie"])): ?>
            <img class="selfie" src="../<?= htmlspecialchars($data["selfie"]) ?>" alt="">
        <?php else: ?>
            <div class="selfie" style="display:grid;place-items:center;">User</div>
        <?php endif; ?>
        <h2><?= htmlspecialchars($data["name"]) ?></h2>
        <p class="masked-mobile"><?= htmlspecialchars(maskMobileForVillager($data["mobile"])) ?></p>
        <span class="badge"><?= !empty($data["is_suspicious"]) ? "Suspicious" : "Normal Visitor" ?></span>
    </div>

    <?php if ($canManageQr): ?>
    <div class="premium-card">
        <h3>Visitor QR Code</h3>
        <?php if ($qrMessage): ?><div class="alert success"><?= htmlspecialchars($qrMessage) ?></div><?php endif; ?>

        <?php if ($qrReady): ?>
            <img class="qr-img" src="<?= htmlspecialchars($qrImageUrl) ?>" alt="Visitor QR Code">
            <div class="row"><span>Mobile Verified</span><b><?= !empty($data["mobile_verified_at"]) ? htmlspecialchars($data["mobile_verified_at"]) : "Not yet" ?></b></div>
            <form method="POST">
                <button class="btn" type="submit" name="verify_mobile" value="1">Mark Mobile Verified</button>
            </form>
            <div class="share-row">
                <a class="btn" href="<?= htmlspecialchars($qrWhatsappUrl) ?>" target="_blank" rel="noopener">Share QR On WhatsApp</a>
                <button class="btn" type="button" onclick="shareVisitorQr()">Share From Mobile</button>
            </div>
            <p class="note">WhatsApp opens with the visitor mobile and QR link. The user confirms send inside WhatsApp.</p>
        <?php else: ?>
            <div class="alert error">Please run database_updates_visitor_qr.sql first to enable QR codes.</div>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <div class="premium-card">
        <h3>Visitor Information</h3>
        <div class="row"><span>Village</span><b><?= htmlspecialchars($data["village_name"] ?? "-") ?></b></div>
        <div class="row"><span>Entry By</span><b><?= htmlspecialchars($data["entry_by_name"] ?? "Unknown") ?></b></div>
        <div class="row"><span>Description</span><b><?= htmlspecialchars($data["description"] ?? "-") ?></b></div>
    </div>

    <div class="premium-card">
        <h3>Documents</h3>
        <div class="img-grid">
            <div>
                <p><b>Aadhaar Front</b></p>
                <?php if (!empty($data["aadhaar_front"])): ?>
                    <img class="doc-img blur-doc" src="../<?= htmlspecialchars($data["aadhaar_front"]) ?>" alt="">
                <?php else: ?>
                    <div class="empty">No front image</div>
                <?php endif; ?>
            </div>
            <div>
                <p><b>Aadhaar Back</b></p>
                <?php if (!empty($data["aadhaar_back"])): ?>
                    <img class="doc-img blur-doc" src="../<?= htmlspecialchars($data["aadhaar_back"]) ?>" alt="">
                <?php else: ?>
                    <div class="empty">No back image</div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="premium-card">
        <h3>Visit Timeline</h3>
        <?php if ($timeline && $timeline->num_rows > 0): ?>
            <div class="timeline">
                <?php while($t = $timeline->fetch_assoc()): ?>
                    <div class="t-item">
                        <h4><?= htmlspecialchars($t["village_name"] ?? "Unknown Village") ?></h4>
                        <p>Checked by: <?= htmlspecialchars($t["checked_by_name"] ?? "Unknown") ?></p>
                        <p>Action: <?= htmlspecialchars($t["action"] ?? "visited") ?></p>
                        <p>Time: <?= htmlspecialchars($t["created_at"]) ?></p>
                    </div>
                <?php endwhile; ?>
            </div>
        <?php else: ?>
            <div class="empty">No visit timeline found.</div>
        <?php endif; ?>
    </div>

    <div class="bottom-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"><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" class="active"><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>
async function shareVisitorQr() {
    const shareData = {
        title: "Gram Rakshak Visitor QR",
        text: "Scan this Gram Rakshak QR to record the visitor entry.",
        url: "<?= htmlspecialchars($qrScanUrl, ENT_QUOTES) ?>"
    };
    if (navigator.share) {
        await navigator.share(shareData);
    } else {
        window.open("<?= htmlspecialchars($qrWhatsappUrl, ENT_QUOTES) ?>", "_blank");
    }
}
</script>
</body>
</html>
