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

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

$stmt = $pdo->query("
  SELECT l.*, u.username 
  FROM leave_requests l
  JOIN users u ON l.officer_id = u.id
  ORDER BY l.status DESC, l.created_at DESC
");
$requests = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Officer Leave Requests | CFS System OS</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- CSS Dependencies -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">

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

  <div class="content-wrapper">
    <section class="content-header">
      <div class="container-fluid">
        <div class="row mb-2">
          <div class="col-sm-6">
            <h1>🗂 Officer Leave Requests</h1>
          </div>
          <div class="col-sm-6">
            <ol class="breadcrumb float-sm-end">
              <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
              <li class="breadcrumb-item active">Leave Requests</li>
            </ol>
          </div>
        </div>
      </div>
    </section>

    <section class="content">
      <div class="container-fluid">
        <div class="card card-primary">
          <div class="card-body table-responsive">
            <table id="leaveTable" class="table table-bordered table-striped">
              <thead class="table-dark">
                <tr>
                  <th>Officer</th>
                  <th>Leave Type</th>
                  <th>From</th>
                  <th>To</th>
                  <th>Status</th>
                  <th>Reason</th>
                  <th>Submitted</th>
                  <th>Action</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($requests as $row): ?>
                  <?php
  $status = $row['status'];
  if ($status === 'approved') {
    $badge = 'success';
  } elseif ($status === 'rejected') {
    $badge = 'danger';
  } else {
    $badge = 'warning';
  }
?>

                  <tr>
                    <td><?= htmlspecialchars($row['username']) ?></td>
                    <td><?= htmlspecialchars($row['leave_type']) ?></td>
                    <td><?= htmlspecialchars($row['start_date']) ?></td>
                    <td><?= htmlspecialchars($row['end_date']) ?></td>
                    <td class="status-cell"><?= ucfirst($status) ?><span class="badge bg-<?= $badge ?> ms-2"><?= ucfirst($status) ?></span></td>
                    <td><?= htmlspecialchars($row['reason']) ?></td>
                    <td><?= date("d M Y", strtotime($row['created_at'])) ?></td>
                    <td class="action-cell">
                      <?php if ($status === 'pending'): ?>
                        <button class="btn btn-success btn-sm approve-btn" data-id="<?= $row['id'] ?>" data-name="<?= htmlspecialchars($row['username']) ?>">✅ Approve</button>
                        <button class="btn btn-danger btn-sm reject-btn" data-id="<?= $row['id'] ?>" data-name="<?= htmlspecialchars($row['username']) ?>">❌ Reject</button>
                      <?php else: ?>
                        <span class="text-muted">No action</span>
                      <?php endif; ?>
                    </td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </section>
  </div>
</div>

<!-- Toast Container -->
<div id="toastContainer" class="position-fixed bottom-0 end-0 p-3" style="z-index: 1055;"></div>

<!-- JS Dependencies -->
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/js/adminlte.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>

<script>
  $(document).ready(function () {
    $('#leaveTable').DataTable({
      responsive: true,
      order: [[6, 'desc']]
    });
  });

  function showToast(message, bg = 'success') {
    const id = 'toast' + Date.now();
    $('#toastContainer').append(`
      <div id="${id}" class="toast align-items-center text-white bg-${bg} border-0 mb-2" role="alert" data-bs-delay="3000">
        <div class="d-flex">
          <div class="toast-body">${message}</div>
          <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>
      </div>
    `);
    new bootstrap.Toast(document.getElementById(id)).show();
  }

  $(document).on('click', '.approve-btn, .reject-btn', function () {
    const isApprove = $(this).hasClass('approve-btn');
    const id = $(this).data('id');
    const name = $(this).data('name');
    const button = $(this);

    $.post('leave_action_ajax.php', {
      leave_id: id,
      action: isApprove ? 'approve' : 'reject'
    }, function (res) {
      if (res.success) {
        const row = button.closest('tr');
        const badgeClass = res.status === 'approved' ? 'success' : 'danger';
        const statusLabel = res.status.charAt(0).toUpperCase() + res.status.slice(1);
        row.find('.status-cell').html(`<span class="badge bg-${badgeClass}">${statusLabel}</span>`);
        row.find('.action-cell').html('<span class="text-muted">No action</span>');

        showToast(`Leave ${res.status} for ${name}`, badgeClass);
      } else {
        showToast('Failed to process leave request.', 'danger');
      }
    }, 'json');
  });
</script>
</body>
</html>
