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

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

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

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

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

$employee_id     = (int)$user['id'];
$user_role       = strtolower($user['role']);
$username_session = $_SESSION['username'] ?? $user['name'] ?? 'User';

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

$balances = ['CL'=>0,'SL'=>0];
$stmt = $conn->prepare("SELECT leave_type,balance FROM leave_balance WHERE user_id=? AND leave_type IN('CL','SL')");
$stmt->bind_param("i",$employee_id);
$stmt->execute();
$res = $stmt->get_result();
while($r=$res->fetch_assoc()) $balances[$r['leave_type']] = (int)$r['balance'];
$stmt->close();

if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action']??'')==='update_balance' && in_array($user_role,['admin','superadmin'])) {
    $emp = (int)$_POST['employee_id'];
    $cl  = (int)$_POST['cl_balance'];
    $sl  = (int)$_POST['sl_balance'];
    foreach(['CL'=>$cl,'SL'=>$sl] as $type=>$val){
        $q=$conn->prepare("INSERT INTO leave_balance(user_id,leave_type,balance) VALUES(?,?,?) ON DUPLICATE KEY UPDATE balance=VALUES(balance)");
        $q->bind_param("isi",$emp,$type,$val);
        $q->execute();
    }
    $_SESSION['message']="Leave balance updated successfully";
    header("Location: leave_dashboard.php"); exit;
}

if (isset($_GET['id'],$_GET['status']) && in_array($user_role,['admin','superadmin'])) {
    $id=(int)$_GET['id'];
    $status=$_GET['status']==='Approved'?'Approved':'Rejected';
    if($status==='Approved'){
        $q=$conn->prepare("SELECT employee_id,leave_type, IF(leave_type='Permission',0, DATEDIFF(end_date,start_date)+1) AS days FROM leave_requests WHERE id=? AND status='Pending'");
        $q->bind_param("i",$id); $q->execute();
        $lr=$q->get_result()->fetch_assoc(); $q->close();
        if($lr && in_array($lr['leave_type'],['CL','SL'])){
            $days=max(1,(int)$lr['days']);
            $b=$conn->prepare("SELECT balance FROM leave_balance WHERE user_id=? AND leave_type=?");
            $b->bind_param("is",$lr['employee_id'],$lr['leave_type']); $b->execute();
            $b->bind_result($bal); $b->fetch(); $b->close();
            if($bal < $days){ $_SESSION['error']="Insufficient {$lr['leave_type']} balance"; header("Location: leave_dashboard.php"); exit; }
            $u=$conn->prepare("UPDATE leave_balance SET balance = balance - ? WHERE user_id=? AND leave_type=?");
            $u->bind_param("iis",$days,$lr['employee_id'],$lr['leave_type']); $u->execute();
        }
    }
    $up=$conn->prepare("UPDATE leave_requests SET status=? WHERE id=?");
    $up->bind_param("si",$status,$id); $up->execute();
    $_SESSION['message']="Leave request $status";
    header("Location: leave_dashboard.php"); exit;
}

function getRequests($conn,$status,$role,$emp){
    $sql="SELECT lr.*, CONCAT(u.first_name,' ',u.last_name) AS emp_name, lr.delegate_to_name FROM leave_requests lr JOIN users u ON u.id=lr.employee_id WHERE lr.status=? ORDER BY lr.applied_on DESC";
    if(!in_array($role,['admin','superadmin'])){ $sql.=" AND lr.employee_id=?"; $s=$conn->prepare($sql); $s->bind_param("si",$status,$emp); }
    else { $s=$conn->prepare($sql); $s->bind_param("s",$status); }
    $s->execute();
    return $s->get_result()->fetch_all(MYSQLI_ASSOC);
}

$pending  = getRequests($conn,'Pending',$user_role,$employee_id);
$approved = getRequests($conn,'Approved',$user_role,$employee_id);
$rejected = getRequests($conn,'Rejected',$user_role,$employee_id);

$employees=[];
if(in_array($user_role,['admin','superadmin'])){
    $employees = $conn->query("SELECT id, CONCAT(first_name,' ',last_name) AS name FROM users WHERE role='employee' ORDER BY first_name,last_name")->fetch_all(MYSQLI_ASSOC);
}
?>
<!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 · 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=Sora:wght@300;400;500;600;700&family=JetBrains+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">
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
  --ink: #0f172a; --ink-2: #334155; --muted: #94a3b8; --border: #e2e8f0;
  --surface: #ffffff; --bg: #f1f5f9; --sidebar-bg: #0f172a; --sidebar-w: 260px;
  --radius: 12px; --shadow: 0 1px 3px rgba(15,23,42,.06), 0 4px 16px rgba(15,23,42,.06);
  font-family: 'Sora', system-ui, sans-serif;
}
html, body { height: 100%; }
body { background: var(--bg); color: var(--ink); font-size: 14px; line-height: 1.6; -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; overflow-x: hidden; transition: transform .3s cubic-bezier(.4,0,.2,1); scrollbar-width: none; }
.sidebar::-webkit-scrollbar { display: none; }
.sidebar.hidden { transform: translateX(-100%); }
.sidebar-brand { padding: 24px 20px 16px; display: flex; align-items: center; gap: 10px; border-bottom: 1px solid rgba(255,255,255,.06); margin-bottom: 8px; }
.brand-logo { width: 36px; height: 36px; background: linear-gradient(135deg, #3b82f6, #6366f1); border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 16px; font-weight: 700; color: #fff; flex-shrink: 0; }
.brand-name { font-size: 15px; font-weight: 700; color: #fff; }
.brand-sub  { font-size: 10px; color: rgba(255,255,255,.4); letter-spacing: 1.5px; text-transform: uppercase; margin-top: 1px; }
.nav-section { padding: 0 12px 6px; }
.nav-item { list-style: none; }
.nav-link, .nav-dropdown-toggle { display: flex; align-items: center; gap: 10px; padding: 8px 10px; border-radius: 8px; color: rgba(255,255,255,.65); text-decoration: none; font-size: 13px; font-weight: 500; cursor: pointer; border: none; background: none; width: 100%; text-align: left; transition: background .15s, color .15s; }
.nav-link:hover, .nav-dropdown-toggle:hover { background: rgba(255,255,255,.07); color: #fff; }
.nav-link.active { background: rgba(59,130,246,.2); color: #60a5fa; }
.nav-link i, .nav-dropdown-toggle i { width: 16px; text-align: center; font-size: 13px; }
.nav-dropdown-toggle .arrow { margin-left: auto; transition: transform .2s; font-size: 10px; }
.nav-dropdown-toggle.open .arrow { transform: rotate(180deg); }
.nav-submenu { list-style:none; overflow:hidden; max-height:0; transition:max-height .3s ease; padding-left:26px; }
.nav-submenu.open { max-height: 600px; }
.nav-submenu .nav-link { font-size: 12px; padding: 6px 10px; color: rgba(255,255,255,.5); }
.nav-submenu .nav-link:hover { color: #fff; background: rgba(255,255,255,.05); }
.sidebar-footer { margin-top: auto; padding: 12px; 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 cubic-bezier(.4,0,.2,1); }
.content.expanded { margin-left: 0; }
.topbar { height: 60px; background: var(--surface); border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 12px; padding: 0 24px; position: sticky; top: 0; z-index: 100; }
.hamburger-btn { width: 36px; height: 36px; border-radius: 8px; border: 1px solid var(--border); background: var(--surface); display: flex; align-items: center; justify-content: center; cursor: pointer; color: var(--ink-2); font-size: 15px; flex-shrink: 0; transition: background .15s; }
.hamburger-btn:hover { background: var(--bg); }
.topbar-breadcrumb { display:flex; align-items:center; gap:6px; font-size:13px; color:var(--muted); }
.topbar-breadcrumb .current { color:var(--ink); font-weight:600; }
.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, #3b82f6, #6366f1); display: flex; align-items: center; justify-content: center; color: #fff; font-size: 12px; font-weight: 700; }

.page { padding: 24px; flex: 1; }
.page-header { margin-bottom: 20px; }
.page-title  { font-size: 22px; font-weight: 700; color: var(--ink); letter-spacing: -.4px; }
.page-subtitle { font-size: 13px; color: var(--muted); margin-top: 2px; }

.alert { padding: 12px 16px; border-radius: 10px; font-size: 13px; font-weight: 500; display: flex; align-items: flex-start; gap: 10px; margin-bottom: 20px; border: 1px solid transparent; animation: fadeUp .25s ease; }
.alert-success { background: #d1fae5; border-color: #6ee7b7; color: #065f46; }
.alert-danger   { background: #fee2e2; border-color: #fca5a5; color: #991b1b; }
@keyframes fadeUp { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }

.balance-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-bottom: 24px; }
.balance-card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow); padding: 24px; text-align: center; }
.balance-card i { font-size: 32px; margin-bottom: 10px; }
.balance-card h6 { font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: .8px; color: var(--muted); margin-bottom: 6px; }
.balance-card h2 { font-size: 36px; font-weight: 700; color: var(--ink); }
.balance-cl { border-top: 3px solid #3b82f6; } .balance-cl i { color: #3b82f6; }
.balance-sl { border-top: 3px solid #ef4444; } .balance-sl i { color: #ef4444; }

.card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow); overflow: hidden; margin-bottom: 20px; }
.card-header { display: flex; align-items: center; gap: 8px; padding: 16px 20px; border-bottom: 1px solid var(--border); }
.card-title { font-size: 15px; font-weight: 700; color: var(--ink); }
.card-body { padding: 20px; }

.form-row { display: flex; flex-wrap: wrap; gap: 12px; align-items: flex-end; }
.form-group { display: flex; flex-direction: column; gap: 4px; }
.form-label { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: .8px; color: var(--muted); }
.form-select, .form-input {
  height: 38px; border: 1px solid var(--border); border-radius: 8px; padding: 0 12px;
  font-size: 13px; font-family: 'Sora', sans-serif; color: var(--ink); background: var(--bg);
  outline: none; transition: border-color .15s; min-width: 160px;
}
.form-select:focus, .form-input:focus { border-color: #3b82f6; background: var(--surface); }

.btn { display: inline-flex; align-items: center; gap: 6px; padding: 8px 16px; border-radius: 8px; border: none; font-size: 13px; font-weight: 600; font-family: 'Sora', sans-serif; cursor: pointer; transition: opacity .15s; text-decoration: none; }
.btn-primary { background: #1d4ed8; color: #fff; } .btn-primary:hover { opacity: .88; }
.btn-success { background: #059669; color: #fff; } .btn-success:hover { opacity: .88; }
.btn-danger  { background: #dc2626; color: #fff; } .btn-danger:hover  { opacity: .88; }
.btn-sm { padding: 5px 10px; font-size: 12px; border-radius: 6px; }

.tabs { display: flex; gap: 8px; margin-bottom: 16px; flex-wrap: wrap; }
.tab { padding: 9px 24px; border-radius: 50px; background: var(--bg); border: 1px solid var(--border); font-size: 13px; font-weight: 600; color: var(--ink-2); cursor: pointer; transition: all .15s; }
.tab.active { background: #1d4ed8; color: #fff; border-color: #1d4ed8; }
.tab-panel { display: none; } .tab-panel.active { display: block; }

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

.badge-status { display: inline-flex; align-items: center; padding: 3px 10px; border-radius: 20px; font-size: 11px; font-weight: 600; }
.badge-Pending  { background: #fef3c7; color: #92400e; }
.badge-Approved { background: #d1fae5; color: #065f46; }
.badge-Rejected { background: #fee2e2; color: #991b1b; }

.no-data { text-align: center; padding: 40px; color: var(--muted); }

@media (max-width: 768px) {
  .sidebar { transform: translateX(-100%); }
  .sidebar:not(.hidden) { transform: none; }
  .content { margin-left: 0; }
  .page { padding: 16px; }
}
</style>
</head>
<body>
<div class="layout">

<nav class="sidebar" id="sidebar">
  <div class="sidebar-brand">
    <div class="brand-logo">M</div>
    <div><div class="brand-name">MPC</div><div class="brand-sub">Admin Portal</div></div>
  </div>
  <nav class="nav-section">
    <ul style="list-style:none">
      <li class="nav-item"><a href="dashboard_admin.php" class="nav-link"><i class="fas fa-sitemap"></i> Organisation Chart</a></li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)"><i class="fas fa-folder-open"></i> DAP<i class="fas fa-chevron-down arrow"></i></button>
        <ul class="nav-submenu">
          <li><a href="manage_users.php"         class="nav-link"><i class="fas fa-users"></i>        Employee Details</a></li>
          <li><a href="manage_documents.php"     class="nav-link"><i class="fas fa-file-alt"></i>     Policies Rolled Out</a></li>
          <li><a href="division_designation.php" class="nav-link"><i class="fas fa-tag"></i>          Division / Designation</a></li>
          <li><a href="digital.php"              class="nav-link"><i class="fas fa-check-circle"></i> Acceptance Confirmed</a></li>
          <li><a href="change_password.php"      class="nav-link"><i class="fas fa-key"></i>          Change Password</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle open" onclick="toggleMenu(this)"><i class="fas fa-calendar-alt"></i> CAB<i class="fas fa-chevron-down arrow"></i></button>
        <ul class="nav-submenu open">
          <li><a href="attendance.php"              class="nav-link"><i class="fas fa-clock"></i>             Attendance Dashboard</a></li>
          <li><a href="payroll.php"                 class="nav-link"><i class="fas fa-money-bill"></i>        Payroll Dashboard</a></li>
          <li><a href="mobile_attendance.php"       class="nav-link"><i class="fas fa-mobile-alt"></i>       Daily Attendance Report</a></li>
          <li><a href="task_dashboard.php"          class="nav-link"><i class="fas fa-tasks"></i>            Task Dashboard</a></li>
          <li><a href="daily_reports_dashboard.php" class="nav-link"><i class="fas fa-chart-line"></i>       Daily Report Dashboard</a></li>
          <li><a href="company_holidays.php"        class="nav-link"><i class="fas fa-star"></i>             Company Holidays</a></li>
          <li><a href="hr_approval_salary.php"      class="nav-link"><i class="fas fa-hand-holding-usd"></i> Advance Dashboard</a></li>
          <li><a href="expense_dashboard.php"       class="nav-link"><i class="fas fa-receipt"></i>          Expenses Dashboard</a></li>
          <li><a href="leave_dashboard.php"         class="nav-link active"><i class="fas fa-umbrella-beach"></i> Leave Dashboard</a></li>
          <li><a href="grievance_dashboard.php"     class="nav-link"><i class="fas fa-comment-alt"></i>      Grievance Dashboard</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)"><i class="fas fa-user-tie"></i> PEP<i class="fas fa-chevron-down arrow"></i></button>
        <ul class="nav-submenu">
          <li><a href="individual_rr.php"     class="nav-link"><i class="fas fa-trophy"></i>   Individual R &amp; R</a></li>
          <li><a href="individual_kpi.php"    class="nav-link"><i class="fas fa-bullseye"></i> Individual KPI</a></li>
          <li><a href="login_credentials.php" class="nav-link"><i class="fas fa-id-card"></i>  Login Credentials</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)"><i class="fas fa-book-open"></i> L&amp;D<i class="fas fa-chevron-down arrow"></i></button>
        <ul class="nav-submenu">
          <li><a href="incident_employee.php"  class="nav-link"><i class="fas fa-exclamation-triangle"></i> Incident Portal</a></li>
          <li><a href="training_dashboard.php" class="nav-link"><i class="fas fa-chalkboard-teacher"></i>   Training Portal</a></li>
          <li><a href="rr.php"                 class="nav-link"><i class="fas fa-award"></i>                Rewards &amp; Recognition</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)"><i class="fas fa-star"></i> AAA<i class="fas fa-chevron-down arrow"></i></button>
        <ul class="nav-submenu">
          <li><a href="employee_tiy.php"      class="nav-link"><i class="fas fa-user-check"></i> Employee TIY</a></li>
          <li><a href="login_credentials.php" class="nav-link"><i class="fas fa-id-card"></i>    Login Credentials</a></li>
        </ul>
      </li>
    </ul>
  </nav>
  <div class="sidebar-footer">
    <a href="logout.php" class="nav-link" style="color:#f87171;"><i class="fas fa-sign-out-alt"></i> Logout</a>
  </div>
</nav>

<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>CAB</span>
      <i class="fas fa-chevron-right" style="font-size:10px;color:var(--border)"></i>
      <span class="current">Leave Dashboard</span>
    </div>
    <div class="topbar-spacer"></div>
    <div class="topbar-user">
      <div class="topbar-avatar"><?php echo strtoupper(substr($username_session ?: 'A', 0, 1)); ?></div>
      <?php echo h($username_session); ?>
    </div>
  </div>

  <div class="page">
    <div class="page-header">
      <div class="page-title"><?php echo in_array($user_role,['admin','superadmin']) ? 'Leave Approval Dashboard' : 'My Leave Requests'; ?></div>
      <div class="page-subtitle">Track &amp; manage leave applications</div>
    </div>

    <?php foreach(['message'=>'success','error'=>'danger'] as $k=>$c):
    if(isset($_SESSION[$k])): ?>
      <div class="alert alert-<?php echo $c; ?>">
        <i class="fas fa-<?php echo $c==='success'?'check-circle':'exclamation-circle'; ?>"></i>
        <?php echo h($_SESSION[$k]); unset($_SESSION[$k]); ?>
      </div>
    <?php endif; endforeach; ?>

    <!-- Leave Balance -->
    <div class="balance-grid">
      <div class="balance-card balance-cl">
        <i class="fas fa-calendar-check"></i>
        <h6>Casual Leave Balance</h6>
        <h2><?php echo $balances['CL']; ?></h2>
      </div>
      <div class="balance-card balance-sl">
        <i class="fas fa-user-injured"></i>
        <h6>Sick Leave Balance</h6>
        <h2><?php echo $balances['SL']; ?></h2>
      </div>
    </div>

    <!-- Configure Balance (Admin) -->
    <?php if(in_array($user_role,['admin','superadmin'])): ?>
    <div class="card">
      <div class="card-header">
        <i class="fas fa-sliders-h" style="color:var(--muted)"></i>
        <div class="card-title">Configure Employee Leave Balance</div>
      </div>
      <div class="card-body">
        <form method="POST">
          <input type="hidden" name="action" value="update_balance">
          <div class="form-row">
            <div class="form-group">
              <label class="form-label">Employee</label>
              <select name="employee_id" class="form-select" required>
                <option value="">Select Employee</option>
                <?php foreach($employees as $e): ?>
                  <option value="<?php echo $e['id']; ?>"><?php echo h($e['name']); ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="form-group">
              <label class="form-label">CL Balance</label>
              <input type="number" name="cl_balance" class="form-input" placeholder="Casual Leave" required>
            </div>
            <div class="form-group">
              <label class="form-label">SL Balance</label>
              <input type="number" name="sl_balance" class="form-input" placeholder="Sick Leave" required>
            </div>
            <div style="display:flex;align-items:flex-end;">
              <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save Balance</button>
            </div>
          </div>
        </form>
      </div>
    </div>
    <?php endif; ?>

    <!-- Tabs -->
    <div class="tabs">
      <div class="tab active" onclick="showTab('pending',this)"><i class="fas fa-clock"></i> Pending (<?php echo count($pending); ?>)</div>
      <div class="tab" onclick="showTab('approved',this)"><i class="fas fa-check"></i> Approved (<?php echo count($approved); ?>)</div>
      <div class="tab" onclick="showTab('rejected',this)"><i class="fas fa-times"></i> Rejected (<?php echo count($rejected); ?>)</div>
    </div>

    <?php
    function renderTable($rows, $role) {
        if (!$rows) { echo '<div class="no-data"><i class="fas fa-inbox" style="font-size:28px;display:block;margin-bottom:8px;"></i>No records found</div>'; return; }
        echo '<div class="table-wrap"><table class="mpc-table"><thead><tr>
          <th>Employee</th><th>Type</th><th>Date / Time</th><th>Delegate To</th>
          <th>Work Description</th><th>Reason</th><th>Applied On</th><th>Status</th>';
        if (in_array($role, ['admin','superadmin'])) echo '<th>Actions</th>';
        echo '</tr></thead><tbody>';
        foreach ($rows as $r) {
            $badge = 'badge-'.$r['status'];
            echo '<tr>
              <td>'.htmlspecialchars($r['emp_name'] ?? '').'</td>
              <td><strong>'.htmlspecialchars($r['leave_type']).'</strong></td>
              <td>'.htmlspecialchars($r['permission_date'] ?: ($r['start_date'].' – '.$r['end_date'])).'</td>
              <td>'.htmlspecialchars($r['delegate_to_name'] ?: '—').'</td>
              <td>'.htmlspecialchars($r['work_description'] ?: '—').'</td>
              <td>'.htmlspecialchars($r['reason']).'</td>
              <td style="font-size:12px;">'.date('d M Y, g:i A', strtotime($r['applied_on'])).'</td>
              <td><span class="badge-status '.$badge.'">'.htmlspecialchars($r['status']).'</span></td>';
            if (in_array($role, ['admin','superadmin'])) {
                if ($r['status'] === 'Pending') {
                    echo '<td>
                      <a class="btn btn-success btn-sm" href="?id='.$r['id'].'&status=Approved"><i class="fas fa-check"></i></a>
                      <a class="btn btn-danger btn-sm" href="?id='.$r['id'].'&status=Rejected"><i class="fas fa-times"></i></a>
                    </td>';
                } else { echo '<td style="color:var(--muted);font-size:12px;">—</td>'; }
            }
            echo '</tr>';
        }
        echo '</tbody></table></div>';
    }
    ?>

    <div class="card">
      <div class="tab-panel active" id="pending"><?php renderTable($pending, $user_role); ?></div>
      <div class="tab-panel" id="approved"><?php renderTable($approved, $user_role); ?></div>
      <div class="tab-panel" id="rejected"><?php renderTable($rejected, $user_role); ?></div>
    </div>

  </div>
</div>
</div>

<script>
function toggleSidebar() {
  document.getElementById('sidebar').classList.toggle('hidden');
  document.getElementById('content').classList.toggle('expanded');
}
function toggleMenu(btn) {
  btn.nextElementSibling.classList.toggle('open');
  btn.classList.toggle('open');
}
function showTab(id, el) {
  document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
  document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
  document.getElementById(id).classList.add('active');
  el.classList.add('active');
}
</script>
</body>
</html>