<?php
$page_title = 'Manager Approvals';
require_once __DIR__ . '/header.php';
if (!in_array($role, ['manager', 'admin', 'super_admin'])) redirect('index.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action_leave'])) {
    $lid = (int)$_POST['leave_id'];
    $status = $_POST['status'];
    $db->prepare("UPDATE emp_leaves SET status=?, approved_by=? WHERE id=?")->execute([$status, $emp_id, $lid]);
    redirect('approvals.php?success=1');
}

// Get pending leaves for department
$pending = $db->query("SELECT l.*, e.name as emp_name, e.emp_code FROM emp_leaves l JOIN employees e ON l.employee_id = e.id WHERE e.department='{$dept}' AND l.status='Pending' ORDER BY l.created_at DESC")->fetchAll();
?>

<div class="card">
  <h3 style="margin:0 0 16px;color:#0f172a;">Pending Leave Requests</h3>
  <?php if(isset($_GET['success'])): ?><div style="background:#dcfce7;color:#166534;padding:12px;border-radius:6px;margin-bottom:16px;">Leave status updated!</div><?php endif; ?>
  
  <div class="table-wrap">
    <table>
      <thead>
        <tr>
          <th>Employee</th>
          <th>Leave Type</th>
          <th>Dates</th>
          <th>Reason</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach($pending as $p): ?>
        <tr>
          <td><strong><?= h($p['emp_name']) ?></strong><br><span style="font-size:.8rem;color:#64748b;"><?= h($p['emp_code']) ?></span></td>
          <td><?= h($p['leave_type']) ?></td>
          <td style="font-size:.85rem;"><?= date('d M', strtotime($p['start_date'])) ?> - <?= date('d M', strtotime($p['end_date'])) ?></td>
          <td style="font-size:.85rem;max-width:200px;"><?= h($p['reason']) ?></td>
          <td>
            <form method="POST" style="display:flex;gap:8px;">
              <input type="hidden" name="action_leave" value="1">
              <input type="hidden" name="leave_id" value="<?= $p['id'] ?>">
              <button type="submit" name="status" value="Approved" style="background:#16a34a;color:#fff;border:none;padding:6px 12px;border-radius:4px;cursor:pointer;"><i class="fas fa-check"></i></button>
              <button type="submit" name="status" value="Rejected" style="background:#dc2626;color:#fff;border:none;padding:6px 12px;border-radius:4px;cursor:pointer;"><i class="fas fa-times"></i></button>
            </form>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php if(!$pending): ?>
        <tr><td colspan="5" style="text-align:center;color:#64748b;padding:20px;">No pending leave requests.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<?php require_once __DIR__ . '/footer.php'; ?>
