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

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

$officer_id = $_SESSION['user_id'];
$username = $_SESSION['username'] ?? 'Officer';

$stmt = $pdo->prepare("SELECT * FROM leave_requests WHERE officer_id = ? ORDER BY start_date DESC");
$stmt->execute([$officer_id]);
$leaves = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>My Leave History</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
  <style>
    body {
      background-color: #f4f7fb;
      font-family: 'Segoe UI', sans-serif;
    }
    .container {
      max-width: 960px;
    }
    .badge-warning {
      background-color: #ffc107;
    }
    .badge-success {
      background-color: #28a745;
    }
    .badge-danger {
      background-color: #dc3545;
    }
  </style>
</head>
<body>

<div class="container py-4">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h4 class="text-primary">📝 My Leave Applications</h4>
    <a href="dashboard.php" class="btn btn-outline-secondary btn-sm">← Back to Dashboard</a>
  </div>

  <div class="card">
    <div class="card-body">
      <?php if (empty($leaves)): ?>
        <p class="text-muted">You have not applied for any leave yet.</p>
      <?php else: ?>
        <div class="table-responsive">
          <table class="table table-bordered table-hover small">
            <thead class="table-dark">
              <tr>
                <th>Type</th>
                <th>Start</th>
                <th>End</th>
                <th>Reason</th>
                <th>Status</th>
                <th>Requested On</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($leaves as $leave): ?>
                <tr>
                  <td><?= ucfirst($leave['leave_type']) ?></td>
                  <td><?= $leave['start_date'] ?></td>
                  <td><?= $leave['end_date'] ?></td>
                  <td><?= htmlspecialchars($leave['reason']) ?></td>
                  <td>
                    <span class="badge 
                      <?= $leave['status'] === 'approved' ? 'badge-success' : 
                          ($leave['status'] === 'rejected' ? 'badge-danger' : 'badge-warning') ?>">
                      <?= ucfirst($leave['status']) ?>
                    </span>
                  </td>
                  <td><?= date('d M Y', strtotime($leave['created_at'] ?? $leave['start_date'])) ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>
    </div>
  </div>
</div>

</body>
</html>
