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

if (!isset($_SESSION['username']) || !in_array($_SESSION['role'], ['superadmin', 'md'])) {
    header("Location: index.php");
    exit;
}

$conn->set_charset('utf8mb4');
$username = $_SESSION['username'] ?? '';

$month = $_GET['month'] ?? date('Y-m');
if (!preg_match('/^\d{4}-\d{2}$/', $month)) $month = date('Y-m');
[$year, $mon] = explode('-', $month);

$emp_id   = $_GET['emp_id'] ?? '';
$division = $_GET['division'] ?? '';

$locked = 0;
$chk = $conn->query("SHOW TABLES LIKE 'payroll_lock'");
if ($chk && $chk->num_rows) {
    $lk = $conn->prepare("SELECT locked FROM payroll_lock WHERE month = ?");
    $lk->bind_param("s", $month);
    $lk->execute();
    $lk->bind_result($locked);
    $lk->fetch();
    $lk->close();
}

$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'approve') {
    $upd = $conn->prepare("UPDATE payroll SET status = 'approved' WHERE month = ? AND (status = 'pending' OR status IS NULL)");
    $upd->bind_param("s", $month);
    $upd->execute();
    $affected = $upd->affected_rows;
    $upd->close();
    $message = $affected > 0
        ? "success|Successfully approved $affected records for " . date('F Y', mktime(0,0,0,$mon,1,$year)) . "!"
        : "warning|No pending records found for this month.";
}

$rows = [];
$total_gross = $total_epf = $total_esi = $total_net = 0;
$pending_count = 0;

$where  = "p.month = ?";
$params = [$month];
$types  = "s";

if ($emp_id !== '') { $where .= " AND u.id = ?"; $params[] = $emp_id; $types .= "i"; }
if ($division !== '') { $where .= " AND u.division = ?"; $params[] = $division; $types .= "s"; }

$sql = "SELECT p.*, u.username AS emp_name, u.division, u.basic_salary
        FROM payroll p JOIN users u ON u.id = p.emp_id
        WHERE $where ORDER BY u.username";
$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();

$epf_final = 0; $esi = 0; $net = 0;
while ($r = $result->fetch_assoc()) {
    $rows[] = $r;
    $wd    = $r['working_days'] ?? 30;
    $base  = $r['basic_salary'] ?? 0;
    $sal   = $r['salary'] > 0 ? $r['salary'] : $base;
    $abs   = $r['absent_days'] ?? 0;
    $paid  = max($wd - $abs, 0);
    $wages = ($sal / $wd) * $paid;
    $basic = $wages * 0.40; $da = $wages * 0.20; $hra = $wages * 0.20;
    $med   = $wages * 0.10; $conv = $wages * 0.10;
    $gross = $basic + $da + $hra + $med + $conv;
    $epf_calc  = $r['epf_eligible'] ? min(($basic + $da + $hra) * 0.12, 1800) : 0;
    $epf_final = $r['epf_manual_amt'] > 0 ? $r['epf_manual_amt'] : $epf_calc;
    $esi = $r['esi_eligible'] && $gross <= 21000 ? $gross * 0.0075 : 0;
    $net = $gross + ($r['travel_allow'] ?? 0) + ($r['two_wheeler_maint'] ?? 0) + ($r['outstanding_amt'] ?? 0)
         - $epf_final - $esi - ($r['tds'] ?? 0) - ($r['advance'] ?? 0) + ($r['round_off'] ?? 0);
    $total_gross += $gross; $total_epf += $epf_final; $total_esi += $esi; $total_net += $net;
    if ($r['status'] === 'pending') $pending_count++;
}
$stmt->close();
$month_status = $rows[0]['status'] ?? 'draft';

function d($v) { return number_format(round((float)$v), 0); }

$emps = $conn->query("SELECT id, username FROM users ORDER BY username")->fetch_all(MYSQLI_ASSOC);
$divs = $conn->query("SELECT DISTINCT division FROM users WHERE division <> '' ORDER BY division")->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 · MD Payroll Approval — <?= date('F Y', mktime(0,0,0,$mon,1,$year)) ?></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">
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<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;
  --l1:#0f172a;--l2:#1d4ed8;--l3:#059669;--l4:#d97706;--l5:#dc2626;
  --radius:12px;
  --shadow:0 1px 3px rgba(15,23,42,.06),0 4px 16px rgba(15,23,42,.06);
  --shadow-md:0 4px 6px rgba(15,23,42,.07),0 12px 32px rgba(15,23,42,.10);
  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 */
.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;letter-spacing:.3px}
.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{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;transition:background .15s,color .15s}
.nav-link:hover{background:rgba(255,255,255,.07);color:#fff}
.nav-link.active{background:rgba(59,130,246,.2);color:#60a5fa}
.nav-link i{width:16px;text-align:center;font-size:13px}
.nav-link.danger{color:#f87171}
.nav-link.danger:hover{background:rgba(248,113,113,.12);color:#fca5a5}
.sidebar-footer{margin-top:auto;padding:12px;border-top:1px solid rgba(255,255,255,.06)}

/* CONTENT */
.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 */
.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 */
.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}

/* CARD */
.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow);overflow:hidden;margin-bottom:16px}
.card-pad{padding:16px}

/* FILTER BAR */
.filter-bar{display:flex;flex-wrap:wrap;gap:10px;align-items:flex-end;padding:14px 16px;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);margin-bottom:12px;box-shadow:var(--shadow)}
.filter-group{display:flex;flex-direction:column;gap:4px}
.filter-group.grow{flex:1;min-width:180px}
.filter-label{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.8px;color:var(--muted)}
.filter-select,.filter-input{height:36px;border:1px solid var(--border);border-radius:8px;padding:0 10px;font-size:13px;font-family:'Sora',sans-serif;color:var(--ink);background:var(--bg);outline:none;transition:border-color .15s,box-shadow .15s;min-width:140px}
.filter-select:focus,.filter-input:focus{border-color:#3b82f6;box-shadow:0 0 0 3px rgba(59,130,246,.12);background:var(--surface)}
.filter-btn{height:36px;padding:0 16px;border-radius:8px;border:none;cursor:pointer;font-size:12px;font-weight:600;font-family:'Sora',sans-serif;display:flex;align-items:center;gap:6px;transition:background .15s}
.btn-primary-sm{background:#0f172a;color:#fff}
.btn-primary-sm:hover{background:#1e293b}
.btn-ghost-sm{background:var(--bg);color:var(--ink-2);border:1px solid var(--border)}
.btn-ghost-sm:hover{background:var(--border)}

/* STATUS BANNER */
.status-banner{padding:12px 16px;border-radius:var(--radius);margin-bottom:12px;font-size:13px;font-weight:600;display:flex;align-items:center;gap:8px}
.banner-pending{background:#fef3c7;color:#92400e;border:1px solid #fde68a}
.banner-approved{background:#d1fae5;color:#065f46;border:1px solid #6ee7b7}
.banner-draft{background:#f1f5f9;color:var(--muted);border:1px solid var(--border)}

/* ALERT */
.alert{padding:12px 16px;border-radius:var(--radius);margin-bottom:12px;font-size:13px;font-weight:500;display:flex;align-items:center;gap:8px}
.alert-success{background:#d1fae5;color:#065f46;border:1px solid #6ee7b7}
.alert-warning{background:#fef3c7;color:#92400e;border:1px solid #fde68a}

/* NAV PILLS for month */
.month-nav{display:flex;align-items:center;gap:8px}
.mnav-btn{height:32px;padding:0 14px;border-radius:7px;border:1px solid var(--border);background:var(--surface);cursor:pointer;font-size:12px;font-weight:600;font-family:'Sora',sans-serif;color:var(--ink-2);display:flex;align-items:center;gap:5px;text-decoration:none;transition:background .15s}
.mnav-btn:hover{background:var(--bg);color:var(--ink)}
.mnav-label{font-size:14px;font-weight:700;color:var(--ink);min-width:120px;text-align:center}

/* APPROVE BTN */
.approve-btn{display:inline-flex;align-items:center;gap:8px;padding:10px 28px;border-radius:10px;background:#059669;color:#fff;border:none;cursor:pointer;font-size:14px;font-weight:700;font-family:'Sora',sans-serif;transition:background .15s;box-shadow:0 4px 12px rgba(5,150,105,.3)}
.approve-btn:hover{background:#047857}

/* TABLE */
.tbl-wrap{overflow-x:auto}
table{width:100%;border-collapse:collapse;font-size:12px}
thead th{background:var(--ink);color:rgba(255,255,255,.85);font-weight:600;font-size:10px;text-transform:uppercase;letter-spacing:.7px;padding:9px 8px;text-align:left;white-space:nowrap;position:sticky;top:0;z-index:5}
tbody td{padding:8px 8px;border-bottom:1px solid var(--border);color:var(--ink-2);vertical-align:middle}
tbody tr:last-child td{border-bottom:none}
tbody tr:hover td{background:#f8fafc}
.amt{text-align:right;font-family:'JetBrains Mono',monospace;font-weight:600}
.col-gross{color:var(--l2);font-weight:700}
.col-net{color:var(--l3);font-weight:700}
.col-ded{color:var(--l5)}

/* TOTALS FOOTER */
.totals-footer{display:grid;grid-template-columns:repeat(4,1fr);border-top:2px solid var(--border);background:var(--bg)}
.total-cell{padding:12px 16px;text-align:center;border-right:1px solid var(--border)}
.total-cell:last-child{border-right:none}
.total-cell small{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.8px;color:var(--muted);display:block;margin-bottom:2px}
.total-cell .val{font-size:18px;font-weight:700;font-family:'JetBrains Mono',monospace;color:var(--ink)}
.total-cell.net-cell .val{color:var(--l3)}

/* TOGGLE SWITCH */
.switch-sm input[type=checkbox]{width:32px;height:18px;cursor:default;opacity:.7}

@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">

<!-- SIDEBAR -->
<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">MD Portal</div>
    </div>
  </div>
  <nav class="nav-section">
    <ul style="list-style:none">
      <li class="nav-item"><a href="dashboard_md.php"              class="nav-link"><i class="fas fa-sitemap"></i> Organisation</a></li>
      <li class="nav-item"><a href="payroll_md_dashboard.php"      class="nav-link active"><i class="fas fa-money-bill"></i> Payroll</a></li>
      <li class="nav-item"><a href="daily_reports_dashboard_md.php" class="nav-link"><i class="fas fa-chart-line"></i> Reports</a></li>
      <li class="nav-item"><a href="md_leave_approval.php"         class="nav-link"><i class="fas fa-umbrella-beach"></i> Leave Approval</a></li>
      <li class="nav-item"><a href="mdmobile.php"                  class="nav-link"><i class="fas fa-mobile-alt"></i> Attendance</a></li>
      <li class="nav-item"><a href="tasks_md.php"                  class="nav-link"><i class="fas fa-tasks"></i> Tasks</a></li>
    </ul>
  </nav>
  <div class="sidebar-footer">
    <a href="logout.php" class="nav-link danger"><i class="fas fa-sign-out-alt"></i> Logout</a>
  </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>Payroll</span>
      <i class="fas fa-chevron-right" style="font-size:10px;color:var(--border)"></i>
      <span class="current">MD Approval</span>
    </div>
    <div class="topbar-spacer"></div>
    <div class="topbar-user">
      <div class="topbar-avatar"><?= strtoupper(substr($username ?: 'M', 0, 1)) ?></div>
      <?= htmlspecialchars($username ?: 'MD') ?>
    </div>
  </div>

  <div class="page">

    <div class="page-header" style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px">
      <div>
        <div class="page-title">MD Payroll Approval</div>
        <div class="page-subtitle"><?= date('F Y', mktime(0,0,0,$mon,1,$year)) ?></div>
      </div>
      <div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap">
        <div class="month-nav">
          <a href="?month=<?= date('Y-m', mktime(0,0,0,$mon-1,1,$year)) ?>" class="mnav-btn"><i class="fas fa-chevron-left"></i></a>
          <span class="mnav-label"><?= date('M Y', mktime(0,0,0,$mon,1,$year)) ?></span>
          <a href="?month=<?= date('Y-m', mktime(0,0,0,$mon+1,1,$year)) ?>" class="mnav-btn"><i class="fas fa-chevron-right"></i></a>
        </div>
        <button class="mnav-btn" onclick="window.print()"><i class="fas fa-print"></i> Print</button>
        <button class="mnav-btn" id="exportExcel"><i class="fas fa-file-excel" style="color:#059669"></i> Excel</button>
      </div>
    </div>

    <?php if ($message):
        [$mtype, $mtext] = explode('|', $message, 2); ?>
    <div class="alert alert-<?= $mtype ?>"><i class="fas fa-<?= $mtype==='success'?'check-circle':'exclamation-triangle' ?>"></i> <?= $mtext ?></div>
    <?php endif; ?>

    <!-- Filters -->
    <form method="get">
      <div class="filter-bar">
        <div class="filter-group">
          <span class="filter-label">Month</span>
          <input type="month" name="month" value="<?= htmlspecialchars($month) ?>" class="filter-input" style="min-width:150px">
        </div>
        <div class="filter-group">
          <span class="filter-label">Employee</span>
          <select name="emp_id" class="filter-select">
            <option value="">All Employees</option>
            <?php foreach($emps as $e): ?>
            <option value="<?= $e['id'] ?>" <?= $emp_id == $e['id'] ? 'selected' : '' ?>><?= htmlspecialchars($e['username']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="filter-group">
          <span class="filter-label">Division</span>
          <select name="division" class="filter-select">
            <option value="">All Divisions</option>
            <?php foreach($divs as $d): ?>
            <option <?= $division == $d['division'] ? 'selected' : '' ?>><?= htmlspecialchars($d['division']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div style="display:flex;gap:6px;align-items:flex-end">
          <button type="submit" class="filter-btn btn-primary-sm"><i class="fas fa-filter"></i> Filter</button>
          <a href="payroll_md_dashboard.php" class="filter-btn btn-ghost-sm" style="text-decoration:none"><i class="fas fa-undo"></i> Reset</a>
        </div>
      </div>
    </form>

    <!-- Status banner -->
    <?php if ($month_status === 'pending'): ?>
    <div class="status-banner banner-pending"><i class="fas fa-hourglass-half"></i> This payroll is <strong>pending MD approval</strong>.</div>
    <?php elseif ($month_status === 'approved'): ?>
    <div class="status-banner banner-approved"><i class="fas fa-check-circle"></i> This payroll has been <strong>APPROVED</strong>.</div>
    <?php else: ?>
    <div class="status-banner banner-draft"><i class="fas fa-file-alt"></i> Payroll status: <strong>Draft / Not Sent</strong></div>
    <?php endif; ?>

    <!-- Approve button -->
    <?php if ($pending_count > 0): ?>
    <div style="text-align:center;margin-bottom:16px">
      <button class="approve-btn" onclick="if(confirm('Approve all pending payroll for this month? This action cannot be undone.')) document.getElementById('approveForm').submit();">
        <i class="fas fa-check-circle"></i> APPROVE ALL (<?= $pending_count ?> pending)
      </button>
    </div>
    <?php endif; ?>

    <!-- Table -->
    <div class="card">
      <div class="tbl-wrap">
        <table id="payrollTable">
          <thead>
            <tr>
              <th>#</th><th>Employee</th><th>Division</th>
              <th class="amt">Base</th><th class="amt">Manual</th>
              <th style="text-align:center">Absent</th><th class="amt">Paid</th>
              <th class="amt">Basic</th><th class="amt">DA</th><th class="amt">HRA</th>
              <th class="amt">Med</th><th class="amt">Conv</th>
              <th class="amt">Gross</th><th class="amt">Travel</th><th class="amt">2W</th>
              <th class="amt">Outstd</th>
              <th style="text-align:center">EPF</th><th class="amt">EPF Amt</th><th class="amt">Man EPF</th>
              <th style="text-align:center">ESI</th><th class="amt">ESI Amt</th>
              <th class="amt">TDS</th><th class="amt">Adv</th><th class="amt">Round</th>
              <th class="amt">Net Pay</th>
            </tr>
          </thead>
          <tbody>
            <?php $sn = 1; foreach ($rows as $r):
              $wd    = $r['working_days'] ?? 30;
              $base  = $r['basic_salary'] ?? 0;
              $sal   = $r['salary'] > 0 ? $r['salary'] : $base;
              $abs   = $r['absent_days'] ?? 0;
              $paid  = max($wd - $abs, 0);
              $wages = $wd > 0 ? ($sal / $wd) * $paid : 0;
              $basic = $wages*.40; $da=$wages*.20; $hra=$wages*.20; $med=$wages*.10; $conv=$wages*.10;
              $gross = $basic+$da+$hra+$med+$conv;
              $epf_c = $r['epf_eligible'] ? min(($basic+$da+$hra)*.12,1800) : 0;
              $epf_f = $r['epf_manual_amt']>0 ? $r['epf_manual_amt'] : $epf_c;
              $esi   = $r['esi_eligible'] && $gross<=21000 ? $gross*.0075 : 0;
              $net   = $gross+($r['travel_allow']??0)+($r['two_wheeler_maint']??0)+($r['outstanding_amt']??0)
                      -$epf_f-$esi-($r['tds']??0)-($r['advance']??0)+($r['round_off']??0);
            ?>
            <tr>
              <td><?= $sn++ ?></td>
              <td style="font-weight:600"><?= htmlspecialchars($r['emp_name']??'-') ?></td>
              <td><?= htmlspecialchars($r['division']??'-') ?></td>
              <td class="amt"><?= d($r['basic_salary']??0) ?></td>
              <td class="amt"><?= d($r['salary']??0) ?></td>
              <td style="text-align:center"><?= $r['absent_days']??0 ?></td>
              <td class="amt"><?= d($paid) ?></td>
              <td class="amt"><?= d($basic) ?></td>
              <td class="amt"><?= d($da) ?></td>
              <td class="amt"><?= d($hra) ?></td>
              <td class="amt"><?= d($med) ?></td>
              <td class="amt"><?= d($conv) ?></td>
              <td class="amt col-gross"><?= d($gross) ?></td>
              <td class="amt"><?= d($r['travel_allow']??0) ?></td>
              <td class="amt"><?= d($r['two_wheeler_maint']??0) ?></td>
              <td class="amt"><?= d($r['outstanding_amt']??0) ?></td>
              <td style="text-align:center"><input type="checkbox" <?= $r['epf_eligible']?'checked':'' ?> disabled style="width:16px;height:16px;opacity:.7"></td>
              <td class="amt col-ded"><?= d($epf_f) ?></td>
              <td class="amt"><?= d($r['epf_manual_amt']??0) ?></td>
              <td style="text-align:center"><input type="checkbox" <?= $r['esi_eligible']?'checked':'' ?> disabled style="width:16px;height:16px;opacity:.7"></td>
              <td class="amt col-ded"><?= d($esi) ?></td>
              <td class="amt"><?= d($r['tds']??0) ?></td>
              <td class="amt"><?= d($r['advance']??0) ?></td>
              <td class="amt"><?= d($r['round_off']??0) ?></td>
              <td class="amt col-net"><?= d($net) ?></td>
            </tr>
            <?php endforeach; ?>
            <?php if (empty($rows)): ?>
            <tr><td colspan="25" style="text-align:center;padding:40px;color:var(--muted)"><i class="fas fa-inbox" style="font-size:28px;display:block;margin-bottom:8px;opacity:.4"></i>No payroll records found for this period.</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
      <div class="totals-footer">
        <div class="total-cell"><small>Total Gross</small><div class="val"><?= d($total_gross) ?></div></div>
        <div class="total-cell"><small>Total EPF</small><div class="val"><?= d($total_epf) ?></div></div>
        <div class="total-cell"><small>Total ESI</small><div class="val"><?= d($total_esi) ?></div></div>
        <div class="total-cell net-cell"><small>Net Payable</small><div class="val"><?= d($total_net) ?></div></div>
      </div>
    </div>

    <form id="approveForm" method="post" style="display:none">
      <input type="hidden" name="action" value="approve">
    </form>

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

<script>
function toggleSidebar(){
  document.getElementById('sidebar').classList.toggle('hidden');
  document.getElementById('content').classList.toggle('expanded');
}

document.getElementById('exportExcel')?.addEventListener('click', () => {
  const wb = XLSX.utils.book_new();
  const ws_data = [["#","Employee","Division","Base","Manual","Absent","Paid","Basic","DA","HRA","Med","Conv","Gross","Travel","2W","Outstd","EPF","EPF Amt","Man EPF","ESI","ESI Amt","TDS","Adv","Round","Net Pay"]];
  document.querySelectorAll('#payrollTable tbody tr').forEach((row, i) => {
    if (row.style.display === 'none') return;
    const cells = row.querySelectorAll('td');
    if (cells.length < 25) return;
    ws_data.push([i+1,...Array.from(cells).slice(1,25).map((c,idx) => {
      if (idx===15||idx===18) return c.querySelector('input')?.checked ? 'Yes' : 'No';
      return c.textContent.trim();
    })]);
  });
  const ws = XLSX.utils.aoa_to_sheet(ws_data);
  XLSX.utils.book_append_sheet(wb, ws, "Payroll <?= $month ?>");
  XLSX.writeFile(wb, `Payroll_MD_<?= $month ?>.xlsx`);
});
</script>
</body>
</html>