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

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

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

$user_id = intval($_SESSION['sub_admin_id']);

/* ================= USER DATA ================= */
$userRes = $conn->query("SELECT id, name, village_id FROM users WHERE id='$user_id' LIMIT 1");
$user = $userRes ? $userRes->fetch_assoc() : null;

if (!$user) {
    die("User not found");
}

$user_name = $user['name'];
$village_id = intval($user['village_id']);

$msg = "";
$err = "";

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

/* ================= SEND SUSPICIOUS ================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_suspicious'])) {

    $visitor_id = intval($_POST['visitor_id'] ?? 0);
    $reason = $conn->real_escape_string(trim($_POST['reason'] ?? ''));

    if (!$visitor_id || !$reason) {
        $err = "Reason is required.";
    } else {

        $check = $conn->query("
            SELECT id FROM suspicious_requests 
            WHERE visitor_id='$visitor_id'
            AND requested_by='$user_id'
            AND status IN ('pending','approved_by_village')
        ");

        if ($check && $check->num_rows > 0) {
            $err = "Request already under review.";
        } else {

            $conn->query("
                INSERT INTO suspicious_requests
                (visitor_id, requested_by, requested_role, reason, status, created_at)
                VALUES
                ('$visitor_id','$user_id','sub_admin','$reason','pending',NOW())
            ");

            $request_id = $conn->insert_id;

            $conn->query("
                INSERT INTO suspicious_history
                (request_id, action_by, role, action, note, created_at)
                VALUES
                ('$request_id','$user_id','sub_admin','requested','$reason',NOW())
            ");

            $msg = "Request sent to Village Admin.";
        }
    }
}

/* ================= FIXED QUERY ================= */
$q = $conn->query("
    SELECT 
        v.id,

        MAX(v.name) AS name,
        MAX(v.mobile) AS mobile,
        MAX(v.selfie) AS selfie,
        MAX(v.description) AS description,
        MAX(v.entry_by) AS entry_by,

        COALESCE(MAX(u.name), 'Unknown') AS entry_by_name,

        COUNT(DISTINCT vl.id) AS total_visits,
        MAX(vl.created_at) AS last_visit,

        MAX(sr.id) AS suspicious_request_id,
        MAX(sr.status) AS suspicious_status,
        MAX(sr.reason) AS suspicious_reason

    FROM visitors v

    LEFT JOIN visitor_logs vl 
        ON vl.visitor_id = v.id 
        AND vl.village_id = '$village_id'

    LEFT JOIN users u 
        ON v.entry_by = u.id

    LEFT JOIN suspicious_requests sr 
        ON sr.id = (
            SELECT MAX(sr2.id)
            FROM suspicious_requests sr2
            WHERE sr2.visitor_id = v.id
            AND sr2.requested_by = '$user_id'
        )

    WHERE 
        v.village_id = '$village_id'
        OR vl.village_id = '$village_id'
        OR v.entry_by = '$user_id'

    GROUP BY v.id
    ORDER BY last_visit DESC
");

if (!$q) {
    $err = "Query error: " . $conn->error;
}
?>

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Village Visitors</title>
<link rel="stylesheet" href="../assets/css/mobile-premium.css">

<style>
body{margin:0;font-family:system-ui;background:#f1f5f9}
.app{max-width:520px;margin:auto;background:#fff;min-height:100vh;padding-bottom:90px}

.header{
background:linear-gradient(135deg,#0f172a,#1e3a8a,#0ea5e9);
color:#fff;padding:25px;border-radius:0 0 30px 30px
}

.card{
background:#fff;margin:15px;padding:15px;border-radius:20px;
box-shadow:0 10px 25px rgba(0,0,0,0.08)
}

.visitor{
display:flex;gap:10px
}

.visitor img{
width:70px;height:70px;border-radius:15px;object-fit:cover
}

.btn{
display:block;padding:10px;margin-top:8px;
border:none;border-radius:10px;color:#fff;font-weight:bold
}

.primary{background:#2563eb}
.danger{background:#dc2626}
.disabled{background:#cbd5e1}

.badge{
display:inline-block;padding:4px 8px;
border-radius:20px;font-size:12px;margin-top:5px
}

.review{background:#fef3c7}
.sent{background:#e0f2fe}
.rejected{background:#fee2e2}
</style>
<link rel="stylesheet" href="../assets/css/mobile-premium.css">
</head>

<body>

<div class="app">

<div class="header">
<h2>Village Visitors</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; ?>

<?php if ($q && $q->num_rows > 0): ?>
<?php while($row = $q->fetch_assoc()): ?>

<div class="card">
<div class="visitor">

<?php if($row['selfie']): ?>
<img src="../<?= htmlspecialchars($row['selfie']) ?>" alt="">
<?php else: ?>
<div style="width:70px;height:70px;background:#ddd;border-radius:15px"></div>
<?php endif; ?>

<div style="flex:1">
<b><?= htmlspecialchars($row['name']) ?></b><br>
<span class="masked-mobile"><?= htmlspecialchars(maskMobileForVillager($row['mobile'])) ?></span><br>

Visits: <?= $row['total_visits'] ?><br>
Last: <?= $row['last_visit'] ?><br>

Added by: <?= htmlspecialchars($row['entry_by_name']) ?><br>

<?php if($row['suspicious_status']): ?>
<span class="badge"><?= $row['suspicious_status'] ?></span>
<?php endif; ?>

<a href="visitor-detail.php?id=<?= intval($row['id']) ?>" class="btn primary">View</a>

<?php if(!$row['suspicious_request_id']): ?>
<button class="btn danger" onclick="openModal(<?= $row['id'] ?>)">Mark Suspicious</button>
<?php else: ?>
<button class="btn disabled">Under Review</button>
<?php endif; ?>

</div>
</div>
</div>

<?php endwhile; ?>
<?php else: ?>
<div class="card">No visitors 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>

<!-- Modal -->
<div id="modal" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:#0008">
<div style="background:#fff;padding:20px;margin:100px auto;width:90%;max-width:400px;border-radius:20px">
<form method="POST">
<input type="hidden" name="send_suspicious" value="1">
<input type="hidden" name="visitor_id" id="visitor_id">

<textarea name="reason" placeholder="Reason..." required style="width:100%"></textarea>

<button class="btn danger">Send</button>
<button type="button" onclick="closeModal()">Cancel</button>
</form>
</div>
</div>

<script src="../assets/js/mobile-app.js"></script>
<script>
function openModal(id){
document.getElementById("visitor_id").value=id;
document.getElementById("modal").style.display="block";
}
function closeModal(){
document.getElementById("modal").style.display="none";
}
</script>

</body>
</html>
