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

$msg = "";
$err = "";
$user_id = intval($user['id']);

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $visitor_id = intval($_POST['visitor_id'] ?? 0);
    $reason = $conn->real_escape_string($_POST['reason'] ?? '');

    if (!$visitor_id || !$reason) {
        $err = "Visitor and reason required.";
    } else {
        $ins = $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())");

        if ($ins) {
            $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 = "Suspicious request sent to Village Admin.";
        } else {
            $err = "Request failed.";
        }
    }
}

$visitor_id_from_url = intval($_GET['visitor_id'] ?? 0);

$visitors = $conn->query("
    SELECT DISTINCT v.id, v.name, v.mobile 
    FROM visitors v
    JOIN visitor_logs vl ON v.id = vl.visitor_id
    WHERE vl.checked_by='$user_id'
    ORDER BY v.name ASC
");

$requests = $conn->query("
    SELECT sr.*, v.name AS visitor_name, v.mobile
    FROM suspicious_requests sr
    LEFT JOIN visitors v ON sr.visitor_id = v.id
    WHERE sr.requested_by='$user_id'
    ORDER BY sr.id DESC
");
?>

<div class="section-card">
    <h3>Create Suspicious Request</h3>

    <?php if ($msg): ?><div class="alert success"><?= $msg ?></div><?php endif; ?>
    <?php if ($err): ?><div class="alert error"><?= $err ?></div><?php endif; ?>

    <form method="POST" class="app-form">
        <label>Select Visitor</label>
        <select name="visitor_id" required>
            <option value="">Select Visitor</option>
            <?php while($v = $visitors->fetch_assoc()): ?>
                <option value="<?= $v['id'] ?>" <?= $visitor_id_from_url == $v['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($v['name']) ?> - <?= htmlspecialchars($v['mobile']) ?>
                </option>
            <?php endwhile; ?>
        </select>

        <label>Reason</label>
        <textarea name="reason" rows="4" required></textarea>

        <button class="btn-primary">Send Request</button>
    </form>
</div>

<div class="section-card">
    <h3>My Requests</h3>
</div>

<?php if ($requests && $requests->num_rows > 0): ?>
    <?php while($r = $requests->fetch_assoc()): ?>
        <div class="request-card">
            <div class="status-pill <?= htmlspecialchars($r['status']) ?>">
                <?= htmlspecialchars(str_replace("_", " ", $r['status'])) ?>
            </div>
            <h4><?= htmlspecialchars($r['visitor_name']) ?></h4>
            <p class="masked-mobile"><?= htmlspecialchars(maskMobileForVillager($r['mobile'])) ?></p>
            <p><?= htmlspecialchars($r['reason']) ?></p>
            <small><?= htmlspecialchars($r['created_at']) ?></small>
        </div>
    <?php endwhile; ?>
<?php else: ?>
    <div class="empty-state">No suspicious requests found.</div>
<?php endif; ?>

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