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

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

$conn->set_charset('utf8mb4');
$is_admin   = in_array($_SESSION['role'], ['admin','superadmin']);
$is_md      = $_SESSION['role'] === 'superadmin';
$cur_user   = $_SESSION['username'];
$username_session = $_SESSION['username'] ?? '';

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

/* ─── FILTERS ─────────────────────────────────────────────────── */
$month      = $_GET['month']      ?? date('Y-m');
$month_from = $_GET['month_from'] ?? $month;
$month_to   = $_GET['month_to']   ?? $month;
$emp_id     = $_GET['emp_id']     ?? '';
$division   = $_GET['division']   ?? '';
$msg        = $_GET['msg']        ?? '';

/* ─── PAYROLL LOCK ─────────────────────────────────────────────── */
$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();
}

/* ─── HELPERS ──────────────────────────────────────────────────── */
function audit($conn, $month, $action, $user, $notes='') {
    $tbl = $conn->query("SHOW TABLES LIKE 'payroll_audit'");
    if (!$tbl || !$tbl->num_rows) return;
    $s = $conn->prepare("INSERT INTO payroll_audit (month,action,performed_by,notes,created_at) VALUES (?,?,?,?,NOW())");
    $s->bind_param("ssss",$month,$action,$user,$notes); $s->execute(); $s->close();
}

/* ─── MD APPROVE ───────────────────────────────────────────────── */
if (!$locked && isset($_POST['md_approve']) && $is_md) {
    $upd=$conn->prepare("UPDATE payroll SET status='approved',reject_reason=NULL WHERE month=? AND status='pending'");
    $upd->bind_param("s",$month); $upd->execute(); $upd->close();
    audit($conn,$month,'approved',$cur_user,'MD approved payroll');
    header("Location: payroll.php?month=$month&msg=approved"); exit;
}

/* ─── MD REJECT ────────────────────────────────────────────────── */
if (!$locked && isset($_POST['reject_payroll']) && $is_md) {
    $reason=trim($_POST['reject_reason']??'');
    $upd=$conn->prepare("UPDATE payroll SET status='draft',reject_reason=? WHERE month=?");
    $upd->bind_param("ss",$reason,$month); $upd->execute(); $upd->close();
    audit($conn,$month,'rejected',$cur_user,$reason);
    header("Location: payroll.php?month=$month&msg=rejected"); exit;
}

/* ─── SEND FOR APPROVAL ────────────────────────────────────────── */
if (!$locked && isset($_POST['send_approval'])) {
    $upd=$conn->prepare("UPDATE payroll SET status='pending',reject_reason=NULL WHERE month=? AND (status IS NULL OR status='draft')");
    $upd->bind_param("s",$month); $upd->execute(); $upd->close();
    audit($conn,$month,'submitted',$cur_user,'Sent for MD approval');
    header("Location: payroll.php?month=$month&emp_id=$emp_id&division=$division"); exit;
}

/* ─── GLOBAL WORKING DAYS ──────────────────────────────────────── */
if ($is_admin && !$locked && isset($_POST['update_working_days'])) {
    $wd=max((int)$_POST['working_days'],1);
    $u=$conn->prepare("UPDATE payroll SET working_days=?,paid_days=GREATEST(?-absent_days,0) WHERE month=?");
    $u->bind_param("iis",$wd,$wd,$month); $u->execute(); $u->close();
    header("Location: payroll.php?month=$month&emp_id=$emp_id&division=$division"); exit;
}

/* ─── SAVE SINGLE ROW ──────────────────────────────────────────── */
if (!$locked && isset($_POST['save_row'])) {
    $id=(int)$_POST['id'];
    $salary=(float)($_POST['salary']??0); $absent=(int)($_POST['absent_days']??0);
    $travel=(float)($_POST['travel_allow']??0); $tw=(float)($_POST['two_wheeler_maint']??0);
    $out=(float)($_POST['outstanding_amt']??0); $tds=(float)($_POST['tds']??0);
    $advance=(float)($_POST['advance']??0); $round=(float)($_POST['round_off']??0);
    $bonus=(float)($_POST['bonus']??0); $incentive=(float)($_POST['incentive']??0);
    $epf_elg=isset($_POST['epf_eligible'])?1:0; $esi_elg=isset($_POST['esi_eligible'])?1:0;
    $epf_man=(float)($_POST['epf_manual_amt']??0);
    $q=$conn->prepare("SELECT working_days,salary FROM payroll WHERE id=?");
    $q->bind_param("i",$id); $q->execute(); $q->bind_result($wd,$cur_sal); $q->fetch(); $q->close();
    $eff_sal=$salary>0?$salary:$cur_sal; $paid=max($wd-$absent,0);
    $lop_amt=$wd>0?round(($eff_sal/$wd)*$absent,2):0;
    $u=$conn->prepare("UPDATE payroll SET salary=?,absent_days=?,paid_days=?,travel_allow=?,two_wheeler_maint=?,outstanding_amt=?,tds=?,advance=?,round_off=?,epf_eligible=?,epf_manual_amt=?,esi_eligible=?,bonus=?,incentive=?,lop_amount=? WHERE id=?");
    $u->bind_param("diidddddidiiiddi",$salary,$absent,$paid,$travel,$tw,$out,$tds,$advance,$round,$epf_elg,$epf_man,$esi_elg,$bonus,$incentive,$lop_amt,$id);
    $u->execute(); $u->close();
    header("Location: payroll.php?month=$month&emp_id=$emp_id&division=$division"); exit;
}

/* ─── LOOKUP DATA ──────────────────────────────────────────────── */
$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);

/* ─── PAYROLL DATA ─────────────────────────────────────────────── */
$where="p.month BETWEEN ? AND ?"; $params=[$month_from,$month_to]; $types="ss";
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_username,u.first_name,u.last_name,u.division,u.basic_salary,u.id AS emp_id FROM payroll p JOIN users u ON u.id=p.emp_id WHERE $where ORDER BY p.month,u.username";
$st=$conn->prepare($sql); $st->bind_param($types,...$params); $st->execute();
$rows=$st->get_result()->fetch_all(MYSQLI_ASSOC); $st->close();

$cur_rows=array_values(array_filter($rows,fn($r)=>$r['month']===$month));
$global_wd=$cur_rows[0]['working_days']??30;
$month_status=$cur_rows[0]['status']??'draft';
$reject_reason=$cur_rows[0]['reject_reason']??'';

/* ─── AUDIT LOG ─────────────────────────────────────────────────── */
$audit_rows=[];
$at=$conn->query("SHOW TABLES LIKE 'payroll_audit'");
if ($at&&$at->num_rows) {
    $al=$conn->prepare("SELECT action,performed_by,notes,created_at FROM payroll_audit WHERE month=? ORDER BY created_at DESC LIMIT 20");
    $al->bind_param("s",$month); $al->execute();
    $audit_rows=$al->get_result()->fetch_all(MYSQLI_ASSOC); $al->close();
}

function disp($v){ return number_format((float)$v,0,'.',''); }
function statusBadge($s){
    return match($s){
        'approved'=>'<span class="status-badge badge-approved"><i class="fas fa-check-circle"></i> Approved</span>',
        'pending' =>'<span class="status-badge badge-pending"><i class="fas fa-hourglass-half"></i> Pending Approval</span>',
        'rejected'=>'<span class="status-badge badge-rejected"><i class="fas fa-times-circle"></i> Rejected</span>',
        default   =>'<span class="status-badge badge-draft"><i class="fas fa-edit"></i> Draft</span>',
    };
}
?>
<!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 · Payroll <?= h($month) ?></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;
  --radius:12px;--shadow:0 1px 3px rgba(15,23,42,.06),0 4px 16px rgba(15,23,42,.06);
  --accent:#3b82f6;--success:#10b981;--danger:#ef4444;--warn:#f59e0b;
  font-family:'Sora',system-ui,sans-serif;
}
html,body{height:100%;}
body{background:var(--bg);color:var(--ink);font-size:13px;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;}
.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 ── */
.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-actions{display:flex;align-items:center;gap:8px;}
.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;display:flex;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;gap:12px;}
.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;}

/* ── ALERTS ── */
.alert-box{padding:12px 16px;border-radius:var(--radius);font-size:13px;font-weight:500;display:flex;align-items:center;gap:10px;margin-bottom:16px;}
.alert-success{background:#d1fae5;border:1px solid #6ee7b7;color:#065f46;}
.alert-danger{background:#fee2e2;border:1px solid #fca5a5;color:#991b1b;}
.alert-info{background:#dbeafe;border:1px solid #93c5fd;color:#1e40af;}

/* ── STATUS BADGES ── */
.status-badge{display:inline-flex;align-items:center;gap:5px;padding:4px 10px;border-radius:20px;font-size:11px;font-weight:700;}
.badge-approved{background:#d1fae5;color:#065f46;}
.badge-pending{background:#fef3c7;color:#92400e;}
.badge-rejected{background:#fee2e2;color:#991b1b;}
.badge-draft{background:#dbeafe;color:#1e40af;}

/* ── STATUS/ACTION BAR ── */
.action-bar{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:12px 18px;margin-bottom:16px;display:flex;flex-wrap:wrap;gap:12px;align-items:center;box-shadow:var(--shadow);}
.reject-banner{background:#fef2f2;border:1px solid #fca5a5;border-radius:var(--radius);padding:10px 14px;margin-bottom:12px;font-size:13px;color:#991b1b;}

/* ── FILTER CARD ── */
.filter-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:14px 18px;margin-bottom:16px;box-shadow:var(--shadow);}
.filter-row{display:flex;flex-wrap:wrap;gap:10px;align-items:flex-end;}
.filter-group{display:flex;flex-direction:column;gap:4px;}
.filter-label{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.8px;color:var(--muted);}
.form-ctrl{padding:7px 10px;border:1px solid var(--border);border-radius:8px;font-size:13px;font-family:'Sora',sans-serif;color:var(--ink);background:var(--bg);outline:none;transition:border-color .15s;}
.form-ctrl:focus{border-color:var(--accent);box-shadow:0 0 0 3px rgba(59,130,246,.1);background:var(--surface);}

/* ── BUTTONS ── */
.btn{display:inline-flex;align-items:center;gap:6px;padding:7px 14px;border-radius:8px;font-size:12px;font-weight:600;cursor:pointer;transition:all .15s;border:none;font-family:'Sora',sans-serif;text-decoration:none;white-space:nowrap;}
.btn-primary{background:var(--accent);color:#fff;}
.btn-primary:hover{background:#1d4ed8;color:#fff;}
.btn-success{background:var(--success);color:#fff;}
.btn-success:hover{background:#047857;color:#fff;}
.btn-warn{background:var(--warn);color:#fff;}
.btn-warn:hover{background:#b45309;color:#fff;}
.btn-danger{background:var(--danger);color:#fff;}
.btn-danger:hover{background:#b91c1c;color:#fff;}
.btn-ghost{background:transparent;color:var(--ink-2);border:1px solid var(--border);}
.btn-ghost:hover{background:var(--bg);color:var(--ink);}
.btn-sm{padding:5px 10px;font-size:11px;}

/* ── SEARCH ── */
.search-wrap{position:relative;}
.search-wrap input{padding:7px 10px 7px 32px;border:1px solid var(--border);border-radius:8px;font-size:13px;font-family:'Sora',sans-serif;background:var(--bg);color:var(--ink);outline:none;transition:all .15s;width:220px;}
.search-wrap input:focus{border-color:var(--accent);background:var(--surface);box-shadow:0 0 0 3px rgba(59,130,246,.1);}
.search-wrap .si{position:absolute;left:10px;top:50%;transform:translateY(-50%);color:var(--muted);font-size:11px;}

/* ── TABLE ── */
.table-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);overflow:hidden;box-shadow:var(--shadow);margin-bottom:20px;}
.table-scroll{overflow:auto;max-height:60vh;position:relative;}
.pay-table{width:100%;border-collapse:separate;border-spacing:0;font-size:12px;}
.pay-table thead th{position:sticky;top:0;z-index:10;background:#1e293b;color:rgba(255,255,255,.85);padding:8px 6px;font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;white-space:nowrap;border-bottom:2px solid #334155;text-align:center;}
.pay-table tbody td{padding:7px 6px;vertical-align:middle;border-bottom:1px solid var(--border);}
.pay-table tbody tr:last-child td{border-bottom:none;}
.pay-table tbody tr:hover{background:#f8faff;}
.pay-table tbody tr.selected-row{background:#eff6ff;}
.input-xs{width:68px;font-size:11px;padding:3px 5px;border:1px solid var(--border);border-radius:5px;text-align:right;font-family:'JetBrains Mono',monospace;background:var(--bg);color:var(--ink);outline:none;transition:border-color .15s;}
.input-xs:focus{border-color:var(--accent);box-shadow:0 0 0 2px rgba(59,130,246,.1);background:var(--surface);}
.amount{text-align:right;font-family:'JetBrains Mono',monospace;}
.gross{color:#1d4ed8;font-weight:600;}
.net-col{color:#059669;font-weight:700;}
.add-col{color:#16a34a;}
.deduct{color:#dc2626;}
.lop-col{color:#b45309;font-weight:600;}

/* ── TOTALS FOOTER ── */
.totals-bar{display:flex;flex-wrap:wrap;gap:0;border-top:2px solid var(--border);background:rgba(248,250,252,.98);position:sticky;bottom:0;}
.total-cell{flex:1;min-width:80px;padding:10px 8px;text-align:center;border-right:1px solid var(--border);}
.total-cell:last-child{border-right:none;}
.total-label{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:var(--muted);}
.total-value{font-family:'JetBrains Mono',monospace;font-size:14px;font-weight:700;margin-top:2px;}

/* ── DIVISION CARDS ── */
.div-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:12px;margin-bottom:20px;}
.div-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:14px;box-shadow:var(--shadow);}
.div-card-title{font-weight:700;font-size:12px;margin-bottom:8px;color:var(--accent);}
.div-stat{display:flex;justify-content:space-between;font-size:11px;color:var(--muted);margin-bottom:2px;}
.div-stat strong{color:var(--ink);}

/* ── MODAL ── */
.modal-overlay{display:none;position:fixed;inset:0;background:rgba(15,23,42,.5);z-index:300;align-items:center;justify-content:center;backdrop-filter:blur(4px);}
.modal-overlay.show{display:flex;}
.modal-box{background:var(--surface);border-radius:var(--radius);width:90%;max-width:520px;overflow:hidden;box-shadow:0 20px 60px rgba(0,0,0,.2);}
.modal-head{display:flex;align-items:center;gap:8px;padding:16px 20px;background:var(--ink);color:#fff;}
.modal-head-title{font-size:14px;font-weight:700;flex:1;}
.modal-body{padding:20px;}
.modal-foot{padding:12px 20px;border-top:1px solid var(--border);background:var(--bg);display:flex;gap:8px;justify-content:flex-end;}
.btn-close-modal{background:none;border:none;color:rgba(255,255,255,.6);font-size:18px;cursor:pointer;padding:0;}
.form-group{margin-bottom:14px;}
.form-label{display:block;font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.8px;color:var(--muted);margin-bottom:5px;}
.form-input{width:100%;padding:8px 10px;border:1px solid var(--border);border-radius:8px;font-size:13px;font-family:'Sora',sans-serif;color:var(--ink);background:var(--bg);outline:none;}
.form-input:focus{border-color:var(--accent);box-shadow:0 0 0 3px rgba(59,130,246,.1);background:var(--surface);}
textarea.form-input{height:auto;resize:vertical;}

/* ── AUDIT TIMELINE ── */
.timeline-item{border-left:3px solid var(--border);padding:8px 12px;margin-bottom:8px;border-radius:0 6px 6px 0;}
.timeline-item.approved{border-color:var(--success);}
.timeline-item.rejected{border-color:var(--danger);}
.timeline-item.submitted{border-color:var(--warn);}

/* ── PRINT ── */
@media print{.sidebar,.topbar,.filter-card,.action-bar,.no-print{display:none!important;}.content{margin-left:0!important;}.table-scroll{max-height:none;overflow:visible;}.totals-bar{position:static;}}
@media (max-width:768px){.sidebar{transform:translateX(-100%);}.sidebar:not(.hidden){transform:none;}.content{margin-left:0;}.page{padding:14px;}.filter-row{flex-direction:column;}.div-grid{grid-template-columns:repeat(2,1fr);}}
</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">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="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 active"><i class="fas fa-money-bill"></i> Payroll 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="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"><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="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>

<!-- ── 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>CAB</span>
      <i class="fas fa-chevron-right" style="font-size:9px;color:var(--border)"></i>
      <span class="current">Payroll Dashboard</span>
    </div>
    <div class="topbar-spacer"></div>
    <div class="topbar-actions">
      <a href="dashboard_admin.php" class="btn btn-ghost btn-sm"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
      <a href="attendance.php?month=<?= urlencode($month) ?>" class="btn btn-ghost btn-sm"><i class="fas fa-calendar-check"></i> Attendance</a>
      <button id="btnPrint" class="btn btn-ghost btn-sm"><i class="fas fa-print"></i> Print</button>
      <button id="btnExportExcel" class="btn btn-ghost btn-sm"><i class="fas fa-file-excel"></i> Excel</button>
      <?php if(count($audit_rows)): ?>
      <button onclick="document.getElementById('auditModal').classList.add('show')" class="btn btn-ghost btn-sm"><i class="fas fa-history"></i> Audit</button>
      <?php endif; ?>
    </div>
    <div class="topbar-user">
      <div class="topbar-avatar"><?= strtoupper(substr($username_session ?: 'A', 0, 1)) ?></div>
      <?= h($username_session ?: 'Admin') ?>
    </div>
  </div>

  <div class="page">
    <div class="page-header">
      <div>
        <div class="page-title"><i class="fas fa-wallet" style="color:var(--accent);margin-right:8px;"></i>Payroll Management</div>
        <div class="page-subtitle">Month: <?= h($month) ?> &nbsp; <?= statusBadge($month_status) ?></div>
      </div>
      <div style="display:flex;align-items:center;gap:8px;">
        <label style="display:flex;align-items:center;gap:6px;font-size:12px;color:var(--ink-2);cursor:pointer;">
          <input type="checkbox" id="showFullName" checked> Full Name
        </label>
        <button id="btnBulkPrint" class="btn btn-ghost btn-sm"><i class="fas fa-file-pdf"></i> Bulk Payslip</button>
      </div>
    </div>

    <?php if ($msg==='approved'): ?>
    <div class="alert-box alert-success"><i class="fas fa-check-circle"></i> Payroll approved successfully.</div>
    <?php elseif ($msg==='rejected'): ?>
    <div class="alert-box alert-danger"><i class="fas fa-times-circle"></i> Payroll rejected and sent back to draft.</div>
    <?php endif; ?>

    <?php if ($month_status==='draft' && $reject_reason): ?>
    <div class="reject-banner"><i class="fas fa-exclamation-circle"></i> <strong>Rejected by MD:</strong> <?= h($reject_reason) ?></div>
    <?php endif; ?>

    <!-- ACTION BAR -->
    <div class="action-bar">
      <?php if ($is_admin && !$locked && $month_status==='draft'): ?>
      <form method="post" style="display:flex;align-items:center;gap:8px;">
        <label style="font-size:12px;font-weight:700;color:var(--ink-2);">Working Days:</label>
        <input type="number" name="working_days" value="<?= $global_wd ?>" min="1" class="form-ctrl" style="width:70px;">
        <button name="update_working_days" class="btn btn-primary btn-sm">Update</button>
      </form>
      <?php endif; ?>
      <?php if (!$locked && $month_status==='draft'): ?>
      <form method="post">
        <button name="send_approval" class="btn btn-warn btn-sm" onclick="return confirm('Send this month payroll for MD approval?')">
          <i class="fas fa-paper-plane"></i> Send for MD Approval
        </button>
      </form>
      <?php endif; ?>
      <?php if ($is_md && $month_status==='pending'): ?>
      <form method="post" style="display:flex;gap:8px;">
        <button name="md_approve" class="btn btn-success btn-sm" onclick="return confirm('Approve this payroll?')"><i class="fas fa-check"></i> Approve</button>
        <button type="button" class="btn btn-danger btn-sm" onclick="document.getElementById('rejectModal').classList.add('show')"><i class="fas fa-times"></i> Reject</button>
      </form>
      <?php endif; ?>
      <?php if ($locked || $month_status==='approved'): ?>
      <span style="color:var(--success);font-weight:700;font-size:13px;"><i class="fas fa-lock"></i> Payroll Locked &amp; Approved</span>
      <?php endif; ?>
    </div>

    <!-- FILTERS -->
    <div class="filter-card">
      <form class="filter-row" id="filterForm">
        <div class="filter-group">
          <span class="filter-label">Active Month</span>
          <input type="month" name="month" value="<?= h($month) ?>" class="form-ctrl">
        </div>
        <div class="filter-group">
          <span class="filter-label">From</span>
          <input type="month" name="month_from" value="<?= h($month_from) ?>" class="form-ctrl">
        </div>
        <div class="filter-group">
          <span class="filter-label">To</span>
          <input type="month" name="month_to" value="<?= h($month_to) ?>" class="form-ctrl">
        </div>
        <div class="filter-group">
          <span class="filter-label">Employee</span>
          <select name="emp_id" class="form-ctrl">
            <option value="">All Employees</option>
            <?php foreach($emps as $e): ?><option value="<?= $e['id'] ?>" <?= $emp_id==$e['id']?'selected':'' ?>><?= h($e['username']) ?></option><?php endforeach; ?>
          </select>
        </div>
        <div class="filter-group">
          <span class="filter-label">Division</span>
          <select name="division" class="form-ctrl">
            <option value="">All Divisions</option>
            <?php foreach($divs as $d): ?><option <?= $division==$d['division']?'selected':'' ?>><?= h($d['division']) ?></option><?php endforeach; ?>
          </select>
        </div>
        <div class="filter-group">
          <span class="filter-label">Quick Search</span>
          <div class="search-wrap">
            <i class="fas fa-search si"></i>
            <input type="text" id="quickSearch" placeholder="Name / ID…" autocomplete="off">
          </div>
        </div>
        <div style="display:flex;gap:8px;align-items:flex-end;">
          <button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-filter"></i> Filter</button>
          <a href="payroll.php" class="btn btn-ghost btn-sm"><i class="fas fa-undo"></i> Reset</a>
          <span id="visibleCount" style="font-size:11px;color:var(--muted);align-self:center;"></span>
        </div>
      </form>
    </div>

    <!-- PAYROLL TABLE -->
    <div class="table-card">
      <div class="table-scroll">
        <table class="pay-table" id="payrollTable">
          <thead>
            <tr>
              <th class="no-print" style="width:20px"><input type="checkbox" id="selectAll" title="Select all"></th>
              <th>#</th><th>ID</th><th style="min-width:160px;">Name</th><th>Div</th>
              <th class="amount">Base</th><th class="amount">Manual</th>
              <th class="text-center">Absent</th><th class="amount lop-col">LOP</th><th class="amount">Paid</th>
              <th class="amount">Basic</th><th class="amount">DA</th><th class="amount">HRA</th><th class="amount">Med</th><th class="amount">Conv</th>
              <th class="amount add-col">Bonus</th><th class="amount add-col">Incentive</th>
              <th class="amount gross">Gross</th>
              <th class="amount">Travel</th><th class="amount">2W</th><th class="amount">Outstd</th>
              <th>EPF</th><th class="amount deduct">EPF Amt</th><th class="amount">Man EPF</th>
              <th>ESI</th><th class="amount deduct">ESI Amt</th>
              <th class="amount deduct">TDS</th><th class="amount deduct">Adv</th><th class="amount">Round</th>
              <th class="amount net-col">Net Pay</th>
              <th class="no-print">Act</th>
            </tr>
          </thead>
          <tbody id="payrollBody">
          <?php $sn=1; foreach($rows as $r):
            $full_name=trim(($r['first_name']??'').' '.($r['last_name']??''));
            if(empty($full_name)) $full_name=$r['emp_username']??'Unknown';
            $short_name=$r['emp_username'].' ('.$r['emp_id'].')';
            $long_name=$full_name.' ('.$r['emp_id'].')';
            $is_draft=($r['status']??'draft')==='draft';
            $editable=!$locked&&$is_draft;
          ?>
          <tr class="pay-row"
              data-id="<?= $r['id'] ?>" data-month="<?= h($r['month']) ?>"
              data-working="<?= $r['working_days']??30 ?>" data-basic="<?= $r['basic_salary']??0 ?>"
              data-division="<?= h(strtolower($r['division']??'')) ?>"
              data-name="<?= h(strtolower($long_name)) ?>"
              data-shortname="<?= h(strtolower($short_name)) ?>"
              data-username="<?= h(strtolower($r['emp_username']??'')) ?>"
              data-empid="<?= h(strtolower($r['emp_id'])) ?>">
            <form method="post">
            <input type="hidden" name="id" value="<?= $r['id'] ?>">
            <input type="hidden" name="month" value="<?= h($r['month']) ?>">
            <td class="no-print text-center"><input type="checkbox" class="row-cb" data-id="<?= $r['id'] ?>"></td>
            <td style="text-align:center;font-size:11px;color:var(--muted);font-family:'JetBrains Mono',monospace"><?= $sn++ ?></td>
            <td style="font-family:'JetBrains Mono',monospace;font-size:11px;"><?= h($r['emp_id']) ?></td>
            <td class="emp-name"><?= h($long_name) ?></td>
            <td style="font-size:11px;"><?= h($r['division']??'-') ?></td>
            <td class="amount" style="font-size:11px;"><?= disp($r['basic_salary']??0) ?></td>
            <td><input name="salary" class="input-xs salary" value="<?= disp($r['salary']??0) ?>" step="any" <?= !$editable?'disabled':'' ?>></td>
            <td><input name="absent_days" class="input-xs absent" style="text-align:center;" value="<?= $r['absent_days']??0 ?>" <?= !$editable?'disabled':'' ?>></td>
            <td class="amount lop-col lop">—</td>
            <td class="amount paid" style="font-weight:700;">—</td>
            <td class="amount basic">—</td><td class="amount da">—</td>
            <td class="amount hra">—</td><td class="amount med">—</td><td class="amount conv">—</td>
            <td><input name="bonus" class="input-xs bonus add-col" value="<?= disp($r['bonus']??0) ?>" step="any" <?= !$editable?'disabled':'' ?>></td>
            <td><input name="incentive" class="input-xs incentive add-col" value="<?= disp($r['incentive']??0) ?>" step="any" <?= !$editable?'disabled':'' ?>></td>
            <td class="amount gross">—</td>
            <td><input name="travel_allow" class="input-xs travel" value="<?= disp($r['travel_allow']??0) ?>" step="any" <?= !$editable?'disabled':'' ?>></td>
            <td><input name="two_wheeler_maint" class="input-xs tw" value="<?= disp($r['two_wheeler_maint']??0) ?>" step="any" <?= !$editable?'disabled':'' ?>></td>
            <td><input name="outstanding_amt" class="input-xs out" value="<?= disp($r['outstanding_amt']??0) ?>" step="any" <?= !$editable?'disabled':'' ?>></td>
            <td style="text-align:center;"><input class="epf_chk" type="checkbox" name="epf_eligible" <?= $r['epf_eligible']?'checked':'' ?> <?= !$editable?'disabled':'' ?>></td>
            <td class="amount deduct epf-amt">—</td>
            <td><input name="epf_manual_amt" class="input-xs epf-man" value="<?= disp($r['epf_manual_amt']??0) ?>" step="any" <?= !$editable?'disabled':'' ?>></td>
            <td style="text-align:center;"><input class="esi_chk" type="checkbox" name="esi_eligible" <?= $r['esi_eligible']?'checked':'' ?> <?= !$editable?'disabled':'' ?>></td>
            <td class="amount deduct esi-amt">—</td>
            <td><input name="tds" class="input-xs tds deduct" value="<?= disp($r['tds']??0) ?>" step="any" <?= !$editable?'disabled':'' ?>></td>
            <td><input name="advance" class="input-xs adv deduct" value="<?= disp($r['advance']??0) ?>" step="any" <?= !$editable?'disabled':'' ?>></td>
            <td><input name="round_off" class="input-xs round" value="<?= disp($r['round_off']??0) ?>" step="any" <?= !$editable?'disabled':'' ?>></td>
            <td class="amount net-col">—</td>
            <td class="no-print" style="white-space:nowrap;">
              <?php if($editable): ?><button type="submit" name="save_row" class="btn btn-success btn-sm" title="Save"><i class="fas fa-save"></i></button><?php endif; ?>
              <a href="payslip_new.php?id=<?= $r['id'] ?>" class="btn btn-primary btn-sm" target="_blank" title="Payslip"><i class="fas fa-file-invoice"></i></a>
            </td>
            </form>
          </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
      <div class="totals-bar">
        <div class="total-cell"><div class="total-label">Employees</div><div class="total-value" id="tcount" style="color:var(--accent)">0</div></div>
        <div class="total-cell"><div class="total-label">LOP</div><div class="total-value" id="tlop" style="color:var(--warn)">0</div></div>
        <div class="total-cell"><div class="total-label">Gross</div><div class="total-value" id="tg">0</div></div>
        <div class="total-cell"><div class="total-label">Bonus+Inc</div><div class="total-value" id="tbonus" style="color:var(--success)">0</div></div>
        <div class="total-cell"><div class="total-label">EPF</div><div class="total-value" id="tep" style="color:var(--danger)">0</div></div>
        <div class="total-cell"><div class="total-label">ESI</div><div class="total-value" id="tes" style="color:var(--danger)">0</div></div>
        <div class="total-cell" style="background:#d1fae5;"><div class="total-label">NET PAY</div><div class="total-value" id="tn" style="color:var(--success)">0</div></div>
      </div>
    </div>

    <!-- DIVISION SUMMARY -->
    <div style="margin-bottom:12px;font-weight:700;font-size:14px;display:flex;align-items:center;gap:8px;">
      <i class="fas fa-chart-pie" style="color:var(--accent)"></i> Division Summary
    </div>
    <div class="div-grid" id="divisionTotals"></div>

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

<!-- ── REJECT MODAL ── -->
<div class="modal-overlay" id="rejectModal">
  <div class="modal-box" style="max-width:440px">
    <div class="modal-head" style="background:#991b1b;">
      <i class="fas fa-times-circle"></i>
      <div class="modal-head-title">Reject Payroll</div>
      <button class="btn-close-modal" onclick="document.getElementById('rejectModal').classList.remove('show')">×</button>
    </div>
    <form method="post">
      <div class="modal-body">
        <div class="form-group">
          <label class="form-label">Reason for Rejection <span style="color:var(--danger)">*</span></label>
          <textarea name="reject_reason" class="form-input" rows="4" placeholder="Enter reason (shown to admin)…" required style="height:auto;padding:8px 10px;"></textarea>
        </div>
      </div>
      <div class="modal-foot">
        <button type="button" class="btn btn-ghost btn-sm" onclick="document.getElementById('rejectModal').classList.remove('show')">Cancel</button>
        <button type="submit" name="reject_payroll" class="btn btn-danger btn-sm"><i class="fas fa-times"></i> Confirm Reject</button>
      </div>
    </form>
  </div>
</div>

<!-- ── AUDIT MODAL ── -->
<?php if(count($audit_rows)): ?>
<div class="modal-overlay" id="auditModal">
  <div class="modal-box" style="max-width:580px">
    <div class="modal-head">
      <i class="fas fa-history"></i>
      <div class="modal-head-title">Audit Log — <?= h($month) ?></div>
      <button class="btn-close-modal" onclick="document.getElementById('auditModal').classList.remove('show')">×</button>
    </div>
    <div class="modal-body" style="max-height:60vh;overflow-y:auto;">
      <?php foreach($audit_rows as $al): ?>
      <div class="timeline-item <?= h($al['action']) ?>">
        <div style="display:flex;justify-content:space-between;align-items:flex-start;">
          <div>
            <?php
            $icon=match($al['action']){'approved'=>'<i class="fas fa-check-circle" style="color:var(--success)"></i>','rejected'=>'<i class="fas fa-times-circle" style="color:var(--danger)"></i>','submitted'=>'<i class="fas fa-paper-plane" style="color:var(--warn)"></i>',default=>'<i class="fas fa-info-circle" style="color:var(--accent)"></i>'};
            echo $icon;
            ?>
            <strong><?= ucfirst(h($al['action'])) ?></strong> by <span style="color:var(--accent)"><?= h($al['performed_by']) ?></span>
            <?php if($al['notes']): ?><div style="color:var(--muted);font-size:11px;margin-top:4px;padding-left:16px;"><?= h($al['notes']) ?></div><?php endif; ?>
          </div>
          <span style="color:var(--muted);font-size:11px;white-space:nowrap;margin-left:12px;"><?= date('d M Y, h:i A',strtotime($al['created_at'])) ?></span>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
</div>
<?php endif; ?>

<!-- ── BULK PAYSLIP MODAL ── -->
<div class="modal-overlay" id="bulkPrintModal">
  <div class="modal-box" style="max-width:440px">
    <div class="modal-head">
      <i class="fas fa-file-pdf"></i>
      <div class="modal-head-title">Bulk Payslip Print</div>
      <button class="btn-close-modal" onclick="document.getElementById('bulkPrintModal').classList.remove('show')">×</button>
    </div>
    <div class="modal-body">
      <div style="display:flex;gap:8px;margin-bottom:10px;">
        <button class="btn btn-ghost btn-sm" id="bulkSelectAll">Select All</button>
        <button class="btn btn-ghost btn-sm" id="bulkClearAll">Clear</button>
      </div>
      <div id="bulkEmpList" style="max-height:280px;overflow-y:auto;border:1px solid var(--border);border-radius:8px;padding:8px;"></div>
    </div>
    <div class="modal-foot">
      <button class="btn btn-ghost btn-sm" onclick="document.getElementById('bulkPrintModal').classList.remove('show')">Cancel</button>
      <button class="btn btn-primary btn-sm" id="doBulkPrint"><i class="fas fa-print"></i> Open Payslips</button>
    </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');
}
document.querySelectorAll('.modal-overlay').forEach(m => {
  m.addEventListener('click', function(e) { if(e.target===this) this.classList.remove('show'); });
});

const EPF_WAGE_CAP=15000, EPF_RATE=0.12, ESI_RATE=0.0075, ESI_GROSS_CAP=21000;
function n(v){ return parseFloat(v)||0; }

function calcRow(r) {
  const w=n(r.dataset.working), base=n(r.dataset.basic);
  const sal=n(r.querySelector('[name="salary"]').value);
  const abs=n(r.querySelector('[name="absent_days"]').value);
  const travel=n(r.querySelector('[name="travel_allow"]').value);
  const tw=n(r.querySelector('[name="two_wheeler_maint"]').value);
  const out=n(r.querySelector('[name="outstanding_amt"]').value);
  const tds=n(r.querySelector('[name="tds"]').value);
  const adv=n(r.querySelector('[name="advance"]').value);
  const round=n(r.querySelector('[name="round_off"]').value);
  const bonus=n(r.querySelector('[name="bonus"]').value);
  const inc=n(r.querySelector('[name="incentive"]').value);
  const manEpf=n(r.querySelector('[name="epf_manual_amt"]').value);
  const salary=sal>0?sal:base;
  const paid=Math.max(w-abs,0), lop=w>0?(salary/w)*abs:0;
  const wages=w>0?(salary/w)*paid:salary;
  const basic=wages*.40, da=wages*.20, hra=wages*.20, med=wages*.10, conv=wages*.10;
  const gross=basic+da+hra+med+conv+bonus+inc;
  const epfWage=Math.min(basic+da,EPF_WAGE_CAP);
  const epfCalc=r.querySelector('[name="epf_eligible"]').checked?epfWage*EPF_RATE:0;
  const epfFinal=manEpf>0?manEpf:epfCalc;
  const esi=r.querySelector('[name="esi_eligible"]').checked&&gross<=ESI_GROSS_CAP?gross*ESI_RATE:0;
  const net=gross+travel+tw+out-epfFinal-esi-tds-adv+round;
  return {w,paid,lop,basic,da,hra,med,conv,bonus,inc,gross,epfFinal,esi,net};
}

function fmt(v){ return Math.round(v).toLocaleString('en-IN'); }

function recalc() {
  let TG=0,TEP=0,TES=0,TN=0,TLOP=0,TBONUS=0,CNT=0;
  const divMap={};
  document.querySelectorAll('.pay-row:not([style*="display: none"])').forEach(r => {
    const c=calcRow(r);
    r.querySelector('.lop').textContent=Math.round(c.lop);
    r.querySelector('.paid').textContent=Math.round(c.paid);
    r.querySelector('.basic').textContent=Math.round(c.basic);
    r.querySelector('.da').textContent=Math.round(c.da);
    r.querySelector('.hra').textContent=Math.round(c.hra);
    r.querySelector('.med').textContent=Math.round(c.med);
    r.querySelector('.conv').textContent=Math.round(c.conv);
    r.querySelector('.gross').textContent=Math.round(c.gross);
    r.querySelector('.epf-amt').textContent=Math.round(c.epfFinal);
    r.querySelector('.esi-amt').textContent=Math.round(c.esi);
    r.querySelector('.net-col').textContent=Math.round(c.net);
    TG+=c.gross;TEP+=c.epfFinal;TES+=c.esi;TN+=c.net;TLOP+=c.lop;TBONUS+=c.bonus+c.inc;CNT++;
    const div=r.dataset.division||'Unknown';
    if(!divMap[div])divMap[div]={g:0,e:0,s:0,n:0,cnt:0};
    divMap[div].g+=c.gross;divMap[div].e+=c.epfFinal;divMap[div].s+=c.esi;divMap[div].n+=c.net;divMap[div].cnt++;
  });
  document.getElementById('tcount').textContent=CNT;
  document.getElementById('tlop').textContent=fmt(TLOP);
  document.getElementById('tg').textContent=fmt(TG);
  document.getElementById('tbonus').textContent=fmt(TBONUS);
  document.getElementById('tep').textContent=fmt(TEP);
  document.getElementById('tes').textContent=fmt(TES);
  document.getElementById('tn').textContent=fmt(TN);
  let html='';
  for(const d in divMap){const dm=divMap[d];html+=`<div class="div-card"><div class="div-card-title">${d} <span style="background:rgba(59,130,246,.1);color:var(--accent);padding:2px 6px;border-radius:4px;font-size:10px;">${dm.cnt}</span></div><div class="div-stat"><span>Gross</span><strong>₹${fmt(dm.g)}</strong></div><div class="div-stat"><span>EPF</span><strong style="color:var(--danger)">₹${fmt(dm.e)}</strong></div><div class="div-stat"><span>ESI</span><strong style="color:var(--danger)">₹${fmt(dm.s)}</strong></div><div class="div-stat"><span>Net Pay</span><strong style="color:var(--success)">₹${fmt(dm.n)}</strong></div></div>`;}
  document.getElementById('divisionTotals').innerHTML=html||'<p style="color:var(--muted);padding:12px;">No records</p>';
}

document.querySelectorAll('.pay-row input').forEach(inp=>{
  inp.addEventListener('input',recalc);
  if(inp.type==='checkbox') inp.addEventListener('change',recalc);
});

let searchTimer;
document.getElementById('quickSearch')?.addEventListener('input',function(){
  clearTimeout(searchTimer);
  searchTimer=setTimeout(()=>{
    const term=this.value.toLowerCase().trim();
    let vis=0;
    document.querySelectorAll('.pay-row').forEach(row=>{
      const match=!term||(row.dataset.empid||'').includes(term)||(row.dataset.name||'').includes(term)||(row.dataset.username||'').includes(term);
      row.style.display=match?'':'none';
      if(match)vis++;
    });
    document.getElementById('visibleCount').textContent=term?`${vis} match${vis!==1?'es':''}`:'';
    recalc();
  },280);
});

document.getElementById('showFullName')?.addEventListener('change',function(){
  document.querySelectorAll('.pay-row').forEach(r=>{
    r.querySelector('.emp-name').textContent=this.checked?r.dataset.name:r.dataset.shortname;
  });
});

document.getElementById('selectAll')?.addEventListener('change',function(){
  document.querySelectorAll('.row-cb').forEach(cb=>{cb.checked=this.checked;cb.closest('tr').classList.toggle('selected-row',this.checked);});
});
document.querySelectorAll('.row-cb').forEach(cb=>{cb.addEventListener('change',function(){this.closest('tr').classList.toggle('selected-row',this.checked);});});

document.getElementById('btnPrint')?.addEventListener('click',()=>window.print());

document.getElementById('btnBulkPrint')?.addEventListener('click',()=>{
  const list=document.getElementById('bulkEmpList');list.innerHTML='';
  document.querySelectorAll('.pay-row:not([style*="display: none"])').forEach(r=>{
    const id=r.dataset.id,name=r.dataset.name,cb=document.querySelector(`.row-cb[data-id="${id}"]`),checked=cb?cb.checked:false;
    list.innerHTML+=`<div style="display:flex;align-items:center;gap:8px;padding:6px;border-bottom:1px solid var(--border);"><input type="checkbox" class="bulk-cb" value="${id}" ${checked?'checked':''} style="width:14px;"><label style="font-size:12px;cursor:pointer;">${name}</label></div>`;
  });
  document.getElementById('bulkPrintModal').classList.add('show');
});
document.getElementById('bulkSelectAll')?.addEventListener('click',()=>document.querySelectorAll('.bulk-cb').forEach(c=>c.checked=true));
document.getElementById('bulkClearAll')?.addEventListener('click',()=>document.querySelectorAll('.bulk-cb').forEach(c=>c.checked=false));
document.getElementById('doBulkPrint')?.addEventListener('click',()=>{
  const ids=[...document.querySelectorAll('.bulk-cb:checked')].map(c=>c.value);
  if(!ids.length){alert('Select at least one employee.');return;}
  ids.forEach(id=>window.open(`payslip_new.php?id=${id}&print=1`,'_blank'));
  document.getElementById('bulkPrintModal').classList.remove('show');
});

document.getElementById('btnExportExcel')?.addEventListener('click',()=>{
  const month=document.querySelector('[name="month"]').value;
  const wb=XLSX.utils.book_new();
  const data=[['#','Emp ID','Name','Division','Base Salary','Manual Salary','Absent Days','LOP Amount','Paid Days','Basic','DA','HRA','Medical','Conveyance','Bonus','Incentive','Gross','Travel Allow','2W Maint','Outstanding','EPF Eligible','EPF Amount','Manual EPF','ESI Eligible','ESI Amount','TDS','Advance','Round Off','Net Pay']];
  let sn=1;
  document.querySelectorAll('.pay-row').forEach(r=>{
    const c=calcRow(r);
    data.push([sn++,r.dataset.empid,r.querySelector('.emp-name').textContent.trim(),r.dataset.division,n(r.dataset.basic),n(r.querySelector('[name="salary"]').value),n(r.querySelector('[name="absent_days"]').value),Math.round(c.lop),Math.round(c.paid),Math.round(c.basic),Math.round(c.da),Math.round(c.hra),Math.round(c.med),Math.round(c.conv),Math.round(c.bonus),Math.round(c.inc),Math.round(c.gross),n(r.querySelector('[name="travel_allow"]').value),n(r.querySelector('[name="two_wheeler_maint"]').value),n(r.querySelector('[name="outstanding_amt"]').value),r.querySelector('[name="epf_eligible"]').checked?'Yes':'No',Math.round(c.epfFinal),n(r.querySelector('[name="epf_manual_amt"]').value),r.querySelector('[name="esi_eligible"]').checked?'Yes':'No',Math.round(c.esi),n(r.querySelector('[name="tds"]').value),n(r.querySelector('[name="advance"]').value),n(r.querySelector('[name="round_off"]').value),Math.round(c.net)]);
  });
  const ws=XLSX.utils.aoa_to_sheet(data);
  ws['!cols']=data[0].map((_,ci)=>({wch:Math.max(...data.map(row=>String(row[ci]??'').length))+2}));
  XLSX.utils.book_append_sheet(wb,ws,`Payroll ${month}`);
  XLSX.writeFile(wb,`Payroll_${month}.xlsx`);
});

window.addEventListener('load',()=>setTimeout(recalc,80));
</script>
</body>
</html>