<?php
session_start();
require_once 'config.php';

// Only admin/warden
if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: admin_login.php");
    exit;
}

$stmt = $pdo->query("
    SELECT p.*, s.full_name 
    FROM passes p 
    JOIN students s ON s.unique_reg_number = p.unique_reg_number
    ORDER BY p.created_at DESC
");
$passes = $stmt->fetchAll();

$pageTitle = "Students Passes";
include_once '_header.php';
include_once '_sidebar.php';
?>

<main class="container py-4">
    <h5>Manage Passes</h5>
    <table class="table table-bordered" id="passesTable">
        <thead>
            <tr>
                <th>Student</th>
                <th>Type</th>
                <th>Reason</th>
                <th>From</th>
                <th>To</th>
                <th>Status</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($passes as $p): ?>
            <tr>
                <td><?= htmlspecialchars($p['fullName']) ?></td>
                <td><?= ucfirst($p['pass_type']) ?></td>
                <td><?= htmlspecialchars($p['reason']) ?></td>
                <td><?= $p['from_date'] ?></td>
                <td><?= $p['to_date'] ?></td>
                <td><?= ucfirst($p['status']) ?></td>
                <td>
                    <?php if($p['status'] == 'pending'): ?>
                        <a href="update_pass.php?id=<?= $p['pass_id'] ?>&action=approve" class="btn btn-success btn-sm">Approve</a>
                        <a href="update_pass.php?id=<?= $p['pass_id'] ?>&action=reject" class="btn btn-danger btn-sm">Reject</a>
                    <?php elseif($p['status'] == 'approved'): ?>
                        <a href="update_pass.php?id=<?= $p['pass_id'] ?>&action=complete" class="btn btn-warning btn-sm">Mark In</a>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</main>

<script src="https://cdn.datatables.net/1.13.8/js/jquery.dataTables.min.js"></script>
<script>
    new DataTable('#passesTable');
</script>

<?php include_once 'footer.php'; ?>
