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

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

$is_admin = in_array($_SESSION['role'], ['admin', 'superadmin']);
$message  = '';

if (method_exists($conn, 'set_charset')) $conn->set_charset('utf8mb4');

/* ═══════════════════════════════════════════════════════════
   XLSX READER
═══════════════════════════════════════════════════════════ */
function readXLSX($file) {
    $data = [];
    $zip  = new ZipArchive;
    if ($zip->open($file) === TRUE) {
        $sharedStrings = [];
        $xmlStr = $zip->getFromName('xl/sharedStrings.xml');
        if ($xmlStr !== false) {
            $xml = simplexml_load_string($xmlStr);
            foreach ($xml->si as $si) {
                $text = '';
                if (isset($si->t)) $text = (string)$si->t;
                elseif (isset($si->r)) foreach ($si->r as $r) $text .= (string)$r->t;
                $sharedStrings[] = $text;
            }
        }
        $xmlSheet = $zip->getFromName('xl/worksheets/sheet1.xml');
        if ($xmlSheet !== false) {
            $xml = simplexml_load_string($xmlSheet);
            foreach ($xml->sheetData->row as $row) {
                $rowData = array_fill(0, 20, '');
                foreach ($row->c as $cell) {
                    preg_match('/([A-Z]+)(\d+)/', (string)$cell['r'], $m);
                    $col = $m[1] ?? ''; $ci = 0;
                    for ($i = 0; $i < strlen($col); $i++) $ci = $ci * 26 + (ord($col[$i]) - 64);
                    $ci--;
                    $v = (string)$cell->v;
                    if ((string)($cell['t'] ?? '') === 's' && isset($sharedStrings[(int)$v])) $v = $sharedStrings[(int)$v];
                    if ($ci < 20) $rowData[$ci] = $v;
                }
                $data[] = $rowData;
            }
        }
        $zip->close();
    }
    return $data;
}

function get_table_columns($conn, $table) {
    $cols = []; $db = '';
    $res = $conn->query("SELECT DATABASE() AS dbname");
    if ($res) { $row = $res->fetch_assoc(); $db = $row['dbname'] ?? ''; }
    if (!$db) return $cols;
    $sql  = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=? AND TABLE_NAME=?";
    $stmt = $conn->prepare($sql);
    if ($stmt) {
        $stmt->bind_param("ss", $db, $table); $stmt->execute();
        $r = $stmt->get_result();
        while ($c = $r->fetch_assoc()) $cols[] = $c['COLUMN_NAME'];
        $stmt->close();
    }
    return $cols;
}

/* ═══════════════════════════════════════════════════════════
   REMARKS UPDATE
═══════════════════════════════════════════════════════════ */
if ($is_admin && isset($_POST['update_remarks'])) {
    $r_emp   = (int)($_POST['emp_id'] ?? 0);
    $r_month = trim($_POST['remarks_month'] ?? '');
    $r_text  = trim($_POST['remarks_text']  ?? '');
    if ($r_emp > 0 && $r_month) {
        $upd = $conn->prepare("UPDATE attendance SET remarks=? WHERE emp_id=? AND DATE_FORMAT(created_at,'%Y-%m')=?");
        $upd->bind_param("sis", $r_text, $r_emp, $r_month);
        $message = $upd->execute()
            ? "<div class='alert-box alert-success'><i class='fas fa-check-circle'></i> Remarks updated.</div>"
            : "<div class='alert-box alert-danger'><i class='fas fa-exclamation-circle'></i> Error: ".htmlspecialchars($upd->error)."</div>";
        $upd->close();
    }
}

/* ═══════════════════════════════════════════════════════════
   UPLOAD & AUTO PAYROLL
═══════════════════════════════════════════════════════════ */
if ($is_admin && isset($_POST['upload_attendance'])) {
    if (!isset($_FILES['excel_file']) || $_FILES['excel_file']['error'] !== UPLOAD_ERR_OK) {
        $message = '<div class="alert-box alert-danger"><i class="fas fa-exclamation-triangle"></i> Please select a valid file!</div>';
    } else {
        $tmp   = $_FILES['excel_file']['tmp_name'];
        $ext   = strtolower(pathinfo($_FILES['excel_file']['name'] ?? '', PATHINFO_EXTENSION));
        $month = $_POST['attendance_month'] ?? date('Y-m');

        $data = $ext === 'csv'
            ? (function($t){ $d=[];if(($h=fopen($t,"r"))!==FALSE){while(($r=fgetcsv($h))!==FALSE)$d[]=$r;fclose($h);}return $d; })($tmp)
            : readXLSX($tmp);

        if (empty($data)) {
            $message = '<div class="alert-box alert-danger"><i class="fas fa-exclamation-triangle"></i> Could not read file.</div>';
        } else {
            $conn->autocommit(false);
            try {
                $del = $conn->prepare("DELETE FROM attendance WHERE DATE_FORMAT(created_at,'%Y-%m')=?");
                $del->bind_param("s", $month); $del->execute(); $del->close();
                $inserted = 0; $cur_div = 'General';
                $att = $conn->prepare("REPLACE INTO attendance (emp_id,name,division,absent_days,present_days,remarks,created_at) VALUES (?,?,?,?,?,?,?)");
                foreach ($data as $row) {
                    if (count(array_filter($row)) === 0) continue;
                    if (!empty($row[0]) && empty($row[1]) && empty($row[2])) {
                        $dt = strtoupper(trim($row[0]));
                        $cur_div = str_contains($dt,'DIRECTOR') ? 'Directors'
                            : (str_contains($dt,'ELECTRICAL') ? 'Electrical'
                            : (str_contains($dt,'TAB')        ? 'TAB'
                            : (str_contains($dt,'AC')         ? 'AC'
                            : (str_contains($dt,'AUTOMATION') ? 'Automation'
                            : (str_contains($dt,'ADMIN')      ? 'Admin' : 'General')))));
                        continue;
                    }
                    if (!isset($row[1]) || !is_numeric($row[1])) continue;
                    $eid = (int)$row[1]; $name = trim($row[2] ?? '');
                    if ($eid == 0 || $name === '') continue;
                    $absent  = is_numeric($row[10] ?? null) ? (float)$row[10] : 0.0;
                    $present = is_numeric($row[11] ?? null) ? (float)$row[11] : 30.0;
                    $remarks = trim($row[12] ?? '');
                    $fd = $month . "-01 00:00:00";
                    $att->bind_param("issddss", $eid, $name, $cur_div, $absent, $present, $remarks, $fd);
                    $att->execute(); $inserted++;
                }
                $att->close();
                $delp = $conn->prepare("DELETE FROM payroll WHERE DATE_FORMAT(created_at,'%Y-%m')=?");
                $delp->bind_param("s", $month); $delp->execute(); $delp->close();
                $pcols = get_table_columns($conn, 'payroll');
                $yr = (int)substr($month,0,4); $mn = (int)substr($month,5,2);
                $ps = $conn->prepare("SELECT a.*,COALESCE(s.gross_salary,0) AS gross_salary,COALESCE(s.epf,0) AS epf,COALESCE(s.esi,0) AS esi,COALESCE(s.tds,0) AS tds,COALESCE(s.advance,0) AS advance FROM attendance a LEFT JOIN salary_master s ON a.emp_id=s.emp_id WHERE YEAR(a.created_at)=? AND MONTH(a.created_at)=?");
                $ps->bind_param("ii",$yr,$mn); $ps->execute();
                $prRes = $ps->get_result(); $pay_count = 0;
                while ($pr = $prRes->fetch_assoc()) {
                    $gs = round((float)($pr['gross_salary']??0),2);
                    $pd = (float)($pr['present_days']??0); $ab = (float)($pr['absent_days']??0);
                    $epf=(float)($pr['epf']??0); $esi=(float)($pr['esi']??0);
                    $tds=(float)($pr['tds']??0); $adv=(float)($pr['advance']??0);
                    $pro = round($gs/30*$pd,2); $net=round($pro-$epf-$esi-$tds-$adv,2);
                    $cands=['emp_id'=>(int)$pr['emp_id'],'name'=>$pr['name'],'division'=>$pr['division'],'month'=>$month,'salary'=>$gs,'basic'=>$gs,'basic_salary'=>$gs,'present_days'=>$pd,'paid_days'=>$pd,'absent_days'=>$ab,'per_day_salary'=>$pd>0?round($pro/$pd,2):0,'total_wages'=>$pro,'gross_salary'=>$pro,'epf'=>$epf,'esi'=>$esi,'tds'=>$tds,'advance'=>$adv,'net_pay'=>$net,'pending_amt'=>$net,'grand_total'=>$net,'created_at'=>date('Y-m-d H:i:s')];
                    $desired=['emp_id','name','division','month','salary','basic_salary','basic','present_days','paid_days','absent_days','per_day_salary','total_wages','gross_salary','epf','esi','tds','advance','net_pay','pending_amt','grand_total','created_at'];
                    $ic=[];$ph=[];$vals=[];$ty='';
                    foreach($desired as $f){ if(in_array($f,$pcols,true)&&array_key_exists($f,$cands)){$ic[]="`$f`";$ph[]='?';$v=$cands[$f];$vals[]=$v;$ty.=(is_int($v)?'i':(is_float($v)?'d':'s'));}}
                    if(empty($ic))continue;
                    $sqlI="INSERT INTO payroll (".implode(",",$ic).") VALUES (".implode(",",$ph).")";
                    $ins=$conn->prepare($sqlI);
                    if(!$ins)throw new Exception("Insert failed: ".$conn->error);
                    $refs=[];foreach($vals as $k=>$v){$t2=$ty[$k]??'s';$vals[$k]=$t2==='i'?(int)$v:($t2==='d'?(float)$v:(string)$v);$refs[]=&$vals[$k];}
                    array_unshift($refs,$ty);
                    call_user_func_array([$ins,'bind_param'],$refs);
                    $ins->execute(); $ins->close(); $pay_count++;
                }
                $ps->close(); $conn->commit();
                $message = "<div class='alert-box alert-success'><i class='fas fa-check-circle'></i> <strong>$inserted</strong> attendance &amp; <strong>$pay_count</strong> payroll records processed! <a href='payroll_new.php?month=".htmlspecialchars($month)."' class='btn-inline'>View Payroll →</a></div>";
            } catch (Exception $e) {
                $conn->rollback();
                $message = "<div class='alert-box alert-danger'><i class='fas fa-exclamation-triangle'></i> ".htmlspecialchars($e->getMessage())."</div>";
            }
        }
    }
}

/* ═══════════════════════════════════════════════════════════
   LOAD DISPLAY DATA
═══════════════════════════════════════════════════════════ */
$selected_month  = $_GET['month']    ?? date('Y-m');
$filter_division = $_GET['division'] ?? 'all';
$filter_status   = $_GET['status']  ?? 'all';
$year  = (int)substr($selected_month, 0, 4);
$month = (int)substr($selected_month, 5, 2);
$days  = cal_days_in_month(CAL_GREGORIAN, $month, $year);

$sql = "SELECT a.*, COALESCE(u.division, a.division) as display_division FROM attendance a LEFT JOIN users u ON a.emp_id = u.id WHERE YEAR(a.created_at)=? AND MONTH(a.created_at)=?";
$params = [$year, $month]; $types = "ii";
if ($filter_division !== 'all') { $sql .= " AND COALESCE(u.division,a.division) COLLATE utf8mb4_general_ci=?"; $params[]=$filter_division; $types.='s'; }
$sql .= " ORDER BY COALESCE(u.division,a.division) COLLATE utf8mb4_general_ci, a.name";
$stmt = $conn->prepare($sql);
$stmt->bind_param($types,...$params); $stmt->execute();
$attendance_all = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$attendance = array_filter($attendance_all, function($a) use ($filter_status) {
    if ($filter_status === 'high_absent') return (float)$a['absent_days'] >= 3;
    if ($filter_status === 'perfect')     return (float)$a['absent_days'] == 0;
    return true;
});
$attendance = array_values($attendance);

$total_emp     = count($attendance_all);
$total_absent  = array_sum(array_column($attendance_all, 'absent_days'));
$total_present = array_sum(array_column($attendance_all, 'present_days'));
$high_absent   = count(array_filter($attendance_all, fn($a) => (float)$a['absent_days'] >= 3));
$perfect_att   = count(array_filter($attendance_all, fn($a) => (float)$a['absent_days'] == 0));
$avg_absent    = $total_emp > 0 ? round($total_absent / $total_emp, 1) : 0;

$divs_stmt = $conn->prepare("SELECT DISTINCT COALESCE(u.division,a.division) as division FROM attendance a LEFT JOIN users u ON a.emp_id=u.id WHERE YEAR(a.created_at)=? AND MONTH(a.created_at)=? ORDER BY COALESCE(u.division,a.division) COLLATE utf8mb4_general_ci");
$divs_stmt->bind_param("ii",$year,$month); $divs_stmt->execute();
$divs = $divs_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$divs_stmt->close();

/* CSV Export */
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    $safe = $filter_division === 'all' ? 'All' : preg_replace('/[^A-Za-z0-9_-]/','_',$filter_division);
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="attendance-'.$selected_month.'-'.$safe.'.csv"');
    $out = fopen('php://output','w');
    fputcsv($out, ['Emp ID','Name','Division','Present Days','Absent Days','Remarks']);
    foreach ($attendance as $a) {
        fputcsv($out, [$a['emp_id'],$a['name'],$a['display_division'],$a['present_days'],$a['absent_days'],$a['remarks']??'']);
    }
    fclose($out); exit;
}

$username_session = $_SESSION['username'] ?? '';
function h($str) { return htmlspecialchars($str ?? '', ENT_QUOTES, 'UTF-8'); }
?>
<!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 · Attendance</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: 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; }
.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: 20px; animation: fadeUp .25s ease;
}
.alert-box a.btn-inline { margin-left:8px; background:#fff; color:#1d4ed8; padding:3px 10px; border-radius:6px; font-weight:600; text-decoration:none; font-size:12px; }
.alert-success { background: #d1fae5; border:1px solid #6ee7b7; color: #065f46; }
.alert-danger  { background: #fee2e2; border:1px solid #fca5a5; color: #991b1b; }
@keyframes fadeUp { from { opacity:0; transform:translateY(6px); } to { opacity:1; transform:none; } }

/* ── KPI CARDS ── */
.kpi-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(150px,1fr)); gap:14px; margin-bottom:22px; }
.kpi-card {
  background:var(--surface); border:1px solid var(--border); border-radius:var(--radius);
  padding:16px 18px; position:relative; overflow:hidden;
  transition:box-shadow .18s, transform .18s; box-shadow:var(--shadow);
}
.kpi-card:hover { box-shadow:0 4px 20px rgba(0,0,0,.08); transform:translateY(-2px); }
.kpi-card::before { content:''; position:absolute; top:0; left:0; right:0; height:3px; }
.kpi-card.blue::before   { background: var(--accent); }
.kpi-card.green::before  { background: var(--success); }
.kpi-card.red::before    { background: var(--danger); }
.kpi-card.warn::before   { background: var(--warn); }
.kpi-card.purple::before { background: #7c3aed; }
.kpi-icon { width:36px; height:36px; border-radius:8px; display:flex; align-items:center; justify-content:center; font-size:14px; margin-bottom:10px; }
.kpi-icon.blue   { background:#dbeafe; color:var(--accent); }
.kpi-icon.green  { background:#d1fae5; color:var(--success); }
.kpi-icon.red    { background:#fee2e2; color:var(--danger); }
.kpi-icon.warn   { background:#fef3c7; color:var(--warn); }
.kpi-icon.purple { background:#f5f3ff; color:#7c3aed; }
.kpi-label { font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:.8px; color:var(--muted); }
.kpi-value { font-family:'JetBrains Mono',monospace; font-size:1.75rem; font-weight:700; color:var(--ink); line-height:1.1; margin:4px 0 2px; }
.kpi-meta  { font-size:11px; color:var(--muted); }

/* ── TOOLBAR ── */
.toolbar {
  background:var(--surface); border:1px solid var(--border); border-radius:var(--radius);
  padding:14px 18px; margin-bottom:16px;
  display:flex; flex-wrap:wrap; gap:10px; align-items:flex-end;
  box-shadow:var(--shadow);
}
.toolbar-group { display:flex; flex-direction:column; gap:4px; }
.toolbar-label { font-size:10px; font-weight:700; text-transform:uppercase; letter-spacing:.8px; color:var(--muted); }
.toolbar-actions { display:flex; flex-wrap:wrap; gap:8px; margin-left:auto; align-items:flex-end; }
.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);
  transition:border-color .15s; outline:none;
}
.form-ctrl:focus { border-color:var(--accent); box-shadow:0 0 0 3px rgba(59,130,246,.1); background:var(--surface); }

/* ── FILTER PILLS ── */
.filter-pills { display:flex; gap:6px; flex-wrap:wrap; }
.pill {
  padding:5px 12px; border-radius:20px; font-size:11px; font-weight:600;
  border:1px solid var(--border); background:var(--surface); color:var(--ink-2);
  cursor:pointer; transition:all .15s; text-decoration:none; display:inline-flex; align-items:center; gap:5px;
}
.pill:hover { border-color:var(--accent); color:var(--accent); }
.pill.active { background:var(--accent); border-color:var(--accent); color:#fff; }
.pill.success.active { background:var(--success); border-color:var(--success); color:#fff; }
.pill.danger.active  { background:var(--danger);  border-color:var(--danger);  color:#fff; }

/* ── BUTTONS ── */
.btn {
  display:inline-flex; align-items:center; gap:6px; padding:7px 14px;
  border-radius:8px; font-size:13px; font-weight:600; cursor:pointer;
  transition:all .15s; border:1px solid transparent; 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-ghost   { background:transparent; color:var(--ink-2); border-color:var(--border); }
.btn-ghost:hover { background:var(--bg); color:var(--ink); }

/* ── SEARCH ── */
.search-wrap { position:relative; flex:1; min-width:200px; max-width:280px; }
.search-wrap input { width:100%; 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; }
.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 CARD ── */
.table-card { background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); overflow:hidden; box-shadow:var(--shadow); margin-bottom:24px; }
.table-header { padding:14px 18px; border-bottom:1px solid var(--border); display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:10px; background:var(--ink); }
.table-header-title { color:#fff; font-weight:700; font-size:14px; display:flex; align-items:center; gap:8px; }
.badge { background:rgba(255,255,255,.15); color:#fff; padding:2px 8px; border-radius:10px; font-size:11px; }
.table-scroll { overflow:auto; max-height:62vh; }
.att-table { width:100%; border-collapse:separate; border-spacing:0; font-size:13px; }
.att-table thead th {
  position:sticky; top:0; z-index:10; background:#1e293b;
  color:rgba(255,255,255,.85); padding:9px 8px;
  font-size:10px; font-weight:700; text-transform:uppercase; letter-spacing:.05em;
  white-space:nowrap; border-bottom:2px solid #334155; text-align:center;
}
.att-table thead th:nth-child(-n+7) { text-align:left; }
.att-table tbody td { padding:8px 8px; vertical-align:middle; border-bottom:1px solid var(--border); }
.att-table tbody tr:last-child td { border-bottom:none; }
.att-table tbody tr:hover { background:#f8faff; }
.att-table tbody tr[data-div="Directors"]  td:first-child { border-left:3px solid #f59e0b; }
.att-table tbody tr[data-div="Electrical"] td:first-child { border-left:3px solid #3b82f6; }
.att-table tbody tr[data-div="TAB"]        td:first-child { border-left:3px solid #10b981; }
.att-table tbody tr[data-div="AC"]         td:first-child { border-left:3px solid #8b5cf6; }
.att-table tbody tr[data-div="Automation"] td:first-child { border-left:3px solid #f97316; }
.att-table tbody tr[data-div="Admin"]      td:first-child { border-left:3px solid #ec4899; }
.att-table tbody tr[data-div="General"]    td:first-child { border-left:3px solid #6b7280; }
.day-cell { width:26px; min-width:26px; max-width:26px; text-align:center; font-family:'JetBrains Mono',monospace; font-size:10px; padding:6px 3px !important; }
.day-p { color:var(--success); font-weight:700; }
.day-a { color:var(--danger); font-weight:700; background:#fff5f5; }
.day-w { color:#9ca3af; }
.chip { display:inline-flex; align-items:center; gap:4px; padding:3px 8px; border-radius:20px; font-size:10px; font-weight:600; white-space:nowrap; }
.chip-success { background:#d1fae5; color:#065f46; }
.chip-warn    { background:#fef3c7; color:#92400e; }
.chip-danger  { background:#fee2e2; color:#991b1b; }
.absent-badge { font-family:'JetBrains Mono',monospace; font-weight:700; font-size:13px; }
.absent-0    { color:var(--success); }
.absent-low  { color:var(--warn); }
.absent-high { color:var(--danger); }
.table-footer { padding:10px 18px; border-top:1px solid var(--border); background:var(--bg); display:flex; align-items:center; gap:12px; font-size:11px; color:var(--muted); }

/* ── DIV SUMMARY ── */
.div-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(180px,1fr)); gap:12px; margin-bottom:24px; }
.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:13px; margin-bottom:8px; }
.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:560px; overflow:hidden; box-shadow:0 20px 60px rgba(0,0,0,.2); animation:fadeUp .2s ease; }
.modal-head { display:flex; align-items:center; gap:8px; padding:16px 20px; background:var(--ink); color:#fff; }
.modal-head-title { font-size:15px; font-weight:700; flex:1; }
.modal-body { padding:22px; }
.modal-foot { padding:14px 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:16px; }
.form-label { display:block; font-size:10px; font-weight:700; text-transform:uppercase; letter-spacing:.8px; color:var(--muted); margin-bottom:6px; }
.form-input, .form-select { width:100%; height:40px; 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; }
.form-input:focus, .form-select:focus { border-color:var(--accent); box-shadow:0 0 0 3px rgba(59,130,246,.1); background:var(--surface); }
.form-text { font-size:11px; color:var(--muted); margin-top:5px; }
.col-map { display:grid; grid-template-columns:repeat(auto-fill,minmax(130px,1fr)); gap:4px; font-size:11px; }
.col-map-item { padding:4px 8px; background:var(--bg); border-radius:4px; border:1px solid var(--border); }
.col-map-item strong { color:var(--accent); }
textarea.form-input { height:auto; padding:8px 10px; resize:vertical; }

/* ── PRINT ── */
@media print {
  .sidebar, .topbar, .toolbar, .kpi-grid { display:none !important; }
  .content { margin-left:0 !important; }
  .table-scroll { max-height:none; overflow:visible; }
}
@media (max-width: 768px) {
  .sidebar { transform: translateX(-100%); }
  .sidebar:not(.hidden) { transform: none; }
  .content { margin-left: 0; }
  .page { padding: 16px; }
  .kpi-grid { grid-template-columns: repeat(2,1fr); }
  .toolbar-actions { margin-left:0; width:100%; }
}
</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 open" onclick="toggleMenu(this)">
          <i class="fas fa-folder-open"></i> DAP<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu open">
          <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 active"><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="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"><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>

<!-- ── 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">Attendance Dashboard</span>
    </div>
    <div class="topbar-spacer"></div>
    <div class="topbar-actions">
      <?php if ($is_admin): ?>
      <button onclick="document.getElementById('uploadModal').classList.add('show')" class="btn btn-success" style="font-size:12px;padding:6px 12px;">
        <i class="fas fa-cloud-upload-alt"></i> Upload
      </button>
      <a href="payroll.php?month=<?= urlencode($selected_month) ?>" class="btn btn-primary" style="font-size:12px;padding:6px 12px;">
        <i class="fas fa-rupee-sign"></i> Payroll
      </a>
      <?php endif; ?>
    </div>
    <div class="topbar-user">
      <div class="topbar-avatar"><?php echo strtoupper(substr($username_session ?: 'A', 0, 1)); ?></div>
      <?php echo h($username_session ?: 'Admin'); ?>
    </div>
  </div>

  <div class="page">

    <div class="page-header">
      <div>
        <div class="page-title"><i class="fas fa-calendar-check" style="color:var(--accent);margin-right:8px;"></i>Attendance Dashboard</div>
        <div class="page-subtitle"><?= date('F Y', strtotime("$selected_month-01")) ?> — Upload, review &amp; export attendance records</div>
      </div>
    </div>

    <?php if ($message): echo $message; endif; ?>

    <!-- KPI CARDS -->
    <div class="kpi-grid">
      <div class="kpi-card blue">
        <div class="kpi-icon blue"><i class="fas fa-users"></i></div>
        <div class="kpi-label">Total Employees</div>
        <div class="kpi-value"><?= $total_emp ?></div>
        <div class="kpi-meta"><?= date('F Y', strtotime("$selected_month-01")) ?></div>
      </div>
      <div class="kpi-card green">
        <div class="kpi-icon green"><i class="fas fa-check-circle"></i></div>
        <div class="kpi-label">Perfect Attendance</div>
        <div class="kpi-value"><?= $perfect_att ?></div>
        <div class="kpi-meta">Zero absences</div>
      </div>
      <div class="kpi-card red">
        <div class="kpi-icon red"><i class="fas fa-exclamation-circle"></i></div>
        <div class="kpi-label">High Absence ≥3</div>
        <div class="kpi-value"><?= $high_absent ?></div>
        <div class="kpi-meta">Needs review</div>
      </div>
      <div class="kpi-card warn">
        <div class="kpi-icon warn"><i class="fas fa-chart-bar"></i></div>
        <div class="kpi-label">Avg. Absent Days</div>
        <div class="kpi-value"><?= $avg_absent ?></div>
        <div class="kpi-meta">Per employee</div>
      </div>
      <div class="kpi-card purple">
        <div class="kpi-icon purple"><i class="fas fa-calendar-times"></i></div>
        <div class="kpi-label">Total Absent Days</div>
        <div class="kpi-value"><?= number_format($total_absent, 0) ?></div>
        <div class="kpi-meta">Across all staff</div>
      </div>
    </div>

    <!-- TOOLBAR -->
    <div class="toolbar">
      <div class="toolbar-group">
        <span class="toolbar-label">Month</span>
        <form method="get" style="display:contents">
          <input type="month" name="month" value="<?= h($selected_month) ?>" onchange="this.form.submit()" class="form-ctrl">
          <input type="hidden" name="division" value="<?= h($filter_division) ?>">
          <input type="hidden" name="status"   value="<?= h($filter_status) ?>">
        </form>
      </div>
      <div class="toolbar-group">
        <span class="toolbar-label">Division</span>
        <form method="get" style="display:contents">
          <select name="division" onchange="this.form.submit()" class="form-ctrl">
            <option value="all">All Divisions</option>
            <?php foreach($divs as $d): ?>
            <option value="<?= h($d['division']) ?>" <?= $filter_division===$d['division']?'selected':'' ?>><?= h($d['division']) ?></option>
            <?php endforeach; ?>
          </select>
          <input type="hidden" name="month"  value="<?= h($selected_month) ?>">
          <input type="hidden" name="status" value="<?= h($filter_status) ?>">
        </form>
      </div>
      <div class="toolbar-group">
        <span class="toolbar-label">Status Filter</span>
        <div class="filter-pills">
          <a href="?month=<?= urlencode($selected_month) ?>&division=<?= urlencode($filter_division) ?>&status=all"         class="pill <?= $filter_status==='all'?'active':'' ?>">All</a>
          <a href="?month=<?= urlencode($selected_month) ?>&division=<?= urlencode($filter_division) ?>&status=perfect"     class="pill success <?= $filter_status==='perfect'?'active':'' ?>"><i class="fas fa-check"></i> Perfect</a>
          <a href="?month=<?= urlencode($selected_month) ?>&division=<?= urlencode($filter_division) ?>&status=high_absent" class="pill danger  <?= $filter_status==='high_absent'?'active':'' ?>"><i class="fas fa-exclamation"></i> High Absent</a>
        </div>
      </div>
      <div class="toolbar-actions">
        <div class="toolbar-group">
          <span class="toolbar-label">Search</span>
          <div class="search-wrap">
            <i class="fas fa-search si"></i>
            <input type="text" id="searchBox" placeholder="Name, ID, division…" autocomplete="off">
          </div>
        </div>
        <button onclick="window.print()" class="btn btn-ghost"><i class="fas fa-print"></i> Print</button>
        <a href="?month=<?= urlencode($selected_month) ?>&division=<?= urlencode($filter_division) ?>&export=csv" class="btn btn-ghost"><i class="fas fa-file-csv"></i> CSV</a>
        <button id="btnExcelExport" class="btn btn-ghost"><i class="fas fa-file-excel"></i> Excel</button>
      </div>
    </div>

    <!-- ATTENDANCE TABLE -->
    <div class="table-card">
      <div class="table-header">
        <div class="table-header-title">
          <i class="fas fa-table"></i> Attendance Register
          <span class="badge"><?= count($attendance) ?> employees</span>
          <?php if ($filter_division !== 'all'): ?><span class="badge"><?= h($filter_division) ?></span><?php endif; ?>
          <?php if ($filter_status !== 'all'): ?><span class="badge" style="background:rgba(239,68,68,.3)"><?= $filter_status === 'high_absent' ? 'High Absent' : 'Perfect' ?></span><?php endif; ?>
        </div>
        <div style="display:flex;align-items:center;gap:16px;">
          <label style="display:flex;align-items:center;gap:6px;color:#fff;font-size:12px;cursor:pointer;">
            <input type="checkbox" id="toggleDays" checked> Day Grid
          </label>
          <label style="display:flex;align-items:center;gap:6px;color:#fff;font-size:12px;cursor:pointer;">
            <input type="checkbox" id="selectAllCb"> Select All
          </label>
        </div>
      </div>
      <div class="table-scroll">
        <table class="att-table" id="attTable">
          <thead>
            <tr>
              <th style="width:30px"><input type="checkbox" id="headerCb" onchange="toggleAll(this.checked)"></th>
              <th>#</th><th>Emp ID</th><th>Name</th><th>Division</th>
              <th>Present</th><th>Absent</th><th>Status</th><th>Remarks</th>
              <th class="day-cols" colspan="<?= $days ?>">← Day-wise (<?= $days ?> days) →</th>
            </tr>
          </thead>
          <tbody id="attBody">
          <?php
          $div_stats = []; $sn = 1;
          foreach($attendance as $a):
            $absent  = (float)$a['absent_days'];
            $present = (float)$a['present_days'];
            $div     = $a['display_division'];
            if (!isset($div_stats[$div])) $div_stats[$div] = ['emp'=>0,'absent'=>0,'present'=>0];
            $div_stats[$div]['emp']++;
            $div_stats[$div]['absent']  += $absent;
            $div_stats[$div]['present'] += $present;
            $absent_cls = $absent==0?'absent-0':($absent<3?'absent-low':'absent-high');
            $chip_cls   = $absent==0?'chip-success':($absent<3?'chip-warn':'chip-danger');
            $chip_txt   = $absent==0?'<i class="fas fa-check-circle"></i> Perfect':($absent<3?'<i class="fas fa-minus-circle"></i> Low':'<i class="fas fa-times-circle"></i> High');
            $remarks_preview = $a['remarks'] ? (strlen($a['remarks'])>50?h(substr($a['remarks'],0,47)).'…':h($a['remarks'])) : '<span style="color:#d1d5db">—</span>';
          ?>
          <tr data-id="<?= h($a['emp_id']) ?>" data-name="<?= h(strtolower($a['name'])) ?>" data-div="<?= h($div) ?>" data-division="<?= h(strtolower($div)) ?>">
            <td style="text-align:center"><input type="checkbox" class="row-cb" data-emp="<?= (int)$a['emp_id'] ?>" data-name="<?= h($a['name']) ?>"></td>
            <td style="color:var(--muted);font-family:'JetBrains Mono',monospace;font-size:11px;"><?= $sn++ ?></td>
            <td style="font-family:'JetBrains Mono',monospace;font-weight:600;font-size:12px;"><?= h($a['emp_id']) ?></td>
            <td><strong><?= h($a['name']) ?></strong></td>
            <td><span style="font-size:11px;font-weight:600;color:var(--ink-2)"><?= h($div) ?></span></td>
            <td style="font-family:'JetBrains Mono',monospace;font-weight:700;color:var(--success);text-align:center"><?= $present ?></td>
            <td style="text-align:center"><span class="absent-badge <?= $absent_cls ?>"><?= $absent ?></span></td>
            <td><span class="chip <?= $chip_cls ?>"><?= $chip_txt ?></span></td>
            <td style="max-width:160px">
              <small id="rp_<?= (int)$a['emp_id'] ?>"><?= $remarks_preview ?></small>
              <?php if ($is_admin): ?>
              <button class="btn-edit-remark" data-emp="<?= (int)$a['emp_id'] ?>" data-remarks="<?= h($a['remarks']??'') ?>"
                style="background:none;border:none;cursor:pointer;color:var(--accent);padding:0 4px;font-size:11px;" title="Edit">
                <i class="fas fa-pencil-alt"></i>
              </button>
              <?php endif; ?>
            </td>
            <?php for($d=1;$d<=$days;$d++):
              $dow=$date('N',mktime(0,0,0,$month,$d,$year));
              $is_weekend=($dow==6||$dow==7);
              $p_int=(int)$present;
              $cell_cls=$is_weekend?'day-w':($p_int>=$d?'day-p':'day-a');
              $cell_val=$is_weekend?'·':($p_int>=$d?'P':'A');
            ?>
            <td class="day-cell day-col <?= $cell_cls ?>"><?= $cell_val ?></td>
            <?php endfor; ?>
          </tr>
          <?php endforeach; ?>
          <?php if(empty($attendance)): ?>
          <tr><td colspan="<?= $days+9 ?>" style="text-align:center;padding:60px 20px;color:var(--muted);">
            <i class="fas fa-cloud-upload-alt" style="font-size:2.5rem;display:block;margin-bottom:12px;opacity:.3"></i>
            No attendance data for this period.<br><small>Upload an attendance Excel/CSV to get started.</small>
          </td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
      <div class="table-footer">
        <span id="visCount"><?= count($attendance) ?> records</span>
        <span>·</span>
        <span>Total absent: <strong style="color:var(--danger)"><?= number_format($total_absent,0) ?></strong></span>
        <span>·</span>
        <span>Total present: <strong style="color:var(--success)"><?= number_format($total_present,0) ?></strong></span>
      </div>
    </div>

    <!-- DIVISION SUMMARY -->
    <?php if(!empty($div_stats)): ?>
    <div style="margin-bottom:8px;font-weight:700;font-size:14px;display:flex;align-items:center;gap:8px;">
      <i class="fas fa-chart-bar" style="color:var(--accent)"></i> Division Summary
    </div>
    <div class="div-grid">
      <?php
      $div_colors=['Directors'=>'#f59e0b','Electrical'=>'#3b82f6','TAB'=>'#10b981','AC'=>'#8b5cf6','Automation'=>'#f97316','Admin'=>'#ec4899','General'=>'#6b7280'];
      foreach($div_stats as $dname=>$ds):
        $avg_ab=$ds['emp']>0?round($ds['absent']/$ds['emp'],1):0;
        $color=$div_colors[$dname]??'#6b7280';
      ?>
      <div class="div-card" style="border-top:3px solid <?= $color ?>;">
        <div class="div-card-title" style="color:<?= $color ?>"><?= h($dname) ?></div>
        <div class="div-stat"><span>Employees</span><strong><?= $ds['emp'] ?></strong></div>
        <div class="div-stat"><span>Present Days</span><strong style="color:var(--success)"><?= number_format($ds['present'],0) ?></strong></div>
        <div class="div-stat"><span>Absent Days</span><strong style="color:var(--danger)"><?= number_format($ds['absent'],0) ?></strong></div>
        <div class="div-stat"><span>Avg Absent</span><strong><?= $avg_ab ?></strong></div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php endif; ?>

  </div><!-- /page -->
</div><!-- /content -->
</div><!-- /layout -->

<!-- ── UPLOAD MODAL ── -->
<?php if($is_admin): ?>
<div class="modal-overlay" id="uploadModal">
  <div class="modal-box">
    <form method="post" enctype="multipart/form-data">
      <div class="modal-head">
        <i class="fas fa-cloud-upload-alt"></i>
        <div class="modal-head-title">Upload Attendance → Auto Payroll</div>
        <button type="button" class="btn-close-modal" onclick="document.getElementById('uploadModal').classList.remove('show')">×</button>
      </div>
      <div class="modal-body">
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
          <div class="form-group">
            <label class="form-label">Month</label>
            <input type="month" name="attendance_month" class="form-input" value="<?= h($selected_month) ?>" required>
          </div>
          <div class="form-group">
            <label class="form-label">Attendance File</label>
            <input type="file" name="excel_file" accept=".xlsx,.xls,.csv" class="form-input" style="height:auto;padding:6px;" required>
            <div class="form-text"><i class="fas fa-info-circle"></i> Supports .xlsx, .xls, .csv</div>
          </div>
        </div>
        <div style="background:var(--bg);border-radius:8px;border:1px solid var(--border);padding:12px;">
          <div style="font-size:11px;font-weight:700;color:var(--muted);margin-bottom:8px;"><i class="fas fa-table"></i> Expected Column Layout</div>
          <div class="col-map">
            <?php $cols_map=['Col A'=>'Division Header','Col B'=>'Emp ID','Col C'=>'Name','Col K'=>'Absent Days','Col L'=>'Present Days','Col M'=>'Remarks'];
            foreach($cols_map as $c=>$l): ?>
            <div class="col-map-item"><strong><?= $c ?></strong><br><span style="color:var(--muted)"><?= $l ?></span></div>
            <?php endforeach; ?>
          </div>
        </div>
      </div>
      <div class="modal-foot">
        <button type="button" class="btn btn-ghost" onclick="document.getElementById('uploadModal').classList.remove('show')">Cancel</button>
        <button name="upload_attendance" class="btn btn-success"><i class="fas fa-cloud-upload-alt"></i> Upload &amp; Process</button>
      </div>
    </form>
  </div>
</div>

<!-- ── REMARKS MODAL ── -->
<div class="modal-overlay" id="remarkModal">
  <div class="modal-box" style="max-width:440px">
    <form method="post" id="remarkForm">
      <div class="modal-head">
        <i class="fas fa-comment-dots"></i>
        <div class="modal-head-title">Edit Remarks</div>
        <button type="button" class="btn-close-modal" onclick="document.getElementById('remarkModal').classList.remove('show')">×</button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="emp_id" id="remark_emp_id">
        <input type="hidden" name="remarks_month" value="<?= h($selected_month) ?>">
        <div id="remarkEmpName" style="font-weight:600;color:var(--ink-2);margin-bottom:12px;"></div>
        <div class="form-group">
          <label class="form-label">Remarks / Notes</label>
          <textarea name="remarks_text" id="remarks_text" class="form-input" rows="5" placeholder="Add attendance remarks, leave notes…" style="height:auto;padding:8px 10px;resize:vertical;"></textarea>
        </div>
        <div class="form-text"><i class="fas fa-info-circle"></i> Updates all attendance rows for this employee &amp; month.</div>
      </div>
      <div class="modal-foot">
        <button type="button" class="btn btn-ghost" onclick="document.getElementById('remarkModal').classList.remove('show')">Cancel</button>
        <button type="submit" name="update_remarks" class="btn btn-primary"><i class="fas fa-save"></i> Save Remarks</button>
      </div>
    </form>
  </div>
</div>
<?php endif; ?>

<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');
}

/* Close modal on overlay click */
document.querySelectorAll('.modal-overlay').forEach(m => {
  m.addEventListener('click', function(e) { if(e.target===this) this.classList.remove('show'); });
});

/* Search */
const searchBox = document.getElementById('searchBox');
const rows      = document.querySelectorAll('#attBody tr[data-id]');
const visCount  = document.getElementById('visCount');
searchBox?.addEventListener('input', function() {
  const term = this.value.toLowerCase().trim();
  let vis = 0;
  rows.forEach(r => {
    const show = !term || (r.dataset.id||'').toLowerCase().includes(term) || (r.dataset.name||'').toLowerCase().includes(term) || (r.dataset.division||'').toLowerCase().includes(term);
    r.style.display = show ? '' : 'none';
    if(show) vis++;
  });
  visCount.textContent = `${vis} records`;
});

/* Toggle day grid */
document.getElementById('toggleDays')?.addEventListener('change', function() {
  document.querySelectorAll('.day-col,.day-cols').forEach(el => el.style.display = this.checked ? '' : 'none');
});

/* Select all */
document.getElementById('headerCb')?.addEventListener('change', e => toggleAll(e.target.checked));
document.getElementById('selectAllCb')?.addEventListener('change', e => toggleAll(e.target.checked));
function toggleAll(c) { document.querySelectorAll('.row-cb').forEach(cb => cb.checked = c); }

/* Remarks modal */
document.querySelectorAll('.btn-edit-remark').forEach(btn => {
  btn.addEventListener('click', function() {
    document.getElementById('remark_emp_id').value = this.dataset.emp;
    document.getElementById('remarks_text').value  = this.dataset.remarks || '';
    const row = this.closest('tr');
    document.getElementById('remarkEmpName').textContent = row ? row.querySelector('strong')?.textContent || '' : '';
    document.getElementById('remarkModal').classList.add('show');
  });
});

/* Excel export */
document.getElementById('btnExcelExport')?.addEventListener('click', () => {
  const header = ['#','Emp ID','Name','Division','Present Days','Absent Days','Status','Remarks'];
  const data   = [header];
  let sn = 1;
  rows.forEach(r => {
    if(r.style.display==='none') return;
    const tds = r.querySelectorAll('td');
    const absent = parseFloat(tds[6]?.textContent) || 0;
    data.push([sn++, tds[2]?.textContent.trim()||'', tds[3]?.textContent.trim()||'', tds[4]?.textContent.trim()||'',
               tds[5]?.textContent.trim()||'', tds[6]?.textContent.trim()||'',
               absent===0?'Perfect':absent<3?'Low Absent':'High Absent',
               tds[8]?.querySelector('small')?.textContent.trim()||'']);
  });
  const ws = XLSX.utils.aoa_to_sheet(data);
  ws['!cols'] = data[0].map((_,ci)=>({wch:Math.max(...data.map(r=>String(r[ci]??'').length))+2}));
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Attendance <?= $selected_month ?>');
  XLSX.writeFile(wb, `Attendance_<?= $selected_month ?>.xlsx`);
});
</script>
</body>
</html>