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

ini_set('display_errors', 1);
error_reporting(E_ALL);

/* ================= AUTH ================= */
if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit;
}

$stmt = $conn->prepare("
    SELECT id, role, username,
           CONCAT(COALESCE(first_name,''), ' ', COALESCE(last_name,'')) AS name
    FROM users WHERE id = ?");
$stmt->bind_param("s", $_SESSION['user_id']);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$user) { session_destroy(); header("Location: index.php"); exit; }

$manager_id   = $user['id']; // users.id is VARCHAR(11) -> always treat as STRING, never cast to int
$user_role    = strtolower($user['role']);
if ($user_role !== 'manager') { header("Location: index.php"); exit; }

/*
 * FIX (matches the proven-correct pattern from myteam.php):
 *
 * This file previously scoped every team query by ONLY
 * LOWER(u.reporting_manager) = LOWER($manager_username). Some
 * employees have reporting_manager stored as the manager's FULL
 * NAME instead of their username, so they were silently excluded
 * from Team Leave Balances, Pending/Approved/Rejected requests,
 * and the Approve/Reject actions.
 *
 * We now match on username OR full name (case-insensitive,
 * whitespace-safe), exactly like myteam.php.
 */
$manager_username = trim($user['username'] ?? ($_SESSION['username'] ?? ''));
$manager_name     = trim($user['name'] ?? '') ?: $manager_username;

function h($s){ return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8'); }

/* ================= MANAGER ACTION ================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['request_id'], $_POST['decision'])) {
    $id       = (int)$_POST['request_id'];
    $decision = $_POST['decision'];
    $comment  = substr(trim($_POST['manager_comment'] ?? ''), 0, 500);

    if (!in_array($decision, ['approve','reject'])) { header("Location: leave_dashboard_manager.php"); exit; }

    /*
     * AUTHORIZATION is enforced here via the JOIN + WHERE scoping the
     * UPDATE to this manager's own team (same pattern used in the
     * other manager pages) -- matching on reporting_manager (varchar,
     * case-insensitive) against the manager's username OR full name.
     */
    if ($decision === 'approve') {
        $stmt = $conn->prepare("UPDATE leave_requests lr JOIN users u ON u.id = lr.employee_id SET lr.manager_status = 'Approved', lr.manager_comment = ?, lr.manager_action_on = NOW(), lr.forwarded_to_admin = 1 WHERE lr.id = ? AND (LOWER(TRIM(u.reporting_manager)) = LOWER(TRIM(?)) OR LOWER(TRIM(u.reporting_manager)) = LOWER(TRIM(?))) AND lr.status = 'Pending'");
        $stmt->bind_param("siss", $comment, $id, $manager_username, $manager_name);
        $_SESSION['message'] = "Request approved and forwarded to HR.";
    } else {
        $stmt = $conn->prepare("UPDATE leave_requests lr JOIN users u ON u.id = lr.employee_id SET lr.manager_status = 'Rejected', lr.manager_comment = ?, lr.manager_action_on = NOW(), lr.status = 'Rejected' WHERE lr.id = ? AND (LOWER(TRIM(u.reporting_manager)) = LOWER(TRIM(?)) OR LOWER(TRIM(u.reporting_manager)) = LOWER(TRIM(?))) AND lr.status = 'Pending'");
        $stmt->bind_param("siss", $comment, $id, $manager_username, $manager_name);
        $_SESSION['message'] = "Request rejected.";
    }
    $stmt->execute(); $stmt->close();
    header("Location: leave_dashboard_manager.php"); exit;
}

/* ================= TEAM BALANCES ================= */
$teamBalances = [];
$balSql = $conn->prepare("SELECT u.id, CONCAT(u.first_name,' ',u.last_name) AS emp_name, lb.leave_type, lb.balance FROM users u LEFT JOIN leave_balance lb ON lb.user_id = u.id WHERE (LOWER(TRIM(u.reporting_manager)) = LOWER(TRIM(?)) OR LOWER(TRIM(u.reporting_manager)) = LOWER(TRIM(?))) ORDER BY u.first_name");
$balSql->bind_param("ss", $manager_username, $manager_name); $balSql->execute(); $resBal = $balSql->get_result();
while ($r = $resBal->fetch_assoc()) { $teamBalances[$r['id']]['name'] = $r['emp_name']; $teamBalances[$r['id']][$r['leave_type']] = (int)$r['balance']; }
$balSql->close();

/* ================= FETCH REQUESTS ================= */
function getManagerRequests($conn, $status, $manager_username, $manager_name) {
    $stmt = $conn->prepare("SELECT lr.*, CONCAT(u.first_name,' ',u.last_name) AS emp_name, CONCAT(d.first_name,' ',d.last_name) AS delegate_name FROM leave_requests lr JOIN users u ON u.id = lr.employee_id LEFT JOIN users d ON d.id = lr.delegate_to WHERE (LOWER(TRIM(u.reporting_manager)) = LOWER(TRIM(?)) OR LOWER(TRIM(u.reporting_manager)) = LOWER(TRIM(?))) AND lr.status = ? ORDER BY lr.applied_on DESC");
    $stmt->bind_param("sss", $manager_username, $manager_name, $status);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    return $result;
}

$pending  = getManagerRequests($conn, 'Pending',  $manager_username, $manager_name);
$approved = getManagerRequests($conn, 'Approved', $manager_username, $manager_name);
$rejected = getManagerRequests($conn, 'Rejected', $manager_username, $manager_name);

function renderTable($rows, $showActions = false) {
    if (empty($rows)) {
        return '<div style="text-align:center;padding:48px 24px;color:#64748b"><i class="fas fa-folder-open" style="font-size:36px;display:block;margin-bottom:12px;opacity:.3"></i><p style="font-size:14px">No records found in this category</p></div>';
    }
    $html = '<div style="overflow-x:auto"><table class="dash-table"><thead><tr><th>Employee</th><th>Type</th><th>Period</th><th>Delegate To</th><th>Reason</th><th>Work Description</th><th>Applied On</th><th>Status</th>';
    if ($showActions) $html .= '<th>Action</th>';
    $html .= '</tr></thead><tbody>';
    foreach ($rows as $row) {
        $period = $row['leave_type'] === 'Permission'
            ? date('d M Y', strtotime($row['permission_date'])) . '<br><small style="color:#64748b">' . number_format($row['permission_hours'] ?? 0, 1) . ' hrs</small>'
            : date('d M Y', strtotime($row['start_date'])) . ' – ' . date('d M Y', strtotime($row['end_date']));
        $sc = match($row['status']) { 'Approved'=>'badge-success','Rejected'=>'badge-danger',default=>'badge-warning' };
        $si = match($row['status']) { 'Approved'=>'fa-check-circle','Rejected'=>'fa-times-circle',default=>'fa-clock' };
        $html .= '<tr><td><strong>' . htmlspecialchars($row['emp_name']) . '</strong></td><td><span class="badge-custom badge-purple">' . htmlspecialchars($row['leave_type']) . '</span></td><td style="white-space:nowrap">' . $period . '</td><td>' . (!empty($row['delegate_name']) ? htmlspecialchars($row['delegate_name']) : '<span style="color:#94a3b8">—</span>') . '</td><td>' . htmlspecialchars($row['reason'] ?: '—') . '</td><td>' . htmlspecialchars($row['work_description'] ?: '—') . '</td><td style="white-space:nowrap;color:#64748b;font-size:12px">' . date('d M Y', strtotime($row['applied_on'])) . '<br>' . date('h:i A', strtotime($row['applied_on'])) . '</td><td><span class="badge-custom ' . $sc . '"><i class="fas ' . $si . '"></i> ' . $row['status'] . '</span></td>';
        if ($showActions && $row['status'] === 'Pending') {
            $html .= '<td><form method="post" style="min-width:180px"><input type="hidden" name="request_id" value="' . $row['id'] . '"><textarea name="manager_comment" class="remark-box" placeholder="Comment (optional)...">' . htmlspecialchars($row['manager_comment'] ?? '') . '</textarea><div style="display:flex;gap:6px"><button type="submit" name="decision" value="approve" class="btn-approve"><i class="fas fa-check"></i> Approve</button><button type="submit" name="decision" value="reject" class="btn-reject" onclick="return confirm(\'Reject this request?\')"><i class="fas fa-times"></i> Reject</button></div></form></td>';
        } elseif ($showActions) { $html .= '<td style="text-align:center;color:#94a3b8">—</td>'; }
        $html .= '</tr>';
    }
    $html .= '</tbody></table></div>';
    return $html;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>MPC · Team Leave Dashboard</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;1,400&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{
  --ink:#0f172a;--ink-2:#334155;--muted:#64748b;--border:#e2e8f0;
  --surface:#ffffff;--bg:#f0f4f8;--sidebar-bg:#111827;--sidebar-w:260px;
  --accent:#4f46e5;--accent-2:#06b6d4;--green:#059669;--red:#dc2626;--amber:#d97706;
  --radius:14px;--radius-sm:8px;
  --shadow:0 1px 3px rgba(15,23,42,.06),0 4px 16px rgba(15,23,42,.07);
  --shadow-md:0 4px 6px rgba(15,23,42,.07),0 12px 32px rgba(15,23,42,.10);
  font-family:'DM Sans',system-ui,sans-serif;
}
html,body{height:100%}
body{background:var(--bg);color:var(--ink);font-size:14px;-webkit-font-smoothing:antialiased}
.layout{display:flex;min-height:100vh}
.sidebar{width:var(--sidebar-w);background:var(--sidebar-bg);position:fixed;inset:0 auto 0 0;z-index:200;display:flex;flex-direction:column;overflow-y:auto;transition:transform .3s ease;scrollbar-width:none}
.sidebar::-webkit-scrollbar{display:none}
.sidebar.hidden{transform:translateX(-100%)}
.sidebar-brand{padding:22px 18px 14px;display:flex;align-items:center;gap:10px;border-bottom:1px solid rgba(255,255,255,.07);margin-bottom:6px}
.brand-logo{width:34px;height:34px;background:linear-gradient(135deg,var(--accent),var(--accent-2));border-radius:8px;display:flex;align-items:center;justify-content:center;font-weight:700;color:#fff;font-size:15px;flex-shrink:0}
.brand-name{font-size:14px;font-weight:700;color:#fff;letter-spacing:-.2px}
.brand-sub{font-size:9px;color:rgba(255,255,255,.35);letter-spacing:1.8px;text-transform:uppercase;margin-top:1px}
.nav-group-label{font-size:9px;font-weight:600;letter-spacing:1.8px;text-transform:uppercase;color:rgba(255,255,255,.25);padding:12px 18px 4px}
.nav-item{list-style:none}
.nav-link{display:flex;align-items:center;gap:9px;padding:8px 14px;margin:1px 8px;border-radius:8px;color:rgba(255,255,255,.6);text-decoration:none;font-size:13px;font-weight:500;transition:all .15s}
.nav-link:hover{background:rgba(255,255,255,.07);color:#fff}
.nav-link.active{background:rgba(79,70,229,.25);color:#a5b4fc}
.nav-link i{width:15px;text-align:center;font-size:12px;flex-shrink:0}
.nav-link.danger{color:#f87171}.nav-link.danger:hover{background:rgba(248,113,113,.1);color:#fca5a5}
.sidebar-footer{margin-top:auto;padding:10px 8px;border-top:1px solid rgba(255,255,255,.06)}
.content{flex:1;margin-left:var(--sidebar-w);min-width:0;display:flex;flex-direction:column;transition:margin .3s ease}
.content.expanded{margin-left:0}
.topbar{height:58px;background:var(--surface);border-bottom:1px solid var(--border);display:flex;align-items:center;gap:12px;padding:0 22px;position:sticky;top:0;z-index:100;box-shadow:0 1px 0 var(--border)}
.hamburger-btn{width:34px;height:34px;border-radius:8px;border:1px solid var(--border);background:transparent;display:flex;align-items:center;justify-content:center;cursor:pointer;color:var(--ink-2);font-size:14px;flex-shrink:0;transition:background .15s}
.hamburger-btn:hover{background:var(--bg)}
.topbar-breadcrumb{display:flex;align-items:center;gap:6px;font-size:12px;color:var(--muted)}
.topbar-breadcrumb .current{color:var(--ink);font-weight:600;font-size:13px}
.topbar-spacer{flex:1}
.topbar-user{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--ink-2);font-weight:500}
.topbar-avatar{width:30px;height:30px;border-radius:50%;background:linear-gradient(135deg,var(--accent),var(--accent-2));display:flex;align-items:center;justify-content:center;color:#fff;font-size:11px;font-weight:700;flex-shrink:0}
.page{padding:22px;flex:1}
.page-header{margin-bottom:22px}
.page-title{font-size:20px;font-weight:700;color:var(--ink);letter-spacing:-.4px}
.page-subtitle{font-size:13px;color:var(--muted);margin-top:2px}
.dash-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow);margin-bottom:18px}
.dash-card-header{padding:16px 18px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--border)}
.dash-card-title{font-size:14px;font-weight:700;color:var(--ink);display:flex;align-items:center;gap:7px}
.dash-card-title i{color:var(--accent);font-size:13px}
.dash-card-body{padding:16px 18px}

/* Leave Balance Grid */
.leave-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:10px}
.leave-bal-card{background:var(--bg);border:1px solid var(--border);border-radius:var(--radius-sm);padding:14px;text-align:center}
.leave-bal-card strong{display:block;font-size:13px;margin-bottom:8px;color:var(--ink)}
.leave-badge{display:inline-block;padding:3px 10px;border-radius:20px;font-size:12px;font-weight:600;margin:2px}

/* Tabs */
.leave-tabs{display:flex;gap:0;background:var(--bg);border-radius:var(--radius-sm);padding:4px;margin-bottom:18px;border:1px solid var(--border)}
.tab-btn{flex:1;padding:9px 14px;border:none;background:transparent;border-radius:6px;font-family:'DM Sans',sans-serif;font-weight:600;font-size:13px;cursor:pointer;color:var(--muted);display:flex;align-items:center;justify-content:center;gap:6px;transition:all .2s}
.tab-btn.active{background:var(--surface);color:var(--ink);box-shadow:0 2px 8px rgba(0,0,0,.08)}
.tab-count{display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;border-radius:50%;font-size:11px;font-weight:700}
.count-warn{background:#fef3c7;color:#92400e}
.count-succ{background:#d1fae5;color:#065f46}
.count-dang{background:#fee2e2;color:#991b1b}

/* Table */
.dash-table{width:100%;border-collapse:collapse;font-size:13px}
.dash-table thead th{background:#f8fafc;color:var(--muted);font-weight:600;font-size:11px;text-transform:uppercase;letter-spacing:.6px;padding:10px 14px;text-align:left;white-space:nowrap;border-bottom:2px solid var(--border)}
.dash-table tbody td{padding:10px 14px;border-bottom:1px solid var(--border);color:var(--ink-2);vertical-align:middle}
.dash-table tbody tr:last-child td{border-bottom:none}
.dash-table tbody tr:hover td{background:#fafbfc}

/* Badges */
.badge-custom{display:inline-flex;align-items:center;gap:4px;padding:3px 10px;border-radius:20px;font-size:11px;font-weight:600}
.badge-success{background:#d1fae5;color:#065f46}
.badge-warning{background:#fef3c7;color:#92400e}
.badge-danger{background:#fee2e2;color:#991b1b}
.badge-info{background:#dbeafe;color:#1e40af}
.badge-purple{background:#ede9fe;color:#5b21b6}

/* Action buttons */
.remark-box{width:100%;border:1.5px solid var(--border);border-radius:var(--radius-sm);padding:7px 10px;font-size:12px;font-family:'DM Sans',sans-serif;resize:vertical;min-height:56px;margin-bottom:6px;background:#fff;transition:border-color .15s}
.remark-box:focus{border-color:var(--accent);outline:none}
.btn-approve,.btn-reject{flex:1;padding:7px 10px;border:none;border-radius:var(--radius-sm);font-family:'DM Sans',sans-serif;font-weight:700;font-size:12px;cursor:pointer;transition:all .15s;display:inline-flex;align-items:center;justify-content:center;gap:4px}
.btn-approve{background:#d1fae5;color:#065f46}.btn-approve:hover{background:#059669;color:#fff}
.btn-reject{background:#fee2e2;color:#991b1b}.btn-reject:hover{background:#dc2626;color:#fff}

.alert-custom{padding:12px 16px;border-radius:var(--radius-sm);font-size:13px;margin-bottom:14px}
.alert-success-custom{background:#d1fae5;border-left:3px solid var(--green);color:#065f46}

/* Stats row */
.stats-row{display:grid;grid-template-columns:repeat(3,1fr);gap:14px;margin-bottom:20px}
.stat-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:16px 18px;box-shadow:var(--shadow);display:flex;align-items:center;gap:13px;border-left:4px solid transparent}
.stat-card.c-amber{border-color:var(--amber)}.stat-card.c-green{border-color:var(--green)}.stat-card.c-red{border-color:var(--red)}
.stat-icon{width:42px;height:42px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:16px;flex-shrink:0}
.c-amber .stat-icon{background:#fef3c7;color:var(--amber)}
.c-green .stat-icon{background:#d1fae5;color:var(--green)}
.c-red .stat-icon{background:#fee2e2;color:var(--red)}
.stat-num{font-size:24px;font-weight:800;color:var(--ink);line-height:1;font-family:'DM Mono',monospace}
.stat-lbl{font-size:11px;color:var(--muted);margin-top:3px;font-weight:500}

@media(max-width:768px){.sidebar{transform:translateX(-100%)}.sidebar:not(.hidden){transform:none}.content{margin-left:0}.page{padding:14px}.leave-grid{grid-template-columns:repeat(2,1fr)}.stats-row{grid-template-columns:1fr}}


/* ═══ MOBILE SIDEBAR FIX - SAME AS DASHBOARD_MANAGER ═══ */
.sidebar-overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,.55);z-index:290;backdrop-filter:blur(2px);opacity:0;transition:opacity .28s}
.sidebar-overlay.active{display:block;opacity:1}
@media(max-width:768px){
  body{overflow-x:hidden}
  .layout{min-width:0;width:100%}
  .sidebar{transform:translateX(-100%) !important;left:0;top:0;bottom:0;height:100vh;z-index:300}
  .sidebar.open{transform:translateX(0) !important}
  .content{margin-left:0 !important;width:100%;max-width:100%;min-width:0}
  .content.expanded{margin-left:0 !important}
  .topbar{padding:0 12px;gap:8px}
  .page{padding:13px !important}
  .topbar-user span{max-width:115px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
}
@media(min-width:769px){
  .sidebar{transform:translateX(0) !important}
  .sidebar-overlay.active{display:none !important;opacity:0 !important}
  .content{margin-left:var(--sidebar-w)}
}

</style>
</head>
<body>

<!-- OVERLAY -->
<div class="sidebar-overlay" id="sidebarOverlay" onclick="closeSidebar()"></div>

<div class="layout">

<!-- ═══ SIDEBAR ═══ -->
<nav class="sidebar" id="sidebar">
  <div class="sidebar-brand">
    <div class="brand-logo">M</div>
    <div>
      <div class="brand-name">MPC Portal</div>
      <div class="brand-sub">Manager</div>
    </div>
  </div>
  <div class="nav-group-label">Main</div>
  <ul style="list-style:none;padding:0">
    <li class="nav-item"><a href="dashboard_manager.php" class="nav-link"><i class="fas fa-home"></i> Dashboard</a></li>
    <li class="nav-item"><a href="myteam.php" class="nav-link"><i class="fas fa-sitemap"></i> My Team</a></li>
  </ul>
  <div class="nav-group-label">Work</div>
  <ul style="list-style:none;padding:0">
    <li class="nav-item"><a href="manager_daily_report.php" class="nav-link"><i class="fas fa-calendar-check"></i> Attendance</a></li>
    <li class="nav-item"><a href="daily_reports_manager.php" class="nav-link"><i class="fas fa-file-alt"></i> Daily Reports</a></li>
    <li class="nav-item"><a href="leave_dashboard_manager.php" class="nav-link active"><i class="fas fa-umbrella-beach"></i> Team Leaves</a></li>
    <li class="nav-item"><a href="manager_hr_leave_apply.php" class="nav-link"><i class="fas fa-plane-departure"></i> Apply Leave</a></li>
    <li class="nav-item"><a href="tasks_manager.php" class="nav-link"><i class="fas fa-tasks"></i> Tasks</a></li>
    <li class="nav-item"><a href="manager_expenses.php" class="nav-link"><i class="fas fa-receipt"></i> Claims</a></li>
   <li class="nav-item"><a href="apply_grievance_manager.php" class="nav-link"><i class="fas fa-exclamation-circle"></i> Grievance</a></li>
  </ul>
  <div class="sidebar-footer">
    <ul style="list-style:none;padding:0">
      <li class="nav-item"><a href="logout.php" class="nav-link danger" onclick="return confirm('Are you sure you want to logout?')"><i class="fas fa-right-from-bracket"></i> Logout</a></li>
    </ul>
  </div>
</nav>

<!-- ═══ CONTENT ═══ -->
<div class="content" id="content">
  <div class="topbar">
    <button class="hamburger-btn" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>
    <div class="topbar-breadcrumb">
      <span>Manager</span>
      <i class="fas fa-chevron-right" style="font-size:9px;margin:0 2px"></i>
      <span class="current">Team Leave Dashboard</span>
    </div>
    <div class="topbar-spacer"></div>
    <div class="topbar-user">
      <div class="topbar-avatar"><?= strtoupper(substr($user['name'], 0, 1)) ?></div>
      <span><?= h($user['name']) ?></span>
    </div>
  </div>

  <div class="page">
    <div class="page-header">
      <div class="page-title"><i class="fas fa-umbrella-beach" style="color:var(--accent);margin-right:8px;font-size:18px"></i>Team Leave Dashboard</div>
      <div class="page-subtitle"><?= date('l, F j, Y') ?> · Leave Management</div>
    </div>

    <?php if (isset($_SESSION['message'])): ?>
      <div class="alert-custom alert-success-custom"><i class="fas fa-check-circle me-2"></i><?= h($_SESSION['message']); unset($_SESSION['message']); ?></div>
    <?php endif; ?>

    <!-- Stats -->
    <div class="stats-row">
      <div class="stat-card c-amber">
        <div class="stat-icon"><i class="fas fa-clock"></i></div>
        <div><div class="stat-num"><?= count($pending) ?></div><div class="stat-lbl">Pending</div></div>
      </div>
      <div class="stat-card c-green">
        <div class="stat-icon"><i class="fas fa-check-circle"></i></div>
        <div><div class="stat-num"><?= count($approved) ?></div><div class="stat-lbl">Approved</div></div>
      </div>
      <div class="stat-card c-red">
        <div class="stat-icon"><i class="fas fa-times-circle"></i></div>
        <div><div class="stat-num"><?= count($rejected) ?></div><div class="stat-lbl">Rejected</div></div>
      </div>
    </div>

    <!-- Team Leave Balances -->
    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-users"></i> Team Leave Balances</div>
      </div>
      <div class="dash-card-body">
        <?php if (empty($teamBalances)): ?>
          <p style="color:var(--muted);font-size:13px">No team members found.</p>
        <?php else: ?>
          <div class="leave-grid">
            <?php foreach ($teamBalances as $empId => $b): ?>
              <div class="leave-bal-card">
                <strong><?= h($b['name']) ?></strong>
                <div style="display:flex;gap:6px;justify-content:center;flex-wrap:wrap;margin-top:8px">
                  <span class="leave-badge" style="background:#dbeafe;color:#1e40af">CL: <?= $b['CL'] ?? 0 ?></span>
                  <span class="leave-badge" style="background:#fee2e2;color:#991b1b">SL: <?= $b['SL'] ?? 0 ?></span>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Leave Requests Tabs -->
    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-inbox"></i> Leave Requests</div>
      </div>
      <div class="dash-card-body">
        <div class="leave-tabs">
          <button class="tab-btn active" onclick="switchTab('pending',this)">
            <i class="fas fa-clock"></i> Pending <span class="tab-count count-warn"><?= count($pending) ?></span>
          </button>
          <button class="tab-btn" onclick="switchTab('approved',this)">
            <i class="fas fa-check"></i> Approved <span class="tab-count count-succ"><?= count($approved) ?></span>
          </button>
          <button class="tab-btn" onclick="switchTab('rejected',this)">
            <i class="fas fa-times"></i> Rejected <span class="tab-count count-dang"><?= count($rejected) ?></span>
          </button>
        </div>
        <div id="tab-pending"><?= renderTable($pending, true) ?></div>
        <div id="tab-approved" style="display:none"><?= renderTable($approved, false) ?></div>
        <div id="tab-rejected" style="display:none"><?= renderTable($rejected, false) ?></div>
      </div>
    </div>
  </div>
</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
function toggleSidebar() {
  const sb = document.getElementById('sidebar');
  const ov = document.getElementById('sidebarOverlay');
  if (!sb || !ov) return;
  const isOpen = sb.classList.contains('open');
  sb.classList.toggle('open', !isOpen);
  ov.classList.toggle('active', !isOpen);
}
function closeSidebar() {
  const sb = document.getElementById('sidebar');
  const ov = document.getElementById('sidebarOverlay');
  if (sb) sb.classList.remove('open');
  if (ov) ov.classList.remove('active');
}
document.addEventListener('keydown', function(e) {
  if (e.key === 'Escape') closeSidebar();
});
document.addEventListener('DOMContentLoaded', function() {
  document.querySelectorAll('#sidebar .nav-link').forEach(function(a) {
    a.addEventListener('click', function() {
      if (window.innerWidth <= 768) closeSidebar();
    });
  });
});
function switchTab(name, btn) {
  ['pending','approved','rejected'].forEach(t => {
    document.getElementById('tab-'+t).style.display = (t===name) ? 'block' : 'none';
  });
  document.querySelectorAll('.leave-tabs .tab-btn').forEach(b => b.classList.remove('active'));
  btn.classList.add('active');
}
</script>
</body>
</html>