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

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
  header("Location: ../auth/login.php");
  exit;
}

// Fetch all leave requests with user info
$query = "
  SELECT lr.*, u.username 
  FROM leave_requests lr
  JOIN users u ON lr.officer_id = u.id
  ORDER BY lr.created_at DESC
";

$leaveData = $pdo->query($query)->fetchAll();
?>

<!DOCTYPE html>
<html>
<head>
  <title>View Leave Requests | CFS System OS</title>
  <meta charset="UTF-8">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="../assets/css/admin_dashboard.css">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body>

<?php include '../includes/topbar.php'; ?>
<?php include '../includes/sidebar.php'; ?>

<div class="main-content p-4">
  <h4>📝 Leave Applications</h4>

  <div class="table-responsive mt-3">
    <table class="table table-striped table-hover align-middle">
      <thead class="table-dark">
        <tr>
          <th>#</th>
          <th>Officer</th>
          <th>Leave Type</th>
          <th>From</th>
          <th>To</th>
          <th>Reason</th>
          <th>Status</th>
          <th>Applied On</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($leaveData as $i => $leave): ?>
        <tr>
          <td><?= $i + 1 ?></td>
          <td><?= htmlspecialchars($leave['username']) ?></td>
          <td><?= htmlspecialchars($leave['leave_type']) ?></td>
          <td><?= $leave['start_date'] ?></td>
          <td><?= $leave['end_date'] ?></td>
          <td><?= htmlspecialchars($leave['reason']) ?></td>
          <td>
            <span class="badge bg-<?= 
              $leave['status'] === 'approved' ? 'success' : 
              ($leave['status'] === 'rejected' ? 'danger' : 'warning') ?>">
              <?= ucfirst($leave['status']) ?>
            </span>
          </td>
          <td><?= $leave['created_at'] ?></td>
        </tr>
        <?php endforeach; ?>
        <?php if (empty($leaveData)): ?>
        <tr><td colspan="8" class="text-center text-muted">No leave applications found.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

</body>
</html>
