<?php
require_once("includes/session.php");
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once("api/config/db.php");

$token = trim($_GET["t"] ?? "");
$actorId = 0;
$actorName = "";
$actorRole = "";
$villageId = 0;

if (!empty($_SESSION["sub_admin_id"])) {
    $actorId = intval($_SESSION["sub_admin_id"]);
    $actorName = $_SESSION["sub_admin_name"] ?? "Villager";
    $actorRole = "villager";
    $villageId = intval($_SESSION["sub_admin_village_id"] ?? 0);
} elseif (!empty($_SESSION["village_admin_id"])) {
    $actorId = intval($_SESSION["village_admin_id"]);
    $actorName = $_SESSION["village_admin_name"] ?? "Village Admin";
    $actorRole = "village_admin";
    $villageId = intval($_SESSION["village_admin_village_id"] ?? 0);
}

if (!$actorId || !$villageId) {
    $_SESSION["pending_qr_token"] = $token;
    header("Location: index.php");
    exit;
}

$status = "error";
$message = "Invalid visitor QR code.";
$visitor = null;

if (preg_match('/^[a-f0-9]{48}$/', $token)) {
    $safeToken = $conn->real_escape_string($token);
    $q = $conn->query("SELECT id, name, mobile, selfie FROM visitors WHERE qr_token='$safeToken' LIMIT 1");
    if ($q && $q->num_rows > 0) {
        $visitor = $q->fetch_assoc();
        $visitorId = intval($visitor["id"]);
        $conn->query("
            INSERT INTO visitor_logs (visitor_id, village_id, checked_by, action, created_at)
            VALUES ('$visitorId', '$villageId', '$actorId', 'visited', NOW())
        ");

        if ($conn->error) {
            $message = "Scan found visitor, but visit log failed.";
        } else {
            $status = "success";
            $message = "Visit added to timeline successfully.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>QR Scan Result</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="assets/css/mobile-premium.css">
<style>
body{min-height:100vh;background:#eef3f8}
.result-card{text-align:center}
.scan-selfie{width:118px;height:118px;border-radius:32px;object-fit:cover;background:#e2e8f0;margin:0 auto 12px;display:block}
</style>
</head>
<body>
<div class="mobile-shell">
    <div class="mobile-header">
        <h2>QR Scan Result</h2>
        <p><?= htmlspecialchars($actorName) ?></p>
    </div>

    <div class="premium-card result-card">
        <?php if ($visitor && !empty($visitor["selfie"])): ?>
            <img class="scan-selfie" src="<?= htmlspecialchars($visitor["selfie"]) ?>" alt="">
        <?php else: ?>
            <div class="scan-selfie" style="display:grid;place-items:center;">GR</div>
        <?php endif; ?>

        <h2><?= $visitor ? htmlspecialchars($visitor["name"]) : "Visitor Not Found" ?></h2>
        <div class="alert <?= $status === "success" ? "success" : "error" ?>"><?= htmlspecialchars($message) ?></div>

        <?php if ($actorRole === "village_admin"): ?>
            <a class="btn" href="village-admin/visitor-detail.php?id=<?= intval($visitor["id"] ?? 0) ?>">Open Visitor Detail</a>
            <a class="btn" href="village-admin/scan-qr.php">Scan Another QR</a>
        <?php else: ?>
            <a class="btn" href="sub-admin/visitor-detail.php?id=<?= intval($visitor["id"] ?? 0) ?>">Open Visitor Detail</a>
            <a class="btn" href="sub-admin/scan-qr.php">Scan Another QR</a>
        <?php endif; ?>
    </div>
</div>
</body>
</html>
