<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
<title>ClassTrack — Dashboard</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Sora:wght@400;600;700;800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap" rel="stylesheet">
<style>
:root{
  --navy-950:#0B1526;--navy-900:#0F1E36;--navy-800:#152B4A;--navy-700:#1D3B63;
  --teal-500:#2E5AA8;--teal-400:#4C7BC9;--amber-500:#A9791F;--coral-500:#B23A3A;
  --vivid-blue:#2F6FE4;--vivid-purple:#7C4DE0;--vivid-amber:#E29A2E;
  --vivid-rose:#E1477E;--vivid-green:#1F9D6C;
  --bg:#EEF1F6;--surface:#FFFFFF;--surface-2:#F5F7FA;--line:#DFE4EC;
  --ink-900:#0B1526;--ink-700:#37425A;--ink-500:#6B7690;--ink-300:#AEB6C8;
  --radius:14px;--radius-sm:9px;
  --shadow-sm:0 1px 2px rgba(15,30,54,.06);--shadow-md:0 8px 24px rgba(15,30,54,.08);
  --shadow-lg:0 16px 40px rgba(15,30,54,.14);
  --font-display:'Sora',sans-serif;--font-body:'Inter',sans-serif;--font-mono:'JetBrains Mono',monospace;
  --white:#fff;--white-a05:rgba(255,255,255,.05);--white-a06:rgba(255,255,255,.06);
  --white-a08:rgba(255,255,255,.08);--white-a72:rgba(255,255,255,.72);
  --teal-tint-10:rgba(46,90,168,.10);--teal-tint-12:rgba(46,90,168,.12);
  --teal-tint-14:rgba(46,90,168,.14);--teal-tint-35:rgba(46,90,168,.35);
  --vivid-blue-tint:rgba(47,111,228,.14);--vivid-purple-tint:rgba(124,77,224,.14);
  --vivid-amber-tint:rgba(226,154,46,.16);--vivid-rose-tint:rgba(225,71,126,.14);
  --amber-tint-14:rgba(169,121,31,.14);--amber-tint-16:rgba(169,121,31,.16);
  --badge-red-bg:rgba(240,101,79,.12);--badge-red-text:#C43E29;
  --badge-amber-text:#8A5F1F;--badge-green-text:#1E4A87;
  --badge-slate-bg:rgba(116,128,153,.12);
  --danger-border:#F6D2CB;--danger-bg-hover:#FEF3F1;
  --overlay-modal:rgba(11,21,38,.5);--overlay-sidebar:rgba(0,0,0,.4);
  --logout-bg:rgba(178,58,58,.14);--logout-text:#F1A9A0;--logout-hover-bg:rgba(178,58,58,.22);
}
*{box-sizing:border-box;margin:0;padding:0;}
/* Hide scrollbars everywhere but keep scroll functional */
*:not(.hist-table-wrap):not(.hist-fake-scroll){scrollbar-width:none;-ms-overflow-style:none;}
*:not(.hist-table-wrap):not(.hist-fake-scroll)::-webkit-scrollbar{display:none;}
body{font-family:var(--font-body);background:var(--bg);color:var(--ink-900);min-height:100vh;-webkit-font-smoothing:antialiased;}
::selection{background:var(--teal-400);color:var(--navy-950);}
a{color:inherit;text-decoration:none;}
button{font-family:inherit;cursor:pointer;}
ul{list-style:none;}
:focus-visible{outline:2px solid var(--teal-500);outline-offset:2px;}
.app{display:flex;min-height:100vh;}
</style>
<style>
/* Sidebar */
.sidebar{width:250px;flex-shrink:0;background:linear-gradient(185deg,var(--navy-950),var(--navy-900) 60%);color:var(--white);display:flex;flex-direction:column;position:fixed;top:0;left:0;bottom:0;z-index:100;transition:transform .25s ease;}
.sidebar-brand{display:flex;align-items:center;gap:10px;padding:22px 20px 18px;border-bottom:1px solid var(--white-a08);}
.brand-mark{width:34px;height:34px;border-radius:9px;background:conic-gradient(from 220deg,var(--navy-950),var(--teal-500) 55%,var(--teal-400) 100%);display:flex;align-items:center;justify-content:center;font-family:var(--font-display);font-weight:800;font-size:15px;color:var(--navy-950);flex-shrink:0;}
.brand-text{font-family:var(--font-display);font-weight:700;font-size:16.5px;letter-spacing:.2px;}
.brand-sub{font-size:10.5px;color:var(--ink-300);letter-spacing:.6px;text-transform:uppercase;margin-top:1px;}
.nav-section-label{font-size:10.5px;letter-spacing:1.2px;text-transform:uppercase;color:var(--ink-300);opacity:.6;padding:18px 20px 8px;font-weight:600;}
.nav-list{padding:0 10px;}
.nav-item{display:flex;align-items:center;gap:11px;padding:10px 12px;margin:2px 0;border-radius:9px;color:var(--white-a72);font-size:14px;font-weight:500;cursor:pointer;border:none;background:none;width:100%;text-align:left;transition:background .15s,color .15s;position:relative;}
.nav-item:hover{background:var(--white-a06);color:var(--white);}
.nav-item.active{background:var(--teal-tint-14);color:var(--white);}
.nav-item.active::before{content:'';position:absolute;left:-10px;top:8px;bottom:8px;width:3px;border-radius:3px;background:var(--teal-400);}
.nav-icon{width:18px;height:18px;flex-shrink:0;display:flex;align-items:center;justify-content:center;}
.nav-icon svg{width:100%;height:100%;}
.sidebar-footer{margin-top:auto;padding:16px;border-top:1px solid var(--white-a08);}
.logout-btn{display:flex;align-items:center;gap:10px;padding:10px 12px;border-radius:10px;background:var(--logout-bg);border:none;width:100%;text-align:left;cursor:pointer;color:var(--logout-text);font-size:13.5px;font-weight:600;transition:background .15s;}
.logout-btn:hover{background:var(--logout-hover-bg);}
/* Main */
.main{margin-left:250px;flex:1;min-width:0;display:flex;flex-direction:column;}
.topbar{height:72px;flex-shrink:0;background:var(--surface);border-bottom:1px solid var(--line);box-shadow:0 1px 0 rgba(11,21,38,.02),0 6px 16px -12px rgba(11,21,38,.15);display:flex;align-items:center;gap:18px;padding:0 28px;position:sticky;top:0;z-index:40;}
.menu-toggle{display:none;background:none;border:none;padding:6px;color:var(--ink-700);}
#mobileSearchBtn{display:none;}
.page-heading{flex-shrink:0;}
.page-heading .eyebrow{display:block;font-size:10.5px;font-weight:700;letter-spacing:1px;text-transform:uppercase;color:var(--teal-500);margin-bottom:2px;}
.page-heading h1{font-family:var(--font-display);font-size:20px;font-weight:700;color:var(--ink-900);line-height:1.2;}
.topbar-divider{width:1px;align-self:stretch;margin:16px 2px;background:var(--line);flex-shrink:0;}
.topbar-search{flex:1;max-width:380px;display:flex;align-items:center;gap:9px;background:var(--surface-2);border:1px solid var(--line);border-radius:10px;padding:9px 14px;color:var(--ink-500);margin-left:auto;transition:border-color .15s,background .15s;}
.topbar-search:focus-within{border-color:var(--teal-500);background:var(--surface);box-shadow:0 0 0 3px var(--teal-tint-10);}
.topbar-search input{border:none;background:none;outline:none;font-size:13.5px;width:100%;color:var(--ink-900);}
.topbar-search input::placeholder{color:var(--ink-300);}
.topbar-search svg{width:16px;height:16px;flex-shrink:0;}
.topbar-actions{display:flex;align-items:center;gap:10px;flex-shrink:0;margin-left:auto;}
.icon-btn{width:40px;height:40px;border-radius:10px;border:1px solid var(--line);background:var(--surface);display:flex;align-items:center;justify-content:center;color:var(--ink-700);position:relative;transition:background .15s,border-color .15s,color .15s;}
.icon-btn:hover{background:var(--surface-2);color:var(--navy-950);border-color:var(--ink-300);}
.icon-btn svg{width:17px;height:17px;}
.icon-btn .dot{position:absolute;top:7px;right:8px;width:7px;height:7px;border-radius:50%;background:var(--coral-500);box-shadow:0 0 0 2px var(--surface);}
.topbar-account{display:flex;align-items:center;gap:10px;background:none;border:1px solid transparent;border-radius:11px;padding:5px 8px 5px 5px;transition:background .15s,border-color .15s;}
.topbar-account:hover{background:var(--surface-2);border-color:var(--line);}
.topbar-avatar{width:38px;height:38px;border-radius:50%;flex-shrink:0;background:linear-gradient(135deg,var(--teal-400),var(--navy-800));display:flex;align-items:center;justify-content:center;font-family:var(--font-display);font-weight:700;font-size:13px;color:var(--white);box-shadow:0 0 0 2px var(--surface),0 0 0 3px var(--line);}
.topbar-account-text{display:flex;flex-direction:column;align-items:flex-start;line-height:1.3;}
.topbar-account-name{font-size:13px;font-weight:700;color:var(--ink-900);}
.topbar-account-role{font-size:11px;color:var(--ink-500);}
.topbar-account .chev{width:14px;height:14px;color:var(--ink-500);flex-shrink:0;}
</style>
<style>
/* Content & Views */
.content{padding:26px;flex:1;}
.view{display:none;animation:fadeIn .25s ease;}
.view.active{display:block;}
@keyframes fadeIn{from{opacity:0;transform:translateY(6px);}to{opacity:1;transform:translateY(0);}}
/* Hide mobile nav on desktop */
.mobile-nav{display:none;}
/* Batch popup */
.batch-popup.show{display:block !important;}
/* Attendance history — desktop table / mobile cards */
.hist-desktop-view{display:block;}
.hist-mobile-view{display:none;}
/* Stat cards */
.stat-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:20px;margin-bottom:24px;align-items:stretch;}
.stat-card{background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);padding:18px 18px 16px;box-shadow:var(--shadow-sm);position:relative;overflow:hidden;min-height:160px;display:flex;flex-direction:column;}
.stat-card::before{content:'';position:absolute;top:0;left:0;right:0;height:4px;}
.stat-card .stat-icon{width:38px;height:38px;border-radius:10px;display:flex;align-items:center;justify-content:center;margin-bottom:12px;}
.stat-icon svg{width:19px;height:19px;}
.stat-card.c1::before{background:var(--vivid-blue);}
.stat-card.c2::before{background:var(--vivid-purple);}
.stat-card.c3::before{background:var(--vivid-amber);}
.stat-card.c4::before{background:var(--vivid-rose);}
.stat-card.c1 .stat-icon{background:var(--vivid-blue-tint);color:var(--vivid-blue);}
.stat-card.c2 .stat-icon{background:var(--vivid-purple-tint);color:var(--vivid-purple);}
.stat-card.c3 .stat-icon{background:var(--vivid-amber-tint);color:var(--vivid-amber);}
.stat-card.c4 .stat-icon{background:var(--vivid-rose-tint);color:var(--vivid-rose);}
.stat-value{font-family:var(--font-display);font-size:26px;font-weight:800;}
.stat-label{font-size:12.5px;color:var(--ink-500);margin-top:2px;}
.stat-trend{font-size:11.5px;font-weight:600;margin-top:9px;display:flex;align-items:center;gap:4px;}
.stat-trend.up{color:var(--vivid-green);}
.stat-trend.down{color:var(--vivid-rose);}
/* Panel */
.dash-grid{display:grid;grid-template-columns:1.5fr 1fr;gap:20px;}
.panel{background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);padding:20px;box-shadow:var(--shadow-sm);}
.panel-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;}
.panel-head h3{font-family:var(--font-display);font-size:15px;font-weight:700;}
.panel-head .muted{font-size:12px;color:var(--ink-500);}
/* Chart */
.week-chart{display:flex;align-items:flex-end;gap:10px;height:160px;padding-top:6px;}
.week-bar-col{flex:1;display:flex;flex-direction:column;align-items:center;gap:8px;height:100%;justify-content:flex-end;}
.week-bar{width:100%;max-width:34px;border-radius:7px 7px 3px 3px;background:linear-gradient(180deg,var(--teal-400),var(--teal-500));transition:transform .15s;}
.week-bar:hover{transform:scaleY(1.03);}
.week-bar-col span{font-size:10.5px;color:var(--ink-500);font-weight:600;}
/* Ring */
.ring-wrap{display:flex;align-items:center;gap:16px;}
.ring{position:relative;width:96px;height:96px;flex-shrink:0;}
.ring svg{transform:rotate(-90deg);}
.ring-value{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;font-family:var(--font-display);font-weight:800;font-size:19px;}
.ring-legend{display:flex;flex-direction:column;gap:8px;font-size:12.5px;}
.ring-legend li{display:flex;align-items:center;gap:8px;}
.legend-dot{width:9px;height:9px;border-radius:3px;flex-shrink:0;}
/* Activity */
.activity-item{display:flex;gap:11px;align-items:flex-start;padding:11px 0;border-bottom:1px solid var(--line);}
.activity-item:last-child{border-bottom:none;padding-bottom:0;}
.activity-dot{width:8px;height:8px;border-radius:50%;margin-top:5px;flex-shrink:0;}
.activity-text{font-size:13px;color:var(--ink-700);line-height:1.45;}
.activity-text b{color:var(--ink-900);}
.activity-time{font-size:11px;color:var(--ink-300);margin-top:2px;}
/* Responsive */
.overlay-bg{position:fixed;inset:0;background:var(--overlay-sidebar);z-index:90;display:none;}
.overlay-bg.show{display:block;}
@media(max-width:1100px){.stat-grid{grid-template-columns:repeat(2,1fr);}.dash-grid{grid-template-columns:1fr;}}
@media(max-width:820px){
  .sidebar{transform:translateX(-100%);}
  .sidebar.open{transform:translateX(0);}
  .main{margin-left:0;}
  .menu-toggle{display:flex;flex-shrink:0;}
  .topbar{padding:0 14px;gap:10px;height:64px;}
  .topbar-search{display:none !important;}
  .topbar-divider{display:none !important;}
  .page-heading h1{font-size:16px;}
  .topbar-account-text,.topbar-account .chev{display:none;}
  .topbar-actions{margin-left:auto;}
  .content{padding:14px;}
  .stat-grid{grid-template-columns:1fr 1fr;gap:12px;margin-bottom:18px;}

  /* Sidebar footer above mobile nav */
  .sidebar{padding-bottom:70px;}
  /* Show search btn, hide on desktop */
  #mobileSearchBtn{display:flex !important;}
  /* Attendance history — show cards, hide table on mobile */
  .hist-desktop-view{display:none !important;}
  .hist-mobile-view{display:flex !important;flex-direction:column;gap:12px;padding:16px;}

  /* ── Mobile table → card layout ── */
  .table-card{background:none;border:none;box-shadow:none;}
  .table-card table{display:block;}
  .table-card thead{display:none;}
  .table-card tbody{display:flex;flex-direction:column;gap:12px;}
  .table-card tbody tr{
    display:block;
    background:var(--surface);
    border:1px solid var(--line);
    border-radius:var(--radius);
    box-shadow:var(--shadow-sm);
    padding:12px 16px;
  }
  .table-card tbody td{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:10px;
    padding:7px 0;
    border-bottom:1px dashed var(--line);
    font-size:13px;
  }
  .table-card tbody td:last-child{border-bottom:none;padding-bottom:0;}
  .table-card tbody td:first-child{padding-top:0;}
  .table-card tbody td::before{
    content:attr(data-label);
    font-size:10.5px;
    font-weight:700;
    color:var(--ink-500);
    text-transform:uppercase;
    letter-spacing:.4px;
    flex-shrink:0;
    white-space:nowrap;
  }
  /* first column (name/course) takes full width */
  .table-card tbody td:first-child{flex-direction:column;align-items:flex-start;}
  .table-card tbody td:first-child::before{display:none;}
  /* actions column */
  .table-card tbody td:last-child{justify-content:flex-end;}
  .table-card tbody td:last-child::before{display:none;}

  /* ── Mobile bottom nav ── */
  .mobile-nav{
    display:flex;
    position:fixed;bottom:0;left:0;right:0;
    background:var(--surface);
    border-top:1px solid var(--line);
    box-shadow:0 -4px 16px rgba(11,21,38,.08);
    z-index:150;
    padding:6px 0 calc(6px + env(safe-area-inset-bottom));
  }
  .mobile-nav-item{
    flex:1;display:flex;flex-direction:column;align-items:center;gap:3px;
    background:none;border:none;cursor:pointer;padding:6px 2px;
    color:var(--ink-400,#9AA3B5);font-size:9px;font-weight:600;
    font-family:var(--font-body);text-transform:uppercase;letter-spacing:.3px;
    transition:color .15s;
  }
  .mobile-nav-item svg{width:20px;height:20px;}
  .mobile-nav-item.active,.mobile-nav-item:hover{color:var(--teal-500);}
  /* push content above footer */
  .main .content{padding-bottom:80px;}
}
</style>
</head>
<body>
<div class="overlay-bg" id="overlayBg"></div>
<div class="app">

  <!-- SIDEBAR -->
  <aside class="sidebar" id="sidebar">
    <div class="sidebar-brand">
      <div class="brand-mark" style="color: #FFF">CT</div>
      <div>
        <div class="brand-text">ClassTrack</div>
        <div class="brand-sub">Attendance System</div>
      </div>
    </div>

    <div class="nav-section-label">Overview</div>
    <div class="nav-list">
      <button class="nav-item active" data-view="dashboard">
        <span class="nav-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="9" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="12" width="7" height="9" rx="1.5"/><rect x="3" y="16" width="7" height="5" rx="1.5"/></svg></span>
        Dashboard
      </button>
    </div>

    <div class="nav-section-label">Academics</div>
    <div class="nav-list">
      <button class="nav-item" data-view="courses">
        <span class="nav-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg></span>
        Courses
      </button>
      <button class="nav-item" data-view="batches">
        <span class="nav-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M3 10h18M8 2v4M16 2v4"/></svg></span>
        Batches
      </button>
      <button class="nav-item" data-view="students">
        <span class="nav-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75"/></svg></span>
        Students
      </button>
    </div>

    <div class="nav-section-label">Tracking</div>
    <div class="nav-list">
      <button class="nav-item" data-view="attendance">
        <span class="nav-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg></span>
        Attendance
      </button>
      <button class="nav-item" data-view="transfers">
        <span class="nav-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 1l4 4-4 4"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><path d="M7 23l-4-4 4-4"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg></span>
        Transfer Students
      </button>
      <button class="nav-item" data-view="reports">
        <span class="nav-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3v18h18"/><path d="M18 17V9M13 17V5M8 17v-4"/></svg></span>
        Reports
      </button>
    </div>

    <div class="sidebar-footer">
      <form method="POST" action="<?php echo e(route('logout')); ?>" id="logoutForm">
        <?php echo csrf_field(); ?>
        <button type="submit" class="logout-btn">
          <span class="nav-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><path d="M16 17l5-5-5-5"/><path d="M21 12H9"/></svg></span>
          Logout
        </button>
      </form>
    </div>
  </aside>

  <!-- MAIN -->
  <div class="main">
    <header class="topbar">
      <button class="menu-toggle" id="menuToggle">
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M4 6h16M4 12h16M4 18h16"/></svg>
      </button>

      <div class="page-heading">
        <span class="eyebrow" id="pageEyebrow">Overview</span>
        <h1 id="pageTitle">Dashboard</h1>
      </div>

      <div class="topbar-divider"></div>

      <div class="topbar-search" style="position:relative;">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
        <input type="text" id="desktopSearchInput" placeholder="Search students, batches…" autocomplete="off">
        <div id="desktopSearchDropdown" style="display:none;position:absolute;top:calc(100% + 8px);left:0;right:0;background:var(--surface);border:1px solid var(--line);border-radius:12px;box-shadow:var(--shadow-md);z-index:200;max-height:400px;overflow-y:auto;min-width:360px;"></div>
      </div>

      <div class="topbar-actions">
        <button class="icon-btn" id="mobileSearchBtn" title="Search" onclick="openMobileSearch();">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
        </button>
        <div class="topbar-divider"></div>
        <button class="topbar-account" id="topAccountBtn">
          <div class="topbar-avatar">
            <?php if(auth()->user()->photo): ?>
              <img src="<?php echo e(asset('storage/' . auth()->user()->photo)); ?>" style="width:100%;height:100%;object-fit:contain;border-radius:50%;background:#fff;">
            <?php else: ?>
              <?php echo e(auth()->user()->initials); ?>

            <?php endif; ?>
          </div>
          <div class="topbar-account-text">
            <span class="topbar-account-name"><?php echo e(auth()->user()->name); ?></span>
            <span class="topbar-account-role"><?php echo e(auth()->user()->designation); ?></span>
          </div>
          <svg class="chev" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>
        </button>
      </div>
    </header>

    <main class="content">

      <!-- DASHBOARD VIEW -->
      <section class="view active" id="view-dashboard">
        <div class="stat-grid">
          <div class="stat-card c1">
            <div class="stat-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg></div>
            <div class="stat-value"><?php echo e($totalCourses); ?></div>
            <div class="stat-label">Active Courses</div>
            <div class="stat-trend up">↑ steady this term</div>
          </div>
          <div class="stat-card c2">
            <div class="stat-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M3 10h18M8 2v4M16 2v4"/></svg></div>
            <div class="stat-value"><?php echo e($totalBatches); ?></div>
            <div class="stat-label">Running Batches</div>
            <div class="stat-trend up">↑ active now</div>
          </div>
          <div class="stat-card c3">
            <div class="stat-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/></svg></div>
            <div class="stat-value"><?php echo e($totalStudents); ?></div>
            <div class="stat-label">Enrolled Students</div>
            <div class="stat-trend up">↑ active</div>
          </div>
          <div class="stat-card c4">
            <div class="stat-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg></div>
            <!-- <div class="stat-value"><?php echo e($todayPct !== null ? $todayPct.'%' : '—'); ?></div> -->
            <div class="stat-label">Today's Attendance</div>
            <?php if($currentBatch): ?>
              <div style="margin-top:10px;display:flex;align-items:center;justify-content:space-between;gap:8px;">
                <span style="font-size:12px;font-weight:600;color:var(--ink-500);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;"><?php echo e($currentBatch->name); ?></span>
                <span style="font-size:13px;font-weight:800;color:var(--ink-900);flex-shrink:0;"><?php echo e($currentBatchPresent); ?>/<?php echo e($currentBatchTotal); ?></span>
              </div>
              <div style="height:4px;border-radius:2px;background:var(--line);overflow:hidden;margin-top:5px;">
                <?php $cp = $currentBatchTotal > 0 ? round($currentBatchPresent/$currentBatchTotal*100) : 0; ?>
                <div style="height:100%;width:<?php echo e($cp); ?>%;background:<?php echo e($cp >= 75 ? 'var(--vivid-green)' : ($cp >= 50 ? 'var(--vivid-amber)' : 'var(--vivid-rose)')); ?>;border-radius:2px;"></div>
              </div>
            <?php endif; ?>
            <?php if($todayBatchBreakdown->count() > 0): ?>
              <button onclick="openBdModal('today')" style="margin-top:10px;font-size:11.5px;font-weight:600;color:var(--vivid-rose);background:var(--vivid-rose-tint);border:none;border-radius:6px;padding:3px 9px;cursor:pointer;font-family:var(--font-body);">
                <?php echo e($todayBatchBreakdown->count()); ?> batch<?php echo e($todayBatchBreakdown->count() > 1 ? 'es' : ''); ?> today →
              </button>
            <?php endif; ?>
          </div>
        </div>

        <!-- <div class="dash-grid">
          <div class="panel">
            <div class="panel-head">
              <h3>Weekly Attendance Trend</h3>
              <span class="muted">Last 7 days</span>
            </div>
            <div class="week-chart" id="weekChart"></div>
          </div>
          <div class="panel">
            <div class="panel-head"><h3>Overall Attendance Split</h3></div>
            <div class="ring-wrap">
              <div class="ring">
                <svg width="96" height="96" viewBox="0 0 96 96">
                  <circle cx="48" cy="48" r="40" fill="none" stroke="#EEF1F6" stroke-width="12"/>
                  <circle id="ringPresent" cx="48" cy="48" r="40" fill="none" stroke="#2E5AA8" stroke-width="12"
                    stroke-dasharray="<?php echo e(round($overallPct / 100 * 251)); ?> 251" stroke-linecap="round"/>
                </svg>
                <div class="ring-value"><?php echo e($overallPct); ?>%</div>
              </div>
              <ul class="ring-legend">
                <li><span class="legend-dot" style="background:var(--teal-500)"></span> Present — <b><?php echo e($present); ?></b></li>
                <li><span class="legend-dot" style="background:var(--amber-500)"></span> Late — <b><?php echo e($late); ?></b></li>
                <li><span class="legend-dot" style="background:var(--coral-500)"></span> Absent — <b><?php echo e($absent); ?></b></li>
              </ul>
            </div>
            <?php if($overallBatchBreakdown->count() > 0): ?>
              <button onclick="openBdModal('overall')" style="margin-top:12px;font-size:11.5px;font-weight:600;color:var(--teal-500);background:var(--teal-tint-14);border:none;border-radius:6px;padding:3px 9px;cursor:pointer;font-family:var(--font-body);">
                <?php echo e($overallBatchBreakdown->count()); ?> batch breakdown →
              </button>
            <?php endif; ?>
          </div>
        </div> -->

        <div class="panel" style="margin-top:16px;">
          <div class="panel-head"><h3>Recent Activity</h3></div>
          <div id="activityFeed">
            <?php $__empty_1 = true; $__currentLoopData = $recentActivity; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $act): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
              <div class="activity-item">
                <div class="activity-dot" style="background:<?php echo e($act['status']==='present' ? 'var(--vivid-green)' : ($act['status']==='late' ? 'var(--vivid-amber)' : 'var(--coral-500)')); ?>"></div>
                <div>
                  <div class="activity-text">
                    <b><?php echo e($act['student']); ?></b> marked
                    <b><?php echo e(ucfirst($act['status'])); ?></b>
                    in <b><?php echo e($act['batch']); ?></b> on <?php echo e($act['date']); ?>

                  </div>
                  <div class="activity-time"><?php echo e($act['time']); ?></div>
                </div>
              </div>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
              <div class="activity-item">
                <div class="activity-dot" style="background:var(--teal-500)"></div>
                <div>
                  <div class="activity-text">System ready. <b>Add courses and batches</b> to get started.</div>
                  <div class="activity-time">Just now</div>
                </div>
              </div>
            <?php endif; ?>
          </div>
        </div>
      </section>

      <!-- COURSES VIEW -->
      <section class="view" id="view-courses">

        <style>
          /* ── Toolbar ── */
          .toolbar{display:flex;align-items:center;gap:12px;margin-bottom:18px;flex-wrap:wrap;background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);padding:14px 16px;box-shadow:var(--shadow-sm);}
          .search-field{position:relative;flex:1;min-width:180px;}
          .search-field svg{position:absolute;left:12px;top:50%;transform:translateY(-50%);width:15px;height:15px;color:var(--ink-500);pointer-events:none;}
          .search-field input{width:100%;border:1px solid var(--line);background:var(--surface-2);border-radius:9px;padding:9.5px 12px 9.5px 36px;font-size:13.5px;color:var(--ink-900);outline:none;font-family:var(--font-body);transition:border-color .15s,background .15s,box-shadow .15s;}
          .search-field input::placeholder{color:var(--ink-300);}
          .search-field input:focus{border-color:var(--teal-500);background:var(--surface);box-shadow:0 0 0 3px var(--teal-tint-10);}
          .select-field{position:relative;flex-shrink:0;}
          .select-field select{appearance:none;-webkit-appearance:none;border:1px solid var(--line);background:var(--surface-2);border-radius:9px;padding:9.5px 32px 9.5px 12px;font-size:13.5px;color:var(--ink-900);outline:none;min-width:170px;cursor:pointer;font-family:var(--font-body);transition:border-color .15s,background .15s;}
          .select-field select:focus{border-color:var(--teal-500);background:var(--surface);}
          .select-field svg{position:absolute;right:11px;top:50%;transform:translateY(-50%);width:13px;height:13px;color:var(--ink-500);pointer-events:none;}
          .spacer{flex:1;}
          /* ── Table card ── */
          .table-card{background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);overflow:hidden;box-shadow:var(--shadow-sm);}
          table{width:100%;border-collapse:collapse;}
          thead th{text-align:left;font-size:11px;letter-spacing:.6px;text-transform:uppercase;color:var(--ink-500);font-weight:700;padding:13px 18px;background:var(--surface-2);border-bottom:1px solid var(--line);}
          tbody td{padding:13px 18px;font-size:13.5px;color:var(--ink-700);border-bottom:1px solid var(--line);}
          tbody tr:last-child td{border-bottom:none;}
          tbody tr:hover{background:var(--surface-2);}
          .cell-main{color:var(--ink-900);font-weight:600;}
          .cell-sub{font-size:11.5px;color:var(--ink-500);margin-top:1px;}
          .row-flex{display:flex;align-items:center;gap:10px;}
          .course-icon{width:38px;height:38px;border-radius:11px;flex-shrink:0;display:flex;align-items:center;justify-content:center;font-family:var(--font-display);font-weight:700;font-size:13px;color:var(--white);}
          .duration-pill{display:inline-flex;align-items:center;gap:5px;padding:4px 11px;border-radius:100px;font-size:12px;font-weight:600;background:var(--teal-tint-14);color:var(--badge-green-text);white-space:nowrap;}
          .duration-pill svg{width:12px;height:12px;flex-shrink:0;}
          .badge{display:inline-flex;align-items:center;gap:5px;padding:4px 10px;border-radius:100px;font-size:11.5px;font-weight:600;}
          .badge-dot{width:6px;height:6px;border-radius:50%;}
          .badge-green{background:var(--teal-tint-12);color:var(--badge-green-text);}
          .badge-amber{background:var(--amber-tint-14);color:var(--badge-amber-text);}
          .badge-slate{background:var(--badge-slate-bg);color:var(--ink-700);}
          .badge-red{background:var(--badge-red-bg);color:var(--badge-red-text);}
          .row-actions{display:flex;gap:6px;justify-content:flex-end;}
          .row-actions button{width:30px;height:30px;border-radius:8px;border:1px solid var(--line);background:var(--surface);display:flex;align-items:center;justify-content:center;color:var(--ink-500);cursor:pointer;transition:background .15s,color .15s;}
          .row-actions button:hover{background:var(--surface-2);color:var(--ink-900);}
          .row-actions button.del:hover{color:var(--coral-500);border-color:var(--danger-border);background:var(--danger-bg-hover);}
          .row-actions svg{width:14.5px;height:14.5px;}
          .empty-state{padding:50px 20px;text-align:center;color:var(--ink-500);}
          .empty-state svg{width:40px;height:40px;margin-bottom:10px;color:var(--ink-300);}
          .empty-state p{font-size:13.5px;}
          /* btn-accent */
          .btn-accent{background:var(--teal-500);color:var(--white);}
          .btn-accent:hover{box-shadow:0 8px 20px var(--teal-tint-35);}
          /* Toolbar spacer — collapses when button wraps to next line */
          .toolbar .spacer{flex:1;}
          /* When the accent button wraps to a new row it should be full width */
          @media(max-width:600px){
            .toolbar{flex-wrap:wrap;}
            .toolbar .spacer{display:none;}
            .toolbar .btn-accent{width:100%;justify-content:center;order:3;}
            .toolbar .search-field{order:1;min-width:0;flex:1 1 140px;}
            .toolbar .select-field{order:2;flex-shrink:0;}
          }
          /* Student toolbar mobile: search full width row1, combos row2, button row3 */
          @media(max-width:600px){
            .toolbar-students .search-field{order:1;flex:1 1 100%;width:100%;}
            .toolbar-students .select-field{order:2;flex:1 1 calc(50% - 6px);min-width:0;}
            .toolbar-students .spacer{display:none;}
            .toolbar-students .btn-accent{order:3;width:100%;justify-content:center;}
          }
          /* Course Modal */
          .c-modal-overlay{position:fixed;inset:0;background:rgba(11,21,38,.5);backdrop-filter:blur(2px);z-index:200;display:none;align-items:center;justify-content:center;padding:20px;}
          .c-modal-overlay.open{display:flex;}
          .c-modal{background:var(--surface);border-radius:16px;width:100%;max-width:420px;box-shadow:0 16px 40px rgba(15,30,54,.18);animation:cModalIn .18s ease;}
          @keyframes cModalIn{from{opacity:0;transform:scale(.96) translateY(8px);}to{opacity:1;transform:none;}}
          .c-modal-head{display:flex;align-items:center;justify-content:space-between;padding:18px 20px;border-bottom:1px solid var(--line);}
          .c-modal-head h3{font-family:var(--font-display);font-size:16px;font-weight:700;}
          .c-modal-close{width:30px;height:30px;border:none;background:var(--surface-2);border-radius:8px;color:var(--ink-500);display:flex;align-items:center;justify-content:center;cursor:pointer;}
          .c-modal-close:hover{background:var(--line);color:var(--ink-900);}
          .c-modal-close svg{width:14px;height:14px;}
          .c-modal-body{padding:20px;display:flex;flex-direction:column;gap:14px;}
          .c-modal-body .field{width:100%;}
          .c-modal-body .field input,.c-modal-body .field select{width:100%;min-width:0;border:1px solid var(--line);border-radius:9px;padding:9px 11px;font-size:13.5px;background:var(--surface);color:var(--ink-900);outline:none;font-family:var(--font-body);transition:border-color .15s;}
          .c-modal-body .field input:focus,.c-modal-body .field select:focus{border-color:var(--teal-500);}
          .c-modal-foot{display:flex;justify-content:flex-end;gap:10px;padding:16px 20px;border-top:1px solid var(--line);}
          .c-field-err{font-size:12px;color:var(--coral-500);margin-top:3px;display:none;}
          /* Toast */
          .ct-toast{position:fixed;bottom:24px;left:50%;transform:translateX(-50%) translateY(20px);background:var(--navy-950);color:var(--white);padding:12px 20px;border-radius:10px;font-size:13px;font-weight:500;box-shadow:0 16px 40px rgba(15,30,54,.14);display:flex;align-items:center;gap:9px;opacity:0;pointer-events:none;transition:all .25s ease;z-index:400;}
          .ct-toast.show{opacity:1;transform:translateX(-50%) translateY(0);}
          .ct-toast .dot{width:8px;height:8px;border-radius:50%;background:var(--teal-400);flex-shrink:0;}
          /* Delete confirm */
          .del-overlay{position:fixed;inset:0;background:rgba(11,21,38,.5);backdrop-filter:blur(2px);z-index:300;display:none;align-items:center;justify-content:center;padding:20px;}
          .del-overlay.open{display:flex;}
          .del-modal{background:var(--surface);border-radius:16px;width:100%;max-width:360px;box-shadow:0 16px 40px rgba(15,30,54,.18);animation:cModalIn .18s ease;}
          .confirm-text{font-size:13.5px;color:var(--ink-700);line-height:1.5;}
          .confirm-text b{color:var(--ink-900);}
        </style>

        <div class="toolbar">
          <div class="search-field">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
            <input placeholder="Search courses…" id="courseSearch">
          </div>
          <div class="select-field">
            <select id="courseStatusFilter">
              <option value="">All statuses</option>
              <option value="Active">Active</option>
              <option value="Upcoming">Upcoming</option>
              <option value="Inactive">Inactive</option>
            </select>
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>
          </div>
          <span class="spacer"></span>
          <button class="btn btn-accent" id="addCourseBtn">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M12 5v14M5 12h14"/></svg>
            Add Course
          </button>
        </div>

        <div class="table-card">
          <table>
            <thead>
              <tr>
                <th>Course</th>
                <th>Duration</th>
                <th>Status</th>
                <th style="text-align:right">Actions</th>
              </tr>
            </thead>
            <tbody id="courseTableBody"></tbody>
          </table>
          <div class="empty-state" id="courseEmpty" style="display:none;">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>
            <p>No courses yet — add your first course to get started.</p>
          </div>
        </div>
      </section>

      <!-- COURSE MODAL (Add / Edit) -->
      <div class="c-modal-overlay" id="courseModalOverlay">
        <div class="c-modal">
          <div class="c-modal-head">
            <h3 id="courseModalTitle">Add Course</h3>
            <button class="c-modal-close" id="closeCourseModal">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg>
            </button>
          </div>
          <div class="c-modal-body">
            <input type="hidden" id="cm_id">
            <div class="field">
              <label>Course Name</label>
              <input type="text" id="cm_name" placeholder="e.g. Web Development">
              <span class="c-field-err" id="cm_nameErr">Course name is required.</span>
            </div>
            <div class="field">
              <label>Course Code</label>
              <input type="text" id="cm_code" placeholder="e.g. WD-101">
              <span class="c-field-err" id="cm_codeErr">Course code is required.</span>
            </div>
            <div class="field">
              <label>Duration (months)</label>
              <input type="number" id="cm_duration" min="1" max="60" placeholder="e.g. 6">
              <span class="c-field-err" id="cm_durErr">Enter a valid duration (1–60).</span>
            </div>
            <div class="field">
              <label>Status</label>
              <select id="cm_status">
                <option value="Active">Active</option>
                <option value="Upcoming">Upcoming</option>
                <option value="Inactive">Inactive</option>
              </select>
            </div>
          </div>
          <div class="c-modal-foot">
            <button class="btn btn-ghost" id="cancelCourseModal">Cancel</button>
            <button class="btn btn-primary" id="saveCourseBtn">Save Course</button>
          </div>
        </div>
      </div>

      <!-- DELETE CONFIRM MODAL -->
      <div class="del-overlay" id="delCourseOverlay">
        <div class="del-modal">
          <div class="c-modal-head">
            <h3>Delete Course?</h3>
            <button class="c-modal-close" id="closeDelCourse">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg>
            </button>
          </div>
          <div class="c-modal-body">
            <p class="confirm-text" id="delCourseText">This action cannot be undone.</p>
          </div>
          <div class="c-modal-foot">
            <button class="btn btn-ghost" id="cancelDelCourse">Cancel</button>
            <button class="btn" style="background:var(--coral-500);color:#fff;" id="confirmDelCourse">Delete</button>
          </div>
        </div>
      </div>

      <!-- Toast -->
      <div class="ct-toast" id="ctToast"><span class="dot"></span><span id="ctToastMsg">Saved</span></div>
      <!-- BATCHES VIEW -->
      <section class="view" id="view-batches">
        <style>
          .schedule-editor{display:flex;flex-direction:column;gap:8px;}
          .schedule-row{display:flex;align-items:center;gap:8px;}
          .schedule-row select,.schedule-row input[type="time"]{flex:1;min-width:0;border:1px solid var(--line);border-radius:9px;padding:8px 10px;font-size:13px;color:var(--ink-900);outline:none;background:var(--surface);font-family:var(--font-body);}
          .schedule-row select:focus,.schedule-row input[type="time"]:focus{border-color:var(--teal-500);}
          .schedule-row-remove{width:32px;height:32px;flex-shrink:0;border-radius:8px;border:1px solid var(--line);background:var(--surface);color:var(--ink-500);display:flex;align-items:center;justify-content:center;cursor:pointer;transition:background .15s,color .15s,border-color .15s;}
          .schedule-row-remove:hover{background:var(--danger-bg-hover);color:var(--coral-500);border-color:var(--danger-border);}
          .add-schedule-btn{margin-top:4px;}
          /* batch modal */
          .b-modal-overlay{position:fixed;inset:0;background:rgba(11,21,38,.5);backdrop-filter:blur(2px);z-index:200;display:none;align-items:center;justify-content:center;padding:20px;}
          .b-modal-overlay.open{display:flex;}
          .b-modal{background:var(--surface);border-radius:16px;width:100%;max-width:460px;max-height:90vh;overflow-y:auto;box-shadow:0 16px 40px rgba(15,30,54,.18);animation:bModalIn .18s ease;}
          @keyframes bModalIn{from{opacity:0;transform:scale(.96) translateY(8px);}to{opacity:1;transform:none;}}
          .b-modal-head{display:flex;align-items:center;justify-content:space-between;padding:18px 20px;border-bottom:1px solid var(--line);position:sticky;top:0;background:var(--surface);z-index:2;}
          .b-modal-head h3{font-family:var(--font-display);font-size:16px;font-weight:700;}
          .b-modal-close{width:30px;height:30px;border:none;background:var(--surface-2);border-radius:8px;color:var(--ink-500);display:flex;align-items:center;justify-content:center;cursor:pointer;}
          .b-modal-close:hover{background:var(--line);color:var(--ink-900);}
          .b-modal-close svg{width:14px;height:14px;}
          .b-modal-body{padding:20px;display:flex;flex-direction:column;gap:14px;}
          .b-modal-body .field{width:100%;}
          .b-modal-body .field input,.b-modal-body .field select{width:100%;border:1px solid var(--line);border-radius:9px;padding:9px 11px;font-size:13.5px;background:var(--surface);color:var(--ink-900);outline:none;font-family:var(--font-body);transition:border-color .15s;}
          .b-modal-body .field input:focus,.b-modal-body .field select:focus{border-color:var(--teal-500);}
          .b-modal-foot{display:flex;justify-content:flex-end;gap:10px;padding:16px 20px;border-top:1px solid var(--line);position:sticky;bottom:0;background:var(--surface);z-index:2;}
          .b-field-err{font-size:12px;color:var(--coral-500);margin-top:3px;display:none;}
        </style>

        <div class="toolbar">
          <div class="search-field">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
            <input placeholder="Search batches…" id="batchSearch">
          </div>
          <span class="spacer"></span>
          <button class="btn btn-accent" id="addBatchBtn">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M12 5v14M5 12h14"/></svg>
            Add Batch
          </button>
        </div>

        <div class="table-card">
          <table>
            <thead>
              <tr>
                <th>Batch</th>
                <th>Course</th>
                <th>Schedule</th>
                <th>Students</th>
                <th>Status</th>
                <th style="text-align:right">Actions</th>
              </tr>
            </thead>
            <tbody id="batchTableBody"></tbody>
          </table>
          <div class="empty-state" id="batchEmpty" style="display:none;">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M3 10h18M8 2v4M16 2v4"/></svg>
            <p>No batches yet — create a batch to get started.</p>
          </div>
        </div>
      </section>

      <!-- BATCH MODAL (Add / Edit) -->
      <div class="b-modal-overlay" id="batchModalOverlay">
        <div class="b-modal">
          <div class="b-modal-head">
            <h3 id="batchModalTitle">Add Batch</h3>
            <button class="b-modal-close" id="closeBatchModal">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg>
            </button>
          </div>
          <div class="b-modal-body">
            <input type="hidden" id="bm_id">
            <div class="field">
              <label>Batch Name</label>
              <input type="text" id="bm_name" placeholder="e.g. Batch A - Morning">
              <span class="b-field-err" id="bm_nameErr">Batch name is required.</span>
            </div>
            <div class="field">
              <label>Start Date</label>
              <input type="date" id="bm_start">
              <span class="b-field-err" id="bm_startErr">Start date is required.</span>
            </div>
            <div class="field">
              <label>Status</label>
              <select id="bm_status">
                <option value="Running">Running</option>
                <option value="Upcoming">Upcoming</option>
                <option value="Completed">Completed</option>
              </select>
            </div>
            <div class="field">
              <label>Batch Schedule</label>
              <div class="schedule-editor" id="bm_scheduleList">
                <!-- rows injected by JS -->
              </div>
              <button type="button" class="btn btn-ghost btn-sm add-schedule-btn" id="bm_addScheduleRow">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M12 5v14M5 12h14"/></svg>
                Add Schedule
              </button>
            </div>
          </div>
          <div class="b-modal-foot">
            <button class="btn btn-ghost" id="cancelBatchModal">Cancel</button>
            <button class="btn btn-primary" id="saveBatchBtn">Save Batch</button>
          </div>
        </div>
      </div>

      <!-- BATCH DELETE CONFIRM -->
      <div class="b-modal-overlay" id="delBatchOverlay">
        <div class="b-modal" style="max-width:360px;">
          <div class="b-modal-head">
            <h3>Delete Batch?</h3>
            <button class="b-modal-close" id="closeDelBatch">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg>
            </button>
          </div>
          <div class="b-modal-body">
            <p class="confirm-text" id="delBatchText">This action cannot be undone.</p>
          </div>
          <div class="b-modal-foot">
            <button class="btn btn-ghost" id="cancelDelBatch">Cancel</button>
            <button class="btn" style="background:var(--coral-500);color:#fff;" id="confirmDelBatch">Delete</button>
          </div>
        </div>
      </div>
      <!-- STUDENTS VIEW -->
      <section class="view" id="view-students">
        <style>
          /* mini-stat-grid */
          .mini-stat-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:18px;margin-bottom:20px;}
          .mini-stat-card{background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);padding:15px 16px;box-shadow:var(--shadow-sm);display:flex;align-items:center;gap:12px;position:relative;overflow:hidden;}
          .mini-stat-card::before{content:'';position:absolute;top:0;left:0;bottom:0;width:4px;}
          .mini-stat-card.m1::before{background:var(--vivid-blue);}
          .mini-stat-card.m2::before{background:var(--vivid-purple);}
          .mini-stat-card.m3::before{background:var(--vivid-amber);}
          .mini-stat-card.m4::before{background:var(--vivid-rose);}
          .msc-icon{width:38px;height:38px;border-radius:10px;flex-shrink:0;display:flex;align-items:center;justify-content:center;}
          .msc-icon svg{width:18px;height:18px;}
          .mini-stat-card.m1 .msc-icon{background:var(--vivid-blue-tint);color:var(--vivid-blue);}
          .mini-stat-card.m2 .msc-icon{background:var(--vivid-purple-tint);color:var(--vivid-purple);}
          .mini-stat-card.m3 .msc-icon{background:var(--vivid-amber-tint);color:var(--vivid-amber);}
          .mini-stat-card.m4 .msc-icon{background:var(--vivid-rose-tint);color:var(--vivid-rose);}
          .msc-value{font-family:var(--font-display);font-size:20px;font-weight:800;line-height:1.1;}
          .msc-label{font-size:11.5px;color:var(--ink-500);margin-top:2px;}
          /* student form modal */
          .st-modal-overlay{position:fixed;inset:0;background:rgba(11,21,38,.55);backdrop-filter:blur(3px);z-index:200;display:none;align-items:center;justify-content:center;padding:12px;}
          .st-modal-overlay.open{display:flex;}
          .st-modal{
            background:var(--surface);border-radius:18px;
            width:min(98vw,860px);
            max-height:96vh;
            display:flex;flex-direction:column;
            box-shadow:0 24px 64px rgba(11,21,38,.22);
            animation:stIn .18s ease;overflow:hidden;
          }
          .st-modal-sm{width:min(96vw,380px);max-height:90vh;}
          @keyframes stIn{from{opacity:0;transform:scale(.96) translateY(8px);}to{opacity:1;transform:none;}}

          .st-modal-head{
            display:flex;align-items:center;justify-content:space-between;
            padding:14px 20px;border-bottom:1px solid var(--line);flex-shrink:0;
          }
          .st-modal-head h3{font-family:var(--font-display);font-size:16px;font-weight:700;color:var(--ink-900);}
          .st-modal-close{width:30px;height:30px;border:none;background:var(--surface-2);border-radius:8px;color:var(--ink-500);display:flex;align-items:center;justify-content:center;cursor:pointer;transition:background .15s;}
          .st-modal-close:hover{background:var(--line);color:var(--ink-900);}
          .st-modal-close svg{width:13px;height:13px;}

          /* tabs */
          .form-tabs{display:flex;gap:2px;border-bottom:1px solid var(--line);flex-shrink:0;padding:0 20px;}
          .form-tab-btn{padding:9px 16px;font-size:13px;font-weight:600;color:var(--ink-500);background:none;border:none;border-bottom:2px solid transparent;cursor:pointer;margin-bottom:-1px;transition:color .15s,border-color .15s;}
          .form-tab-btn:hover{color:var(--ink-900);}
          .form-tab-btn.active{color:var(--teal-500);border-bottom-color:var(--teal-500);}
          .form-tab-panel{display:none;}
          .form-tab-panel.active{display:block;}

          /* body — scrollable on mobile */
          .st-modal-body{
            padding:16px 20px;
            display:flex;flex-direction:column;gap:12px;
            overflow-y:auto;flex:1;
          }

          /* NEW layout: photo row on top, fields below in 3 columns */
          .st-photo-row{
            display:flex;align-items:center;gap:14px;
            padding-bottom:12px;border-bottom:1px dashed var(--line);
          }
          .student-photo-lg{
            width:60px;height:60px;border-radius:12px;overflow:hidden;flex-shrink:0;
            background:linear-gradient(135deg,var(--teal-500),var(--navy-700));
            display:flex;align-items:center;justify-content:center;
            font-family:var(--font-display);font-weight:800;font-size:20px;color:var(--white);
          }
          .student-photo-lg img{width:100%;height:100%;object-fit:cover;}
          .photo-upload-label{
            display:inline-flex;align-items:center;gap:6px;
            padding:7px 12px;border-radius:8px;border:1px solid var(--line);
            background:var(--surface-2);font-size:12px;font-weight:600;
            color:var(--ink-700);cursor:pointer;transition:background .15s;
          }
          .photo-upload-label:hover{background:var(--surface);border-color:var(--ink-300);}
          .photo-upload-label svg{width:12px;height:12px;}
          .photo-upload-label input{display:none;}
          .photo-hint{font-size:11px;color:var(--ink-400,#9AA3B5);}

          /* 3-column fields grid */
          .st-fields-grid{display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px 14px;}
          .st-fields-grid .field{display:flex;flex-direction:column;gap:4px;}
          .st-fields-grid .field.span2{grid-column:span 2;}
          .st-fields-grid .field.span3{grid-column:span 3;}

          /* section separator */
          .st-section-label{
            grid-column:1/-1;
            font-family:var(--font-display);font-size:10.5px;font-weight:700;
            color:var(--ink-500);text-transform:uppercase;letter-spacing:.8px;
            padding-bottom:6px;border-bottom:1px dashed var(--line);
            margin-top:4px;
          }

          .st-fields-grid .field label{font-size:11px;font-weight:600;color:var(--ink-500);text-transform:uppercase;letter-spacing:.4px;}
          .st-fields-grid .field input,
          .st-fields-grid .field select{
            width:100%;border:1.5px solid var(--line);border-radius:9px;
            padding:8px 10px;font-size:13px;background:var(--surface);
            color:var(--ink-900);outline:none;font-family:var(--font-body);
            transition:border-color .15s,box-shadow .15s;
          }
          .st-fields-grid .field input:focus,
          .st-fields-grid .field select:focus{
            border-color:var(--teal-500);
            box-shadow:0 0 0 3px var(--teal-tint-10);
          }
          .st-field-err{font-size:11px;color:var(--coral-500);margin-top:1px;display:none;}

          /* keep old .field for delete modal */
          .st-modal-sm .st-modal-body .field{display:flex;flex-direction:column;gap:5px;}

          .st-modal-foot{
            display:flex;justify-content:flex-end;gap:10px;
            padding:12px 20px;border-top:1px solid var(--line);flex-shrink:0;
          }

          /* CSV */
          .csv-actions-row{display:flex;justify-content:flex-end;margin-bottom:10px;}
          .csv-dropzone{display:flex;align-items:center;gap:14px;border:1.5px dashed var(--line);border-radius:12px;padding:16px;background:var(--surface-2);cursor:pointer;transition:border-color .15s,background .15s;position:relative;}
          .csv-dropzone:hover{border-color:var(--teal-500);background:var(--teal-tint-10);}
          .csv-dropzone input[type="file"]{position:absolute;width:1px;height:1px;opacity:0;overflow:hidden;}
          .csv-dropzone svg{width:24px;height:24px;color:var(--teal-500);flex-shrink:0;}
          .csv-dropzone b{font-size:13px;color:var(--ink-900);}
          .csv-filename{font-size:12px;color:var(--ink-500);margin-top:2px;}
          .csv-preview{margin-top:12px;background:var(--surface-2);border:1px solid var(--line);border-radius:10px;padding:12px;}
          .csv-preview-head{font-size:12px;font-weight:700;color:var(--ink-900);margin-bottom:8px;}
          .csv-preview-table-wrap{max-height:160px;overflow-y:auto;border-radius:7px;border:1px solid var(--line);}
          .csv-preview-table{width:100%;border-collapse:collapse;background:var(--surface);}
          .csv-preview-table th{position:sticky;top:0;background:var(--surface-2);text-align:left;font-size:10.5px;text-transform:uppercase;letter-spacing:.4px;color:var(--ink-500);padding:7px 9px;border-bottom:1px solid var(--line);}
          .csv-preview-table td{padding:7px 9px;font-size:12px;color:var(--ink-700);border-bottom:1px solid var(--line);}
          .csv-preview-table tr:last-child td{border-bottom:none;}
          .csv-hint{font-size:11px;color:var(--ink-500);margin-top:10px;line-height:1.6;}
          .csv-hint b{color:var(--ink-700);}
          .row-avatar{width:32px;height:32px;border-radius:50%;flex-shrink:0;display:flex;align-items:center;justify-content:center;font-family:var(--font-display);font-weight:700;font-size:11.5px;color:var(--white);overflow:hidden;}
          .row-avatar img{width:100%;height:100%;object-fit:cover;}
          @media(max-width:680px){
            .st-fields-grid{grid-template-columns:1fr 1fr;}
            .st-fields-grid .field.span3{grid-column:span 2;}
            .st-modal{
              width:100vw;
              height:100dvh;
              max-height:100dvh;
              border-radius:0;
            }
            .st-modal-overlay{padding:0;}
            .st-modal-body{overflow-y:auto;-webkit-overflow-scrolling:touch;}
          }
          @media(max-width:820px){.mini-stat-grid{grid-template-columns:repeat(2,1fr);}}
        </style>

        <!-- Mini stats -->
        <div class="mini-stat-grid">
          <div class="mini-stat-card m1">
            <div class="msc-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75"/></svg></div>
            <div><div class="msc-value" id="mscTotal">0</div><div class="msc-label">Total students</div></div>
          </div>
          <div class="mini-stat-card m2">
            <div class="msc-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M3 10h18M8 2v4M16 2v4"/></svg></div>
            <div><div class="msc-value" id="mscBatches">0</div><div class="msc-label">Batches represented</div></div>
          </div>
          <div class="mini-stat-card m3">
            <div class="msc-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg></div>
            <div><div class="msc-value" id="mscAvg">—</div><div class="msc-label">Average attendance</div></div>
          </div>
          <div class="mini-stat-card m4">
            <div class="msc-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0Z"/><path d="M12 9v4M12 17h.01"/></svg></div>
            <div><div class="msc-value" id="mscRisk">0</div><div class="msc-label">Below 75% attendance</div></div>
          </div>
        </div>

        <!-- Toolbar -->
        <div class="toolbar toolbar-students">
          <div class="search-field">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
            <input placeholder="Search by name or roll…" id="studentSearch">
          </div>
          <div class="select-field">
            <select id="studentCourseFilter"><option value="">All courses</option></select>
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>
          </div>
          <div class="select-field">
            <select id="studentBatchFilter"><option value="">All batches</option></select>
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>
          </div>
          <span class="spacer"></span>
          <button class="btn btn-accent" id="addStudentBtn">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M12 5v14M5 12h14"/></svg>
            Add Student
          </button>
        </div>

        <!-- Table -->
        <div class="table-card">
          <table>
            <thead>
              <tr>
                <th>Student</th><th>Student ID</th><th>Father's Name</th>
                <th>Course</th><th>Batch</th><th>Contact</th>
                <th>Status</th><th>Attendance</th>
                <th style="text-align:right">Actions</th>
              </tr>
            </thead>
            <tbody id="studentTableBody"></tbody>
          </table>
          <div class="empty-state" id="studentEmpty" style="display:none;">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/></svg>
            <p>No students match — try adding one or adjusting filters.</p>
          </div>
        </div>
      </section>

      <!-- STUDENT MODAL (Add / Edit) -->
      <div class="st-modal-overlay" id="studentModalOverlay">
        <div class="st-modal" id="studentModalBox">
          <div class="st-modal-head">
            <h3 id="studentModalTitle">Add Student</h3>
            <button class="st-modal-close" id="closeStudentModal">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg>
            </button>
          </div>
          <div class="st-modal-body" id="studentModalBody"></div>
          <div class="st-modal-foot">
            <button class="btn btn-ghost" id="cancelStudentModal">Cancel</button>
            <button class="btn btn-primary" id="saveStudentBtn">Save Student</button>
          </div>
        </div>
      </div>

      <!-- STUDENT DELETE CONFIRM -->
      <div class="st-modal-overlay" id="delStudentOverlay">
        <div class="st-modal st-modal-sm">
          <div class="st-modal-head">
            <h3>Delete Student?</h3>
            <button class="st-modal-close" id="closeDelStudent">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg>
            </button>
          </div>
          <div class="st-modal-body">
            <p class="confirm-text" id="delStudentText">This action cannot be undone.</p>
          </div>
          <div class="st-modal-foot">
            <button class="btn btn-ghost" id="cancelDelStudent">Cancel</button>
            <button class="btn" style="background:var(--coral-500);color:#fff;" id="confirmDelStudent">Delete</button>
          </div>
        </div>
      </div>
      <!-- ATTENDANCE VIEW -->
      <section class="view" id="view-attendance">
        <style>
          /* Setup bar */
          .att-setup{display:flex;gap:12px;align-items:flex-end;flex-wrap:nowrap;background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);padding:18px;margin-bottom:16px;box-shadow:var(--shadow-sm);}
          .att-setup .field{display:flex;flex-direction:column;gap:6px;}
          .att-setup .field label{font-size:11.5px;font-weight:600;color:var(--ink-500);text-transform:uppercase;letter-spacing:.4px;}
          .att-setup .field select,.att-setup .field input{border:1.5px solid var(--line);border-radius:10px;padding:10px 12px;font-size:13.5px;min-width:170px;background:var(--surface);color:var(--ink-900);outline:none;font-family:var(--font-body);transition:border-color .15s,box-shadow .15s;}
          .att-setup .field select:focus,.att-setup .field input:focus{border-color:var(--teal-500);box-shadow:0 0 0 3px var(--teal-tint-10);}
          /* Desktop: all rows inline */
          .att-setup-row1{display:contents;}
          .att-setup-row2{display:contents;}
          .att-setup-row3{display:contents;}
          @media(max-width:640px){
            .att-setup{flex-direction:column;gap:14px;padding:16px;flex-wrap:wrap;}
            .att-setup-row1{display:grid;grid-template-columns:1fr 1fr;gap:10px;width:100%;}
            .att-setup-row1 .field{width:100%;}
            .att-setup-row1 .field select,.att-setup-row1 .field input{min-width:0;width:100%;font-size:13px;}
            .att-setup-row2{display:grid;grid-template-columns:1fr 1fr;gap:10px;width:100%;}
            .att-setup-row2 .btn{width:100%;justify-content:center;padding:10px;}
            .att-setup-row3{width:100%;display:block;}
            .att-setup-row3 .btn{width:100%;justify-content:center;padding:13px;font-size:14px;}
            .att-setup .spacer{display:none;}
          }
          /* Summary bar */
          .att-summary-bar{display:flex;gap:14px;margin-bottom:14px;flex-wrap:wrap;}
          .att-mini{flex:1;min-width:110px;background:var(--surface);border:1px solid var(--line);border-radius:12px;padding:12px 14px;box-shadow:var(--shadow-sm);}
          .att-mini .n{font-family:var(--font-display);font-weight:800;font-size:22px;}
          .att-mini .l{font-size:11.5px;color:var(--ink-500);margin-top:2px;}
          /* Student rows */
          .att-list{display:flex;flex-direction:column;gap:8px;}
          .att-row{display:flex;align-items:center;gap:12px;background:var(--surface);border:1px solid var(--line);border-radius:12px;padding:12px 16px;box-shadow:var(--shadow-sm);transition:border-color .15s;}
          .att-row:hover{border-color:var(--ink-300);}
          .att-info{flex:1;display:flex;align-items:center;gap:12px;}
          .att-name{font-weight:600;font-size:14px;color:var(--ink-900);}
          .att-id{font-size:12px;color:var(--ink-500);margin-top:1px;}
          /* Toggle buttons */
          .status-toggle{display:flex;gap:6px;}
          .status-btn{
            border:1.5px solid var(--line);background:var(--surface);
            padding:7px 15px;border-radius:9px;font-size:12.5px;font-weight:600;
            color:var(--ink-500);cursor:pointer;font-family:var(--font-body);
            transition:all .15s;
          }
          .status-btn:hover{border-color:var(--ink-300);color:var(--ink-900);}
          .status-btn[data-s="present"].active{background:var(--teal-tint-14);border-color:var(--teal-500);color:var(--badge-green-text);}
          .status-btn[data-s="late"].active{background:var(--amber-tint-16);border-color:var(--amber-500);color:var(--badge-amber-text);}
          .status-btn[data-s="absent"].active{background:var(--badge-red-bg);border-color:var(--coral-500);color:var(--badge-red-text);}
          /* empty */
          .att-empty{padding:50px 20px;text-align:center;color:var(--ink-500);background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);}
          .att-empty svg{width:40px;height:40px;color:var(--ink-300);margin-bottom:10px;}
          .att-empty p{font-size:13.5px;}
          /* Marked section rows — slightly muted to separate from pending */
          #attMarkedList .att-row{opacity:.82;}
          #attMarkedList .att-row:hover{opacity:1;}
        </style>

        <!-- Setup bar -->
        <div class="att-setup">
          <div class="att-setup-row1">
            <div class="field">
              <label>Batch</label>
              <select id="attBatchSelect">
                <option value="">Select a batch…</option>
              </select>
            </div>
            <div class="field">
              <label>Date</label>
              <input type="date" id="attDate">
            </div>
          </div>
          <div class="att-setup-row2">
            <button class="btn btn-ghost" id="attMarkAllPresent" style="display:none;">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M9 11l3 3L22 4"/></svg>
              Mark all present
            </button>
            <button class="btn btn-ghost" id="attClearAll" style="display:none;color:var(--coral-500);border-color:var(--danger-border);">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18M6 6l12 12"/></svg>
              Clear All
            </button>
          </div>
          <div class="att-setup-row3">
            <button class="btn btn-primary" id="saveAttendanceBtn" style="display:none;">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><path d="M17 21v-8H7v8M7 3v5h8"/></svg>
              Save Attendance
            </button>
          </div>
        </div>

        <!-- Summary -->
        <div class="att-summary-bar" id="attSummaryBar" style="display:none;">
          <div class="att-mini"><div class="n" id="attPresentN">0</div><div class="l">Present</div></div>
          <div class="att-mini"><div class="n" id="attLateN">0</div><div class="l">Late</div></div>
          <div class="att-mini"><div class="n" id="attAbsentN">0</div><div class="l">Absent</div></div>
          <div class="att-mini"><div class="n" id="attTotalN">0</div><div class="l">Total students</div></div>
        </div>

        <!-- Pending (unmarked) students -->
        <div class="att-list" id="attList"></div>

        <!-- Marked students container -->
        <div id="attMarkedSection" style="display:none;margin-top:18px;">
          <div style="display:flex;align-items:center;gap:10px;margin-bottom:10px;">
            <div style="flex:1;height:1px;background:var(--line);"></div>
            <span style="font-size:11px;font-weight:700;letter-spacing:.8px;text-transform:uppercase;color:var(--ink-400,#9AA3B5);white-space:nowrap;display:flex;align-items:center;gap:6px;">
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M9 11l3 3L22 4"/></svg>
              Marked — <span id="attMarkedCount">0</span>
            </span>
            <div style="flex:1;height:1px;background:var(--line);"></div>
          </div>
          <div class="att-list" id="attMarkedList"></div>
        </div>

        <!-- Empty state -->
        <div class="att-empty" id="attEmpty">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg>
          <p>Select a batch and date to start marking attendance.</p>
        </div>

      </section>

      <!-- TRANSFERS VIEW -->
      <section class="view" id="view-transfers">
        <style>
          /* ── Transfer Students ── */
          .tr-search-bar{display:flex;align-items:center;gap:12px;background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);padding:14px 16px;margin-bottom:18px;box-shadow:var(--shadow-sm);}
          .tr-search-bar input{flex:1;border:1px solid var(--line);background:var(--surface-2);border-radius:9px;padding:9px 12px 9px 36px;font-size:13.5px;color:var(--ink-900);outline:none;font-family:var(--font-body);transition:border-color .15s;}
          .tr-search-bar input:focus{border-color:var(--teal-500);box-shadow:0 0 0 3px var(--teal-tint-10);}
          .tr-search-wrap{position:relative;flex:1;}
          .tr-search-wrap svg{position:absolute;left:11px;top:50%;transform:translateY(-50%);width:15px;height:15px;color:var(--ink-500);pointer-events:none;}
          /* Student card */
          .tr-card{background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);box-shadow:var(--shadow-sm);margin-bottom:16px;overflow:hidden;}
          /* Card header */
          .tr-card-head{display:flex;align-items:center;gap:14px;padding:16px 20px;border-bottom:1px solid var(--line);}
          .tr-avatar{width:42px;height:42px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-family:var(--font-display);font-weight:700;font-size:13px;color:#fff;flex-shrink:0;}
          .tr-student-name{font-family:var(--font-display);font-size:15px;font-weight:700;color:var(--ink-900);}
          .tr-student-code{font-size:12px;color:var(--ink-500);margin-top:2px;}
          .tr-current-badge{margin-left:auto;background:var(--teal-tint-12);color:var(--badge-green-text);border-radius:100px;padding:4px 12px;font-size:11.5px;font-weight:600;white-space:nowrap;flex-shrink:0;}
          /* Batch section */
          .tr-batch-block{padding:14px 20px;border-bottom:1px solid var(--line);}
          .tr-batch-block:last-child{border-bottom:none;}
          .tr-batch-header{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px;margin-bottom:10px;}
          .tr-batch-name{font-family:var(--font-display);font-size:13.5px;font-weight:700;color:var(--ink-900);display:flex;align-items:center;gap:8px;}
          .tr-batch-stats{display:flex;gap:6px;align-items:center;flex-wrap:wrap;}
          /* Progress bar */
          .tr-progress{height:5px;border-radius:3px;background:var(--line);overflow:hidden;margin-bottom:10px;}
          .tr-progress-fill{height:100%;border-radius:3px;transition:width .3s;}
          /* Date chips grid */
          .tr-chips{display:grid;grid-template-columns:repeat(auto-fill,minmax(50px,1fr));gap:8px 6px;}
          .tr-chip{display:flex;flex-direction:column;align-items:center;gap:3px;}
          .tr-att-cell{display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px;border-radius:7px;font-size:11px;font-weight:700;}
          .tr-att-cell.present{background:var(--teal-tint-14);color:var(--badge-green-text);}
          .tr-att-cell.late{background:var(--amber-tint-16);color:var(--badge-amber-text);}
          .tr-att-cell.absent{background:var(--badge-red-bg);color:var(--badge-red-text);}
          .tr-att-cell.none{background:var(--surface-2);color:var(--ink-300);font-size:10px;}
          .tr-chip-date{font-size:9.5px;font-weight:600;color:var(--ink-500);white-space:nowrap;text-align:center;}
          .tr-chip-day{font-size:9px;color:var(--ink-300);text-align:center;}
          /* Empty */
          .tr-empty{padding:50px 20px;text-align:center;font-size:13px;color:var(--ink-400,#9AA3B5);background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);}
          .tr-empty svg{width:40px;height:40px;color:var(--ink-300);margin-bottom:10px;}
        </style>

        <div class="tr-search-bar">
          <div class="tr-search-wrap">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
            <input type="text" id="trSearch" placeholder="Search by name or student ID…">
          </div>
        </div>

        <div id="transfersPageBody">
          <div class="tr-empty">Loading…</div>
        </div>
      </section>

      <!-- REPORTS VIEW -->
      <section class="view" id="view-reports">
        <style>
          /* Transfer panel */
          .transfer-panel{background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);box-shadow:var(--shadow-sm);overflow:hidden;margin-bottom:20px;}
          .transfer-head{display:flex;align-items:center;justify-content:space-between;padding:16px 20px;border-bottom:1px solid var(--line);}
          .transfer-head h3{font-family:var(--font-display);font-size:15px;font-weight:700;}
          .transfer-empty{padding:30px 20px;text-align:center;font-size:13px;color:var(--ink-400,#9AA3B5);}
          .transfer-row{display:flex;align-items:center;gap:14px;padding:13px 20px;border-bottom:1px solid var(--line);flex-wrap:wrap;}
          .transfer-row:last-child{border-bottom:none;}
          .transfer-info{flex:1;min-width:140px;}
          .transfer-name{font-weight:700;font-size:13.5px;color:var(--ink-900);}
          .transfer-code{font-size:11.5px;color:var(--ink-500);}
          .transfer-batches{display:flex;gap:8px;flex-wrap:wrap;align-items:center;}
          .transfer-batch{
            display:inline-flex;align-items:center;gap:6px;
            padding:5px 12px;border-radius:9px;border:1px solid var(--line);
            background:var(--surface-2);font-size:12px;
          }
          .transfer-batch.current{border-color:var(--teal-500);background:var(--teal-tint-10);}
          .transfer-batch .tb-name{font-weight:600;color:var(--ink-900);}
          .transfer-batch .tb-days{color:var(--ink-500);font-size:11px;}
          .transfer-batch .tb-pct{font-weight:700;}
          .transfer-batch.current .tb-name{color:var(--badge-green-text);}
          .tb-arrow{color:var(--ink-300);font-size:13px;}
          /* History cross-table */
          .hist-panel{background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);box-shadow:var(--shadow-sm);}
          .hist-head{display:flex;align-items:center;justify-content:space-between;padding:16px 20px;border-bottom:1px solid var(--line);flex-wrap:wrap;gap:10px;}
          .hist-head h3{font-family:var(--font-display);font-size:15px;font-weight:700;}
          .hist-filter-wrap{position:relative;}
          .hist-filter-wrap select{border:1px solid var(--line);background:var(--surface-2);border-radius:9px;padding:8px 30px 8px 11px;font-size:13px;color:var(--ink-900);outline:none;font-family:var(--font-body);appearance:none;-webkit-appearance:none;min-width:200px;}
          .hist-filter-wrap select:focus{border-color:var(--teal-500);}
          .hist-filter-wrap svg{position:absolute;right:9px;top:50%;transform:translateY(-50%);width:12px;height:12px;color:var(--ink-500);pointer-events:none;}
          .hist-empty{padding:40px 20px;text-align:center;font-size:13px;color:var(--ink-400,#9AA3B5);}
          .hist-empty svg{width:38px;height:38px;color:var(--ink-300);margin-bottom:10px;}
          /* editable cell */
          .att-cell.editable{cursor:pointer;transition:transform .1s,box-shadow .1s;}
          .att-cell.editable:hover{transform:scale(1.15);box-shadow:0 2px 8px rgba(15,30,54,.12);}
          /* date header with delete btn */
          .date-th-wrap{display:flex;flex-direction:column;align-items:center;gap:3px;}
          .date-del-btn{
            width:18px;height:18px;border-radius:4px;border:none;
            background:var(--badge-red-bg);color:var(--badge-red-text);
            display:flex;align-items:center;justify-content:center;
            cursor:pointer;font-size:10px;opacity:0;
            transition:opacity .15s;
          }
          .date-th:hover .date-del-btn{opacity:1;}
          .date-del-btn svg{width:10px;height:10px;}
          /* inline status dropdown */
          .att-edit-select{
            border:1.5px solid var(--teal-500);border-radius:7px;
            padding:3px 6px;font-size:11px;font-weight:700;
            outline:none;cursor:pointer;font-family:var(--font-body);
            background:var(--surface);color:var(--ink-900);
          }

          /* cross-table wrapper — scrollbar hidden, fake scrollbar sticky at bottom */
          .hist-table-outer{position:relative;}
          .hist-table-wrap{
            overflow-x:auto;
            -webkit-overflow-scrolling:touch;
            scrollbar-width:none;
            -ms-overflow-style:none;
          }
          .hist-table-wrap::-webkit-scrollbar{display:none;}
          /* Fake scrollbar — sticky at bottom of viewport while table is in view */
          .hist-fake-scroll{
            overflow-x:auto;
            overflow-y:hidden;
            position:sticky;
            bottom:0;
            z-index:10;
            background:var(--surface);
            border-top:2px solid var(--teal-400);
            scrollbar-width:thin;
            scrollbar-color:var(--teal-400) var(--line);
          }
          .hist-fake-scroll::-webkit-scrollbar{display:block;height:10px;}
          .hist-fake-scroll::-webkit-scrollbar-track{background:var(--surface-2);}
          .hist-fake-scroll::-webkit-scrollbar-thumb{background:var(--teal-400);border-radius:5px;border:2px solid var(--surface-2);}
          .hist-fake-scroll::-webkit-scrollbar-thumb:hover{background:var(--teal-500);}
          .hist-fake-inner{height:1px;}

          .hist-cross{border-collapse:collapse;width:max-content;min-width:100%;font-size:12.5px;}
          .hist-cross th{
            background:var(--surface-2);
            font-size:10.5px;letter-spacing:.5px;text-transform:uppercase;
            color:var(--ink-500);font-weight:700;
            padding:10px 12px;border-bottom:1px solid var(--line);
            white-space:nowrap;
            position:sticky;top:0;z-index:3;
          }
          /* sticky first column — Student */
          .hist-cross th:first-child,
          .hist-cross td:first-child{
            position:sticky;left:0;
            background:var(--surface-2);
            z-index:4;border-right:1px solid var(--line);
            min-width:180px;
          }
          .hist-cross td:first-child{background:var(--surface);z-index:2;}
          /* sticky last column — Total */
          .hist-cross th:last-child,
          .hist-cross td:last-child{
            position:sticky;right:0;
            background:var(--surface-2);
            z-index:4;border-left:1px solid var(--line);
            min-width:110px;
          }
          .hist-cross td:last-child{background:var(--surface);z-index:2;}
          .hist-cross tr:hover td{background:var(--surface-2);}
          .hist-cross tr:hover td:first-child,
          .hist-cross tr:hover td:last-child{background:var(--surface-2);}

          .hist-cross td{
            padding:10px 12px;border-bottom:1px solid var(--line);
            vertical-align:middle;white-space:nowrap;
          }
          .hist-cross tr:last-child td{border-bottom:none;}

          /* date column header */
          .hist-cross .date-th{
            writing-mode:horizontal-tb;
            text-align:center;
            min-width:60px;max-width:80px;
            font-size:10.5px;
          }

          /* desktop = table, mobile = cards — controlled by global CSS */
          /* Student full-history modal */
          .sh-modal-overlay{position:fixed;inset:0;z-index:600;background:rgba(11,21,38,.55);backdrop-filter:blur(3px);display:none;align-items:flex-start;justify-content:center;padding:20px;overflow-y:auto;}
          .sh-modal-overlay.open{display:flex;}
          .sh-modal{background:var(--surface);border-radius:16px;width:100%;max-width:680px;box-shadow:var(--shadow-lg);overflow:hidden;margin:auto;}
          .sh-modal-head{display:flex;align-items:center;justify-content:space-between;padding:18px 20px;border-bottom:1px solid var(--line);}
          .sh-modal-head h3{font-family:var(--font-display);font-size:15px;font-weight:700;}
          .sh-modal-close{background:var(--surface-2);border:1px solid var(--line);border-radius:8px;width:30px;height:30px;display:flex;align-items:center;justify-content:center;cursor:pointer;color:var(--ink-700);}
          .sh-modal-body{padding:20px;display:flex;flex-direction:column;gap:16px;max-height:70vh;overflow-y:auto;}
          .att-cell{
            display:inline-flex;align-items:center;justify-content:center;
            width:28px;height:28px;border-radius:7px;
            font-size:11px;font-weight:700;margin:auto;
          }
          .att-cell.present{background:var(--teal-tint-14);color:var(--badge-green-text);}
          .att-cell.late{background:var(--amber-tint-16);color:var(--badge-amber-text);}
          .att-cell.absent{background:var(--badge-red-bg);color:var(--badge-red-text);}
          .att-cell.none{background:var(--surface-2);color:var(--ink-300);font-size:10px;}

          /* total column */
          .total-cell{text-align:center;}
          .total-cell .t-p{color:var(--badge-green-text);font-weight:700;}
          .total-cell .t-l{color:var(--badge-amber-text);font-weight:700;}
          .total-cell .t-a{color:var(--badge-red-text);font-weight:700;}
          .total-cell .t-sep{color:var(--ink-300);margin:0 1px;}
        </style>

        <div class="hist-panel">
          <div class="hist-head">
            <h3>Attendance History</h3>
            <div class="hist-filter-wrap">
              <select id="histBatchSelect">
                <option value="">Select batch…</option>
              </select>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>
            </div>
          </div>
          <div id="histBody">
            <div class="hist-empty">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3v18h18"/><path d="M18 17V9M13 17V5M8 17v-4"/></svg>
              <p>Select a batch to view attendance history.</p>
            </div>
          </div>
        </div>
      </section>

      <!-- PROFILE VIEW -->
      <section class="view" id="view-profile">
        <style>
          #view-profile{background:var(--surface);min-height:100%;}
          /* Make content area white when profile is active */
          .content:has(#view-profile.active){background:var(--surface);}
          .profile-layout{display:grid;grid-template-columns:1.7fr 1fr;gap:20px;align-items:start;}
          .profile-card,.security-card{background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);padding:24px;box-shadow:var(--shadow-sm);}
          .profile-top{display:flex;align-items:center;gap:16px;margin-bottom:22px;padding-bottom:22px;border-bottom:1px solid var(--line);}
          .avatar-upload-wrap{position:relative;flex-shrink:0;}
          .avatar-lg{width:68px;height:68px;border-radius:50%;background:linear-gradient(135deg,var(--teal-500),var(--navy-700));display:flex;align-items:center;justify-content:center;font-family:var(--font-display);font-weight:800;font-size:24px;color:var(--white);overflow:hidden;}
          .avatar-lg img{width:100%;height:100%;object-fit:contain;border-radius:50%;background:#fff;}
          .avatar-upload-btn{position:absolute;bottom:-2px;right:-2px;width:25px;height:25px;border-radius:50%;background:var(--teal-500);color:var(--white);display:flex;align-items:center;justify-content:center;border:2px solid var(--surface);cursor:pointer;box-shadow:var(--shadow-sm);}
          .avatar-upload-btn svg{width:12px;height:12px;}
          .avatar-upload-btn input{display:none;}
          .profile-top h2{font-family:var(--font-display);font-size:19px;font-weight:700;}
          .profile-top p{font-size:13px;color:var(--ink-500);margin-top:2px;}
          .profile-grid{display:grid;grid-template-columns:1fr 1fr;gap:16px;}
          .field{display:flex;flex-direction:column;gap:6px;}
          .field label{font-size:11.5px;font-weight:600;color:var(--ink-500);text-transform:uppercase;letter-spacing:.4px;}
          .field input{border:1px solid var(--line);border-radius:9px;padding:9px 11px;font-size:13.5px;background:var(--surface);color:var(--ink-900);outline:none;transition:border-color .15s;}
          .field input:focus{border-color:var(--teal-500);}
          .field input:disabled{background:var(--surface-2);color:var(--ink-500);}
          .profile-side{display:flex;flex-direction:column;gap:10px;}
          .security-card h3{font-family:var(--font-display);font-size:14.5px;font-weight:700;margin-bottom:4px;}
          .security-sub{font-size:12px;color:var(--ink-500);margin-bottom:16px;}
          .btn{display:inline-flex;align-items:center;gap:7px;border:none;border-radius:9px;padding:9.5px 16px;font-size:13.5px;font-weight:600;transition:transform .1s,box-shadow .15s;cursor:pointer;}
          .btn svg{width:15px;height:15px;}
          .btn-primary{background:var(--navy-950);color:var(--white);}
          .btn-primary:hover{box-shadow:var(--shadow-md);}
          .btn-ghost{background:var(--surface);border:1px solid var(--line);color:var(--ink-700);}
          .btn-ghost:hover{background:var(--surface-2);}
          .alert-success{background:rgba(31,157,108,.08);border:1px solid rgba(31,157,108,.25);border-radius:10px;padding:10px 14px;font-size:13px;color:#1F9D6C;margin-bottom:14px;display:none;}
          @media(max-width:1100px){.profile-layout{grid-template-columns:1fr;}.profile-grid{grid-template-columns:1fr;}}
          /* Security card */
          .sec-display-wrap{
            position:relative;display:flex;align-items:center;margin-bottom:14px;
          }
          .sec-display-field{
            border:1px solid var(--line);border-radius:11px;padding:11px 42px 11px 14px;
            font-size:15px;letter-spacing:3px;color:var(--ink-500);
            background:var(--surface);width:100%;
            user-select:none;pointer-events:none;
          }
          .sec-display-eye{
            position:absolute;right:11px;
            background:none;border:none;color:var(--ink-300);cursor:pointer;
            display:flex;align-items:center;padding:4px;border-radius:6px;
            transition:color .15s;
          }
          .sec-display-eye:hover{color:var(--ink-700);}
          .sec-display-eye svg{width:17px;height:17px;}
          .btn-change{
            width:100%;justify-content:center;padding:11px 16px;
            background:var(--surface);border:1px solid var(--line);
            border-radius:11px;font-size:14px;font-weight:700;
            color:var(--ink-900);cursor:pointer;font-family:var(--font-display);
            transition:background .15s,border-color .15s,box-shadow .15s;
            display:flex;align-items:center;gap:8px;
          }
          .btn-change:hover{background:var(--surface-2);border-color:var(--ink-300);box-shadow:var(--shadow-sm);}
          /* Modal */
          .sec-modal-overlay{
            position:fixed;inset:0;background:rgba(11,21,38,.5);
            backdrop-filter:blur(2px);z-index:200;
            display:none;align-items:center;justify-content:center;padding:20px;
          }
          .sec-modal-overlay.open{display:flex;}
          .sec-modal{
            background:var(--surface);border-radius:16px;
            width:100%;max-width:420px;
            box-shadow:0 16px 40px rgba(15,30,54,.18);
            animation:secModalIn .18s ease;
          }
          @keyframes secModalIn{from{opacity:0;transform:scale(.96) translateY(8px);}to{opacity:1;transform:none;}}
          .sec-modal-head{
            display:flex;align-items:center;justify-content:space-between;
            padding:18px 20px;border-bottom:1px solid var(--line);
          }
          .sec-modal-head h3{font-family:var(--font-display);font-size:16px;font-weight:700;color:var(--ink-900);}
          .sec-modal-close{
            width:30px;height:30px;border:none;background:var(--surface-2);
            border-radius:8px;color:var(--ink-500);display:flex;
            align-items:center;justify-content:center;cursor:pointer;
          }
          .sec-modal-close:hover{background:var(--line);color:var(--ink-900);}
          .sec-modal-close svg{width:14px;height:14px;}
          .sec-modal-body{padding:20px;display:flex;flex-direction:column;gap:14px;}
          .sec-modal-body .field input{width:100%;min-width:0;}
          .sec-modal-foot{
            display:flex;justify-content:flex-end;gap:10px;
            padding:16px 20px;border-top:1px solid var(--line);
          }
          .input-pass-wrap{position:relative;}
          .input-pass-wrap input{width:100%;padding-right:40px;}
          .pass-eye{
            position:absolute;right:11px;top:50%;transform:translateY(-50%);
            background:none;border:none;color:var(--ink-300);cursor:pointer;
            display:flex;align-items:center;padding:2px;border-radius:5px;
            transition:color .15s;
          }
          .pass-eye:hover{color:var(--ink-700);}
          .pass-eye svg{width:16px;height:16px;}
          .sec-field-err{font-size:12px;color:var(--coral-500);margin-top:3px;}
          .sec-alert{
            border-radius:9px;padding:10px 13px;font-size:13px;font-weight:500;
            display:flex;align-items:center;gap:8px;
          }
          .sec-alert svg{width:15px;height:15px;flex-shrink:0;}
          .sec-alert.error{background:rgba(178,58,58,.08);border:1px solid rgba(178,58,58,.22);color:var(--coral-500);}
          .sec-alert.success{background:rgba(31,157,108,.08);border:1px solid rgba(31,157,108,.22);color:#1F9D6C;}
        </style>

        <div class="profile-layout">
          <div class="profile-card">
            <div class="profile-top">
              <div class="avatar-upload-wrap">
                <div class="avatar-lg" id="profAvatar"><?php echo e(auth()->user()->initials); ?></div>
                <label class="avatar-upload-btn" title="Upload photo" for="profPhotoInput">
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>
                </label>
              </div>
              <div>
                <h2><?php echo e(auth()->user()->name); ?></h2>
                <p><?php echo e(auth()->user()->designation); ?></p>
              </div>
            </div>

            <div id="profileSuccess" class="alert-success">✓ Profile updated successfully.</div>

            <form method="POST" action="<?php echo e(route('profile.update')); ?>" id="profileForm" enctype="multipart/form-data">
              <?php echo csrf_field(); ?> <?php echo method_field('PATCH'); ?>
              
              <input type="file" name="photo" accept="image/*" id="profPhotoInput" style="display:none;">
              <div class="profile-grid">
                <div class="field">
                  <label>Full Name</label>
                  <input type="text" name="name" value="<?php echo e(auth()->user()->name); ?>" required>
                </div>
                <div class="field">
                  <label>Username</label>
                  <input type="text" name="username" value="<?php echo e(auth()->user()->username); ?>">
                </div>
                <div class="field">
                  <label>Email</label>
                  <input type="email" name="email" value="<?php echo e(auth()->user()->email); ?>" required>
                </div>
                <div class="field">
                  <label>Phone</label>
                  <input type="text" name="phone" value="<?php echo e(auth()->user()->phone); ?>">
                </div>
                <div class="field" style="grid-column:1/-1;">
                  <label>Designation</label>
                  <input type="text" name="designation" value="<?php echo e(auth()->user()->designation); ?>">
                </div>
              </div>
              <div style="display:flex;gap:10px;margin-top:20px;">
                <button type="submit" class="btn btn-primary">
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><path d="M17 21v-8H7v8M7 3v5h8"/></svg>
                  Save Changes
                </button>
                <button type="reset" class="btn btn-ghost">Cancel</button>
              </div>
            </form>
          </div>

          <div class="profile-side">
            <!-- PASSWORD CARD -->
            <div class="security-card">
              <h3>Password</h3>
              <p class="security-sub">Your current password is hidden for security.</p>
              <div class="field" style="margin-bottom:14px;">
                <label>Current Password</label>
                <div class="sec-display-wrap">
                  <div class="sec-display-field" id="passDisplayField">••••••••••</div>
                  <button type="button" class="sec-display-eye" id="passDisplayEye" title="Show password" data-shown="0">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                  </button>
                </div>
              </div>
              
              <span id="passValue" data-val="<?php echo e(auth()->user()->password_plain); ?>" style="display:none;"></span>
              <button type="button" class="btn-change" id="openPassModal">
                Change Password
              </button>
            </div>

            <!-- ACCESS CODE CARD -->
            <div class="security-card">
              <h3>Access Code</h3>
              <p class="security-sub">Used for restricted admin actions.</p>
              <div class="field" style="margin-bottom:14px;">
                <label>Current Access Code</label>
                <div class="sec-display-wrap">
                  <div class="sec-display-field" id="codeDisplayField">••••••••••••</div>
                  <button type="button" class="sec-display-eye" id="codeDisplayEye" title="Show access code" data-shown="0">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                  </button>
                </div>
              </div>
              
              <span id="codeValue" data-val="<?php echo e(auth()->user()->access_code_plain); ?>" style="display:none;"></span>
              <button type="button" class="btn-change" id="openCodeModal">
                Change Access Code
              </button>
            </div>
          </div>
        </div>
      </section>

      
      <div class="sec-modal-overlay" id="passModalOverlay">
        <div class="sec-modal">
          <div class="sec-modal-head">
            <h3>Change Password</h3>
            <button type="button" class="sec-modal-close" id="closePassModal">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg>
            </button>
          </div>

          <form method="POST" action="<?php echo e(route('profile.password')); ?>" id="passModalForm">
            <?php echo csrf_field(); ?> <?php echo method_field('PATCH'); ?>
            <div class="sec-modal-body">

              <?php if($errors->has('current_password')): ?>
                <div class="sec-alert error">
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
                  <?php echo e($errors->first('current_password')); ?>

                </div>
              <?php endif; ?>
              <?php if(session('password_updated')): ?>
                <div class="sec-alert success">
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
                  Password updated successfully.
                </div>
              <?php endif; ?>

              <div class="field">
                <label>Current Password</label>
                <div class="input-pass-wrap">
                  <input type="password" name="current_password" id="pm_cur" placeholder="Enter current password" required autocomplete="current-password">
                  <button type="button" class="pass-eye" data-target="pm_cur">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                  </button>
                </div>
              </div>

              <div class="field">
                <label>New Password</label>
                <div class="input-pass-wrap">
                  <input type="password" name="password" id="pm_new" placeholder="Minimum 8 characters" required autocomplete="new-password">
                  <button type="button" class="pass-eye" data-target="pm_new">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                  </button>
                </div>
              </div>

              <div class="field">
                <label>Confirm New Password</label>
                <div class="input-pass-wrap">
                  <input type="password" name="password_confirmation" id="pm_conf" placeholder="Repeat new password" required autocomplete="new-password">
                  <button type="button" class="pass-eye" data-target="pm_conf">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                  </button>
                </div>
                <span class="sec-field-err" id="pm_matchErr" style="display:none;">Passwords do not match.</span>
              </div>

            </div>
            <div class="sec-modal-foot">
              <button type="button" class="btn btn-ghost" id="cancelPassModal">Cancel</button>
              <button type="submit" class="btn btn-primary">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><path d="M17 21v-8H7v8M7 3v5h8"/></svg>
                Update Password
              </button>
            </div>
          </form>
        </div>
      </div>

      
      <div class="sec-modal-overlay" id="codeModalOverlay">
        <div class="sec-modal">
          <div class="sec-modal-head">
            <h3>Change Access Code</h3>
            <button type="button" class="sec-modal-close" id="closeCodeModal">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg>
            </button>
          </div>

          <form method="POST" action="<?php echo e(route('profile.access-code')); ?>" id="codeModalForm">
            <?php echo csrf_field(); ?> <?php echo method_field('PATCH'); ?>
            <div class="sec-modal-body">

              <?php if($errors->has('current_access_code')): ?>
                <div class="sec-alert error">
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
                  <?php echo e($errors->first('current_access_code')); ?>

                </div>
              <?php endif; ?>
              <?php if(session('code_updated')): ?>
                <div class="sec-alert success">
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
                  Access code updated successfully.
                </div>
              <?php endif; ?>

              <div class="field">
                <label>Current Access Code</label>
                <div class="input-pass-wrap">
                  <input type="password" name="current_access_code" id="cm_cur" placeholder="Enter current access code" required>
                  <button type="button" class="pass-eye" data-target="cm_cur">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                  </button>
                </div>
              </div>

              <div class="field">
                <label>New Access Code</label>
                <div class="input-pass-wrap">
                  <input type="text" name="access_code" id="cm_new" placeholder="e.g. AC-2024-XXXX" required autocomplete="off">
                </div>
              </div>

            </div>
            <div class="sec-modal-foot">
              <button type="button" class="btn btn-ghost" id="cancelCodeModal">Cancel</button>
              <button type="submit" class="btn btn-primary">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><path d="M17 21v-8H7v8M7 3v5h8"/></svg>
                Update Access Code
              </button>
            </div>
          </form>
        </div>
      </div>

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

<script>
/* =============================================
   COURSES — full CRUD with API + HTML design
   ============================================= */
const COURSES_URL  = '<?php echo e(url("/api/courses")); ?>';
const csrfToken    = document.querySelector('meta[name="csrf-token"]')?.content || '<?php echo e(csrf_token()); ?>';

// avatar colour palette (matches HTML design)
const palette = ['#2E5AA8','#0F1E36','#4C7BC9','#16294A','#1B3A66','#7C4DE0','#E29A2E','#E1477E'];
function colorFor(str) {
  let h = 0;
  for (const c of String(str)) h = c.charCodeAt(0) + ((h << 5) - h);
  return palette[Math.abs(h) % palette.length];
}
function initials(name) {
  return name.split(' ').map(w => w[0]).slice(0, 2).join('').toUpperCase();
}

// ── Toast ──
let _toastTimer;
function ctToast(msg) {
  const t = document.getElementById('ctToast');
  document.getElementById('ctToastMsg').textContent = msg;
  t.classList.add('show');
  clearTimeout(_toastTimer);
  _toastTimer = setTimeout(() => t.classList.remove('show'), 2200);
}

// ── Modal helpers ──
function openCourseModal(overlay) { document.getElementById(overlay).classList.add('open'); document.body.style.overflow = 'hidden'; }
function closeCourseModal(overlay) { document.getElementById(overlay).classList.remove('open'); document.body.style.overflow = ''; }

['courseModalOverlay','delCourseOverlay'].forEach(id => {
  document.getElementById(id)?.addEventListener('click', e => { if (e.target.id === id) closeCourseModal(id); });
});
document.getElementById('closeCourseModal').addEventListener('click', () => closeCourseModal('courseModalOverlay'));
document.getElementById('cancelCourseModal').addEventListener('click', () => closeCourseModal('courseModalOverlay'));
document.getElementById('closeDelCourse').addEventListener('click', () => closeCourseModal('delCourseOverlay'));
document.getElementById('cancelDelCourse').addEventListener('click', () => closeCourseModal('delCourseOverlay'));
document.addEventListener('keydown', e => { if (e.key === 'Escape') { closeCourseModal('courseModalOverlay'); closeCourseModal('delCourseOverlay'); } });

// ── Render table ──
let _allCourses = [];

function renderCourseTable(courses) {
  const tbody = document.getElementById('courseTableBody');
  const empty = document.getElementById('courseEmpty');
  if (!courses.length) {
    tbody.innerHTML = '';
    empty.style.display = '';
    return;
  }
  empty.style.display = 'none';
  tbody.innerHTML = courses.map(c => {
    const badgeClass = c.status === 'Active' ? 'badge-green' : c.status === 'Upcoming' ? 'badge-amber' : 'badge-slate';
    return `<tr>
      <td data-label="Course">
        <div class="row-flex">
          <div class="course-icon" style="background:${colorFor(c.id)}">${initials(c.name)}</div>
          <div>
            <div class="cell-main">${c.name}</div>
            <div class="cell-sub">${c.code}</div>
          </div>
        </div>
      </td>
      <td data-label="Duration">
        <span class="duration-pill">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 3"/></svg>
          ${c.duration_months} month${c.duration_months == 1 ? '' : 's'}
        </span>
      </td>
      <td data-label="Status">
        <span class="badge ${badgeClass}">
          <span class="badge-dot" style="background:currentColor"></span>
          ${c.status}
        </span>
      </td>
      <td data-label="Actions">
        <div class="row-actions">
          <button title="Edit" onclick="editCourse(${c.id})">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
          </button>
          <button class="del" title="Delete" onclick="deleteCourse(${c.id}, '${c.name.replace(/'/g,"\\'")}')">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6M14 11v6"/><path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>
          </button>
        </div>
      </td>
    </tr>`;
  }).join('');
}

function filterAndRender() {
  const q  = (document.getElementById('courseSearch').value || '').toLowerCase();
  const sf = document.getElementById('courseStatusFilter').value;
  const filtered = _allCourses.filter(c =>
    (!q  || c.name.toLowerCase().includes(q) || c.code.toLowerCase().includes(q)) &&
    (!sf || c.status === sf)
  );
  renderCourseTable(filtered);
}

async function loadCourses() {
  try {
    const res = await fetch(COURSES_URL, { headers: { 'Accept': 'application/json' } });
    _allCourses = await res.json();
    filterAndRender();
  } catch(e) { console.error('Load courses failed', e); }
}

document.getElementById('courseSearch').addEventListener('input', filterAndRender);
document.getElementById('courseStatusFilter').addEventListener('change', filterAndRender);

// ── Add Course ──
document.getElementById('addCourseBtn').addEventListener('click', () => {
  document.getElementById('courseModalTitle').textContent = 'Add Course';
  document.getElementById('cm_id').value      = '';
  document.getElementById('cm_name').value    = '';
  document.getElementById('cm_code').value    = '';
  document.getElementById('cm_duration').value = '';
  document.getElementById('cm_status').value  = 'Active';
  document.querySelectorAll('.c-field-err').forEach(e => e.style.display = 'none');
  openCourseModal('courseModalOverlay');
  setTimeout(() => document.getElementById('cm_name').focus(), 80);
});

// ── Edit Course ──
window.editCourse = function(id) {
  const c = _allCourses.find(x => x.id == id);
  if (!c) return;
  document.getElementById('courseModalTitle').textContent = 'Edit Course';
  document.getElementById('cm_id').value       = c.id;
  document.getElementById('cm_name').value     = c.name;
  document.getElementById('cm_code').value     = c.code;
  document.getElementById('cm_duration').value = c.duration_months;
  document.getElementById('cm_status').value   = c.status;
  document.querySelectorAll('.c-field-err').forEach(e => e.style.display = 'none');
  openCourseModal('courseModalOverlay');
  setTimeout(() => document.getElementById('cm_name').focus(), 80);
};

// ── Save (Add or Edit) ──
document.getElementById('saveCourseBtn').addEventListener('click', async () => {
  const id       = document.getElementById('cm_id').value;
  const name     = document.getElementById('cm_name').value.trim();
  const code     = document.getElementById('cm_code').value.trim();
  const duration = parseInt(document.getElementById('cm_duration').value, 10);
  const status   = document.getElementById('cm_status').value;

  // Validate
  let valid = true;
  document.querySelectorAll('.c-field-err').forEach(e => e.style.display = 'none');
  if (!name) { document.getElementById('cm_nameErr').style.display = 'block'; valid = false; }
  if (!code) { document.getElementById('cm_codeErr').style.display = 'block'; valid = false; }
  if (!duration || duration < 1 || duration > 60) { document.getElementById('cm_durErr').style.display = 'block'; valid = false; }
  if (!valid) return;

  const isEdit = !!id;
  const url    = isEdit ? `${COURSES_URL}/${id}` : COURSES_URL;
  const method = isEdit ? 'PUT' : 'POST';

  try {
    const res = await fetch(url, {
      method,
      headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'X-CSRF-TOKEN': csrfToken },
      body: JSON.stringify({ name, code, duration_months: duration, status }),
    });
    const data = await res.json();
    if (!res.ok) {
      const msgs = data.errors ? Object.values(data.errors).flat() : [data.message || 'Error'];
      ctToast(msgs[0]);
      return;
    }
    closeCourseModal('courseModalOverlay');
    await loadCourses();
    ctToast(isEdit ? 'Course updated.' : 'Course added.');
  } catch(e) { console.error(e); ctToast('Something went wrong: ' + e.message); }
});

// ── Delete Course ──
let _delId = null;
window.deleteCourse = function(id, name) {
  _delId = id;
  document.getElementById('delCourseText').innerHTML = `Delete <b>${name}</b>? This cannot be undone.`;
  openCourseModal('delCourseOverlay');
};

document.getElementById('confirmDelCourse').addEventListener('click', async () => {
  if (!_delId) return;
  try {
    await fetch(`${COURSES_URL}/${_delId}`, {
      method: 'DELETE',
      headers: { 'Accept': 'application/json', 'X-CSRF-TOKEN': csrfToken },
    });
    closeCourseModal('delCourseOverlay');
    _delId = null;
    await loadCourses();
    ctToast('Course deleted.');
  } catch(e) { ctToast('Delete failed.'); }
});

/* =============================================
   BATCHES — full CRUD with API + HTML design
   ============================================= */
const BATCHES_URL = '<?php echo e(url("/api/batches")); ?>';

// ── Helpers ──
function fmtDate(d) {
  if (!d) return '—';
  return new Date(d + 'T00:00:00').toLocaleDateString('en-GB', {day:'2-digit', month:'short', year:'numeric'});
}
function fmtTime12(t) {
  if (!t) return '';
  const [h, m] = t.split(':').map(Number);
  const period = h >= 12 ? 'PM' : 'AM';
  const h12 = ((h % 12) || 12);
  return `${h12}:${String(m).padStart(2,'0')} ${period}`;
}
function formatScheduleList(schedules) {
  if (!schedules || !schedules.length) return '<span class="cell-sub">No sessions scheduled</span>';
  const order = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
  const items = schedules.slice().sort((a, b) => order.indexOf(a.day) - order.indexOf(b.day));
  return items
    .filter(s => s.day)
    .map(s => `<span style="white-space:nowrap">${s.day}${s.time ? ' · ' + fmtTime12(s.time) : ''}</span>`)
    .join('<br>') || '<span class="cell-sub">No sessions scheduled</span>';
}

// ── Modal helpers ──
function openBatchModal(id) { document.getElementById(id).classList.add('open'); document.body.style.overflow = 'hidden'; }
function closeBatchModal(id) { document.getElementById(id).classList.remove('open'); document.body.style.overflow = ''; }

['batchModalOverlay','delBatchOverlay'].forEach(id => {
  document.getElementById(id)?.addEventListener('click', e => { if (e.target.id === id) closeBatchModal(id); });
});
document.getElementById('closeBatchModal').addEventListener('click', () => closeBatchModal('batchModalOverlay'));
document.getElementById('cancelBatchModal').addEventListener('click', () => closeBatchModal('batchModalOverlay'));
document.getElementById('closeDelBatch').addEventListener('click', () => closeBatchModal('delBatchOverlay'));
document.getElementById('cancelDelBatch').addEventListener('click', () => closeBatchModal('delBatchOverlay'));
document.addEventListener('keydown', e => {
  if (e.key === 'Escape') { closeBatchModal('batchModalOverlay'); closeBatchModal('delBatchOverlay'); }
});

// ── Schedule editor ──
const DAYS = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];

function scheduleRowHtml(sch) {
  sch = sch || {day:'', time:''};
  const dayOptions = DAYS.map(d =>
    `<option value="${d}" ${sch.day === d ? 'selected' : ''}>${d}</option>`
  ).join('');
  return `<div class="schedule-row">
    <select class="sch-day">
      <option value="" ${!sch.day ? 'selected' : ''}>Select day</option>
      ${dayOptions}
    </select>
    <input type="time" class="sch-time" value="${sch.time || ''}">
    <button type="button" class="schedule-row-remove" title="Remove">
      <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg>
    </button>
  </div>`;
}
function wireScheduleEditor() {
  const list   = document.getElementById('bm_scheduleList');
  const addBtn = document.getElementById('bm_addScheduleRow');
  if (!list || !addBtn) return;
  // remove old listener by cloning
  const newBtn = addBtn.cloneNode(true);
  addBtn.parentNode.replaceChild(newBtn, addBtn);
  newBtn.addEventListener('click', () => list.insertAdjacentHTML('beforeend', scheduleRowHtml(null)));
  list.addEventListener('click', e => {
    const btn = e.target.closest('.schedule-row-remove');
    if (!btn) return;
    const row = btn.closest('.schedule-row');
    if (list.children.length > 1) row.remove();
    else { row.querySelector('.sch-date').value = ''; row.querySelector('.sch-time').value = ''; }
  });
}
function collectSchedules() {
  return [...document.querySelectorAll('#bm_scheduleList .schedule-row')].map(r => ({
    day:  r.querySelector('.sch-day').value,
    time: r.querySelector('.sch-time').value,
  })).filter(s => s.day || s.time);
}

// ── Render table ──
let _allBatches = [];

function renderBatchTable(batches) {
  const tbody = document.getElementById('batchTableBody');
  const empty = document.getElementById('batchEmpty');
  if (!batches.length) { tbody.innerHTML = ''; empty.style.display = ''; return; }
  empty.style.display = 'none';
  tbody.innerHTML = batches.map(b => {
    const badgeClass = b.status === 'Running' ? 'badge-green' : b.status === 'Upcoming' ? 'badge-amber' : 'badge-slate';
    return `<tr>
      <td data-label="Batch">
        <div class="cell-main">${b.name}</div>
        <div class="cell-sub">Starts ${fmtDate(b.start_date)}</div>
      </td>
      <td data-label="Course">${
        b.courses && b.courses.length
          ? b.courses.map(c =>
              `<span class="badge badge-green" style="margin:2px 2px 2px 0;display:inline-flex;">
                <span class="badge-dot" style="background:currentColor"></span>${c.name}
              </span>`
            ).join('')
          : '<span class="cell-sub">—</span>'
      }</td>
      <td data-label="Schedule">${formatScheduleList(b.schedules)}</td>
      <td data-label="Students">${b.students_count ?? 0}</td>
      <td data-label="Status">
        <span class="badge ${badgeClass}">
          <span class="badge-dot" style="background:currentColor"></span>
          ${b.status}
        </span>
      </td>
      <td data-label="Actions">
        <div class="row-actions">
          <button title="Edit" onclick="editBatch(${b.id})">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
          </button>
          <button class="del" title="Delete" onclick="deleteBatch(${b.id}, '${b.name.replace(/'/g,"\\'")}')">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6M14 11v6"/><path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>
          </button>
        </div>
      </td>
    </tr>`;
  }).join('');
}

function filterAndRenderBatches() {
  const q = (document.getElementById('batchSearch').value || '').toLowerCase();
  renderBatchTable(_allBatches.filter(b => !q || b.name.toLowerCase().includes(q)));
}

async function loadBatches() {
  try {
    const res = await fetch(BATCHES_URL, { headers: { 'Accept': 'application/json' } });
    _allBatches = await res.json();
    filterAndRenderBatches();
  } catch(e) { console.error('Load batches failed', e); }
}

document.getElementById('batchSearch').addEventListener('input', filterAndRenderBatches);

// ── Open modal helpers ──
function openBatchForm(batch = null) {
  document.getElementById('batchModalTitle').textContent = batch ? 'Edit Batch' : 'Add Batch';
  document.getElementById('bm_id').value     = batch ? batch.id : '';
  document.getElementById('bm_name').value   = batch ? batch.name : '';
  document.getElementById('bm_start').value  = batch ? batch.start_date : '';
  document.getElementById('bm_status').value = batch ? batch.status : 'Running';

  // populate schedules
  const list = document.getElementById('bm_scheduleList');
  const rows = (batch && batch.schedules && batch.schedules.length) ? batch.schedules : [null];
  list.innerHTML = rows.map(s => scheduleRowHtml(s)).join('');

  document.querySelectorAll('.b-field-err').forEach(e => e.style.display = 'none');
  openBatchModal('batchModalOverlay');
  wireScheduleEditor();
  setTimeout(() => document.getElementById('bm_name').focus(), 80);
}

// ── Add ──
document.getElementById('addBatchBtn').addEventListener('click', () => openBatchForm(null));

// ── Edit ──
window.editBatch = function(id) {
  const b = _allBatches.find(x => x.id == id);
  if (b) openBatchForm(b);
};

// ── Save ──
document.getElementById('saveBatchBtn').addEventListener('click', async () => {
  const id        = document.getElementById('bm_id').value;
  const name      = document.getElementById('bm_name').value.trim();
  const startDate = document.getElementById('bm_start').value;
  const status    = document.getElementById('bm_status').value;
  const schedules = collectSchedules();

  let valid = true;
  document.querySelectorAll('.b-field-err').forEach(e => e.style.display = 'none');
  if (!name)      { document.getElementById('bm_nameErr').style.display  = 'block'; valid = false; }
  if (!startDate) { document.getElementById('bm_startErr').style.display = 'block'; valid = false; }
  if (!valid) return;

  const isEdit = !!id;
  const url    = isEdit ? `${BATCHES_URL}/${id}` : BATCHES_URL;
  const method = isEdit ? 'PUT' : 'POST';

  try {
    const res = await fetch(url, {
      method,
      headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'X-CSRF-TOKEN': csrfToken },
      body: JSON.stringify({ name, start_date: startDate, status, schedules }),
    });
    const data = await res.json();
    if (!res.ok) {
      const msgs = data.errors ? Object.values(data.errors).flat() : [data.message || 'Error'];
      ctToast(msgs[0]); return;
    }
    closeBatchModal('batchModalOverlay');
    await loadBatches();
    ctToast(isEdit ? 'Batch updated.' : 'Batch added.');
  } catch(e) { console.error(e); ctToast('Something went wrong.'); }
});

// ── Delete ──
let _delBatchId = null;
window.deleteBatch = function(id, name) {
  _delBatchId = id;
  document.getElementById('delBatchText').innerHTML = `Delete <b>${name}</b>? This cannot be undone.`;
  openBatchModal('delBatchOverlay');
};
document.getElementById('confirmDelBatch').addEventListener('click', async () => {
  if (!_delBatchId) return;
  try {
    await fetch(`${BATCHES_URL}/${_delBatchId}`, {
      method: 'DELETE',
      headers: { 'Accept': 'application/json', 'X-CSRF-TOKEN': csrfToken },
    });
    closeBatchModal('delBatchOverlay');
    _delBatchId = null;
    await loadBatches();
    ctToast('Batch deleted.');
  } catch(e) { ctToast('Delete failed.'); }
});

/* =============================================
   STUDENTS — full CRUD with API + HTML design
   ============================================= */
const STUDENTS_URL   = '<?php echo e(url("/api/students")); ?>';
const FORM_DATA_URL  = '<?php echo e(url("/api/students/form-data")); ?>';

let _allStudents  = [];
let _formCourses  = [];
let _formBatches  = [];
let _stPhotoDraft = '';
let _csvDraft     = [];
let _delStudentId = null;
let _editingStudent = null;

// ── Modal helpers ──
function openStModal(id)  { document.getElementById(id).classList.add('open');    document.body.style.overflow = 'hidden'; }
function closeStModal(id) { document.getElementById(id).classList.remove('open'); document.body.style.overflow = ''; }

['studentModalOverlay','delStudentOverlay'].forEach(id => {
  document.getElementById(id)?.addEventListener('click', e => { if (e.target.id === id) closeStModal(id); });
});
document.getElementById('closeStudentModal').addEventListener('click',  () => closeStModal('studentModalOverlay'));
document.getElementById('cancelStudentModal').addEventListener('click', () => closeStModal('studentModalOverlay'));
document.getElementById('closeDelStudent').addEventListener('click',    () => closeStModal('delStudentOverlay'));
document.getElementById('cancelDelStudent').addEventListener('click',   () => closeStModal('delStudentOverlay'));
document.addEventListener('keydown', e => {
  if (e.key === 'Escape') { closeStModal('studentModalOverlay'); closeStModal('delStudentOverlay'); }
});

// ── Load students ──
async function loadStudents() {
  try {
    const res = await fetch(STUDENTS_URL, { headers: { 'Accept': 'application/json' } });
    _allStudents = await res.json();
    populateStudentFilters();
    filterAndRenderStudents();
  } catch(e) { console.error('Load students failed', e); }
}

async function loadFormData() {
  try {
    const res  = await fetch(FORM_DATA_URL, { headers: { 'Accept': 'application/json' } });
    const data = await res.json();
    _formCourses = data.courses || [];
    _formBatches = data.batches || [];
  } catch(e) { console.error('Form data failed', e); }
}

function populateStudentFilters() {
  const cf = document.getElementById('studentCourseFilter');
  const bf = document.getElementById('studentBatchFilter');
  const prevC = cf.value, prevB = bf.value;

  const uniqueCourses = [...new Map(_allStudents.filter(s => s.course_id).map(s => [s.course_id, {id: s.course_id, name: s.course_name}])).values()];
  const uniqueBatches = [...new Map(_allStudents.filter(s => s.batch_id).map(s => [s.batch_id, {id: s.batch_id, name: s.batch_name}])).values()];

  cf.innerHTML = '<option value="">All courses</option>' + uniqueCourses.map(c => `<option value="${c.id}">${c.name}</option>`).join('');
  bf.innerHTML = '<option value="">All batches</option>' + uniqueBatches.map(b => `<option value="${b.id}">${b.name}</option>`).join('');
  if (prevC) cf.value = prevC;
  if (prevB) bf.value = prevB;
}

function filterAndRenderStudents() {
  const q  = (document.getElementById('studentSearch').value || '').toLowerCase();
  const cf = document.getElementById('studentCourseFilter').value;
  const bf = document.getElementById('studentBatchFilter').value;
  const list = _allStudents.filter(s =>
    (!q  || s.name.toLowerCase().includes(q) || (s.student_id||'').toLowerCase().includes(q)) &&
    (!cf || String(s.course_id) === cf) &&
    (!bf || String(s.batch_id) === bf)
  );
  renderStudentTable(list);
}

function renderStudentTable(list) {
  const tbody = document.getElementById('studentTableBody');
  const empty = document.getElementById('studentEmpty');
  // mini stats
  document.getElementById('mscTotal').textContent   = list.length;
  document.getElementById('mscBatches').textContent = new Set(list.map(s => s.batch_id).filter(Boolean)).size;
  document.getElementById('mscAvg').textContent     = '—';
  document.getElementById('mscRisk').textContent    = 0;

  if (!list.length) { tbody.innerHTML = ''; empty.style.display = ''; return; }
  empty.style.display = 'none';

  tbody.innerHTML = list.map(s => {
    const statusBadge = s.status === 'Active'
      ? `<span class="badge badge-green"><span class="badge-dot" style="background:currentColor"></span>Active</span>`
      : `<span class="badge badge-slate"><span class="badge-dot" style="background:currentColor"></span>Inactive</span>`;
    const avatarInner = s.photo_url
      ? `<img src="${s.photo_url}" alt="${s.name}">`
      : s.initials;
    return `<tr>
      <td data-label="Student">
        <div class="row-flex">
          <div class="row-avatar" style="background:${colorFor(s.id)}">${avatarInner}</div>
          <div class="cell-main">${s.name}</div>
        </div>
      </td>
      <td data-label="Student ID">${s.student_id || '—'}</td>
      <td data-label="Father's Name">${s.father_name || '—'}</td>
      <td data-label="Course">${s.course_name || '—'}</td>
      <td data-label="Batch">${s.batch_name || '—'}</td>
      <td data-label="Contact">
        <div class="cell-main">${s.phone || '—'}</div>
        <div class="cell-sub">Home: ${s.home_phone || '—'}</div>
      </td>
      <td data-label="Status">${statusBadge}</td>
      <td data-label="Attendance">${
        s.attendance_pct === null || s.attendance_pct === undefined
          ? '<span class="badge badge-slate">No data</span>'
          : s.attendance_pct >= 85
            ? `<span class="badge badge-green"><span class="badge-dot" style="background:currentColor"></span>${s.attendance_pct}%</span>`
            : s.attendance_pct >= 70
              ? `<span class="badge badge-amber"><span class="badge-dot" style="background:currentColor"></span>${s.attendance_pct}%</span>`
              : `<span class="badge badge-red"><span class="badge-dot" style="background:currentColor"></span>${s.attendance_pct}%</span>`
      }</td>
      <td data-label="Actions">
        <div class="row-actions">
          <button title="Edit" onclick="editStudent(${s.id})">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
          </button>
          <button class="del" title="Delete" onclick="deleteStudent(${s.id}, '${s.name.replace(/'/g,"\\'")}', '${s.student_id || ''}')">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6M14 11v6"/><path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>
          </button>
        </div>
      </td>
    </tr>`;
  }).join('');
}

document.getElementById('studentSearch').addEventListener('input', filterAndRenderStudents);
document.getElementById('studentCourseFilter').addEventListener('change', filterAndRenderStudents);
document.getElementById('studentBatchFilter').addEventListener('change', filterAndRenderStudents);

// ── Build form HTML ──
function courseOptionsHtml(selectedId) {
  return '<option value="">— Select course —</option>' +
    _formCourses.map(c => `<option value="${c.id}" ${String(c.id) === String(selectedId) ? 'selected' : ''}>${c.name}</option>`).join('');
}
function batchOptionsHtml(selectedId) {
  return '<option value="">— Select batch —</option>' +
    _formBatches.map(b => `<option value="${b.id}" ${String(b.id) === String(selectedId) ? 'selected' : ''}>${b.name}</option>`).join('');
}

function manualFormHtml(s) {
  _stPhotoDraft = s ? (s.photo_url || '') : '';
  const prevImg = _stPhotoDraft ? `<img src="${_stPhotoDraft}" alt="">` : (s ? s.initials : 'S');
  return `
    <div class="st-photo-row">
      <div class="student-photo-lg" id="st_photoPreview">${prevImg}</div>
      <div>
        <label class="photo-upload-label">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 16v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2M7 9l5-5 5 5M12 4v12"/></svg>
          Upload Photo
          <input type="file" accept="image/*" id="st_photo">
        </label>
        <div class="photo-hint" style="margin-top:5px;">Optional · JPG or PNG</div>
      </div>
    </div>

    <div class="st-fields-grid">
      <div class="st-section-label">Basic Information</div>

      <div class="field">
        <label>Student ID</label>
        <input type="text" id="st_studentId" value="${s ? s.student_id||'' : ''}" placeholder="e.g. STU-007">
        <span class="st-field-err" id="st_idErr">Required.</span>
      </div>
      <div class="field">
        <label>Student Name</label>
        <input type="text" id="st_name" value="${s ? s.name||'' : ''}" placeholder="Full name">
        <span class="st-field-err" id="st_nameErr">Required.</span>
      </div>
      <div class="field">
        <label>Father's Name</label>
        <input type="text" id="st_father" value="${s ? s.father_name||'' : ''}" placeholder="Father's name">
      </div>

      <div class="st-section-label">Contact</div>

      <div class="field">
        <label>Home Phone</label>
        <input type="text" id="st_homePhone" value="${s ? s.home_phone||'' : ''}" placeholder="01xxx-xxxxxx">
      </div>
      <div class="field">
        <label>Personal Phone</label>
        <input type="text" id="st_phone" value="${s ? s.phone||'' : ''}" placeholder="01xxx-xxxxxx">
      </div>
      <div class="field">
        <label>Status</label>
        <select id="st_status">
          <option ${(!s || s.status==='Active') ? 'selected' : ''}>Active</option>
          <option ${s && s.status==='Inactive' ? 'selected' : ''}>Inactive</option>
        </select>
      </div>

      <div class="st-section-label">Enrollment</div>

      <div class="field">
        <label>Course</label>
        <select id="st_course">${courseOptionsHtml(s ? s.course_id : '')}</select>
      </div>
      <div class="field">
        <label>Batch</label>
        <select id="st_batch">${batchOptionsHtml(s ? s.batch_id : '')}</select>
      </div>
    </div>
  `;
}

function csvPanelHtml() {
  const courseNames = _formCourses.map(c => `<code style="background:var(--surface-2);border:1px solid var(--line);border-radius:5px;padding:2px 7px;font-size:11.5px;font-family:var(--font-mono)">${c.name}</code>`).join(' ');
  const batchNames  = _formBatches.map(b  => `<code style="background:var(--surface-2);border:1px solid var(--line);border-radius:5px;padding:2px 7px;font-size:11.5px;font-family:var(--font-mono)">${b.name}</code>`).join(' ');

  return `<div>
    <div class="csv-actions-row">
      <button type="button" class="btn btn-ghost btn-sm" id="dlSampleCsvBtn">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="M7 10l5 5 5-5M12 15V3"/></svg>
        Download Sample CSV
      </button>
    </div>
    <label class="csv-dropzone">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6M9 15h6M9 11h2"/></svg>
      <div><b>Click to choose a CSV file</b><div class="csv-filename" id="st_csvFileName">No file selected</div></div>
      <input type="file" accept=".csv" id="st_csvInput">
    </label>
    <div class="csv-preview" id="st_csvPreview" style="display:none;">
      <div class="csv-preview-head">Preview — <span id="st_csvCount">0</span> student(s)</div>
      <div class="csv-preview-table-wrap">
        <table class="csv-preview-table">
          <thead><tr><th>Student ID</th><th>Name</th><th>Course</th><th>Batch</th></tr></thead>
          <tbody id="st_csvBody"></tbody>
        </table>
      </div>
    </div>

    <div style="margin-top:14px;display:flex;flex-direction:column;gap:8px;">
      <div style="font-size:11.5px;color:var(--ink-500);line-height:1.6;">
        <b style="color:var(--ink-700);">Required columns:</b>
        Student ID, Student Name, Father's Name, Home Phone, Personal Phone, Status, Course, Batch
      </div>
      ${_formCourses.length ? `
      <div style="font-size:11.5px;color:var(--ink-500);">
        <b style="color:var(--ink-700);">Available Courses</b> <span style="color:var(--ink-300)">(copy exact name):</span><br>
        <div style="margin-top:4px;display:flex;flex-wrap:wrap;gap:4px;">${courseNames}</div>
      </div>` : ''}
      ${_formBatches.length ? `
      <div style="font-size:11.5px;color:var(--ink-500);">
        <b style="color:var(--ink-700);">Available Batches</b> <span style="color:var(--ink-300)">(copy exact name):</span><br>
        <div style="margin-top:4px;display:flex;flex-wrap:wrap;gap:4px;">${batchNames}</div>
      </div>` : `
      <div style="font-size:11.5px;color:var(--vivid-amber);background:var(--vivid-amber-tint);border-radius:8px;padding:8px 12px;">
        ⚠ No courses or batches found. Add them first before importing students.
      </div>`}
    </div>
  </div>`;
}

function buildStudentForm(s) {
  const manual = manualFormHtml(s);
  if (s) return manual;
  return `<div class="form-tabs">
    <button type="button" class="form-tab-btn active" data-tab="manual">Add Manually</button>
    <button type="button" class="form-tab-btn" data-tab="csv">Import from CSV</button>
  </div>
  <div class="form-tab-panel active" id="stTabManual">${manual}</div>
  <div class="form-tab-panel" id="stTabCsv">${csvPanelHtml()}</div>`;
}

function wireStudentForm(s) {
  // photo
  const photoInput = document.getElementById('st_photo');
  if (photoInput) {
    photoInput.addEventListener('change', e => {
      const file = e.target.files[0];
      if (!file) return;
      const reader = new FileReader();
      reader.onload = ev => {
        _stPhotoDraft = ev.target.result;
        document.getElementById('st_photoPreview').innerHTML = `<img src="${_stPhotoDraft}" alt="">`;
      };
      reader.readAsDataURL(file);
    });
  }
  // tabs
  document.querySelectorAll('.form-tab-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      document.querySelectorAll('.form-tab-btn').forEach(b => b.classList.toggle('active', b === btn));
      document.getElementById('stTabManual')?.classList.toggle('active', btn.dataset.tab === 'manual');
      document.getElementById('stTabCsv')?.classList.toggle('active', btn.dataset.tab === 'csv');
      document.getElementById('saveStudentBtn').textContent = btn.dataset.tab === 'csv' ? 'Import Students' : 'Save Student';
    });
  });
  // csv
  wireCsvStudentImport();
}

// ── CSV helpers ──
function splitCsv(line) {
  const r = []; let cur = '', q = false;
  for (let i = 0; i < line.length; i++) {
    const c = line[i];
    if (q) { if (c === '"') { if (line[i+1] === '"') { cur += '"'; i++; } else q = false; } else cur += c; }
    else { if (c === '"') q = true; else if (c === ',') { r.push(cur); cur = ''; } else cur += c; }
  }
  r.push(cur); return r;
}
function parseCsvStudents(text) {
  const lines = text.split(/\r?\n/).filter(l => l.trim());
  if (lines.length < 2) return [];
  const headers = splitCsv(lines[0]).map(h => h.trim().toLowerCase());
  const get = (cells, key) => { const i = headers.indexOf(key); return i > -1 ? (cells[i]||'').trim() : ''; };
  return lines.slice(1).map(line => {
    const cells = splitCsv(line);
    const cName = get(cells,'course'), bName = get(cells,'batch');
    const course = _formCourses.find(c => c.name.toLowerCase() === cName.toLowerCase());
    const batch  = _formBatches.find(b => b.name.toLowerCase() === bName.toLowerCase());
    return {
      student_id:  get(cells,'student id'),
      name:        get(cells,'student name'),
      father_name: get(cells,"father's name") || get(cells,'father name'),
      home_phone:  get(cells,'home phone'),
      phone:       get(cells,'personal phone'),
      status:      get(cells,'status') || 'Active',
      course_id:   course ? course.id : '',
      batch_id:    batch  ? batch.id  : '',
      course_name: cName, batch_name: bName,
    };
  }).filter(r => r.name);
}
function wireCsvStudentImport() {
  const dlBtn = document.getElementById('dlSampleCsvBtn');
  if (dlBtn) dlBtn.addEventListener('click', () => {
    const hdr  = ['Student ID','Student Name',"Father's Name",'Home Phone','Personal Phone','Status','Course','Batch'];
    const c0   = _formCourses[0]?.name || 'Web Development';
    const c1   = _formCourses[1]?.name || _formCourses[0]?.name || 'Graphic Design';
    const b0   = _formBatches[0]?.name || 'Batch A - Morning';
    const b1   = _formBatches[1]?.name || _formBatches[0]?.name || 'Batch B - Evening';
    const rows = [
      ['STU-101','Karim Ahmed','Md. Abdul Karim','01511-300001','01711-300001','Active', c0, b0],
      ['STU-102','Sadia Islam','Md. Rafiqul Islam','01511-300002','01711-300002','Active', c1, b1],
    ];
    const csv  = [hdr,...rows].map(r => r.map(c=>`"${String(c).replace(/"/g,'""')}"`).join(',')).join('\n');
    const a    = Object.assign(document.createElement('a'), { href: URL.createObjectURL(new Blob([csv],{type:'text/csv'})), download:'sample-students.csv' });
    document.body.appendChild(a); a.click(); document.body.removeChild(a);
    ctToast('Sample CSV downloaded');
  });
  const inp = document.getElementById('st_csvInput');
  if (!inp) return;
  inp.addEventListener('change', e => {
    const file = e.target.files[0]; if (!file) return;
    document.getElementById('st_csvFileName').textContent = file.name;
    const reader = new FileReader();
    reader.onload = ev => {
      _csvDraft = parseCsvStudents(ev.target.result);
      const wrap = document.getElementById('st_csvPreview');
      document.getElementById('st_csvCount').textContent = _csvDraft.length;
      wrap.style.display = _csvDraft.length ? '' : 'none';
      document.getElementById('st_csvBody').innerHTML = _csvDraft.slice(0,50).map(r =>
        `<tr><td>${r.student_id||'—'}</td><td>${r.name}</td>
         <td>${r.course_id ? r.course_name : `<span style="color:var(--coral-500)">${r.course_name||'—'} (not found)</span>`}</td>
         <td>${r.batch_id  ? r.batch_name  : `<span style="color:var(--coral-500)">${r.batch_name||'—'} (not found)</span>`}</td></tr>`
      ).join('');
      if (!_csvDraft.length) ctToast('No valid rows found in CSV');
    };
    reader.readAsText(file);
  });
}

// ── Open Add modal ──
document.getElementById('addStudentBtn').addEventListener('click', async () => {
  await loadFormData();
  _editingStudent = null; _csvDraft = []; _stPhotoDraft = '';
  document.getElementById('studentModalTitle').textContent = 'Add Student';
  document.getElementById('saveStudentBtn').textContent    = 'Save Student';
  document.getElementById('studentModalBody').innerHTML = buildStudentForm(null);
  openStModal('studentModalOverlay');
  wireStudentForm(null);
  setTimeout(() => document.getElementById('st_studentId')?.focus(), 80);
});

// ── Edit ──
window.editStudent = async function(id) {
  await loadFormData();
  const s = _allStudents.find(x => x.id == id);
  if (!s) return;
  _editingStudent = s; _stPhotoDraft = s.photo_url || '';
  document.getElementById('studentModalTitle').textContent = 'Edit Student';
  document.getElementById('saveStudentBtn').textContent    = 'Update Student';
  document.getElementById('studentModalBody').innerHTML = buildStudentForm(s);
  openStModal('studentModalOverlay');
  wireStudentForm(s);
};

// ── Save ──
document.getElementById('saveStudentBtn').addEventListener('click', async () => {
  const activeTab = document.querySelector('.form-tab-btn.active')?.dataset.tab || 'manual';

  if (activeTab === 'csv') {
    // CSV import
    if (!_csvDraft.length) { ctToast('Choose a CSV file first'); return; }
    try {
      const res  = await fetch(STUDENTS_URL + '/bulk', {
        method: 'POST',
        headers: { 'Content-Type':'application/json', 'Accept':'application/json', 'X-CSRF-TOKEN': csrfToken },
        body: JSON.stringify({ students: _csvDraft }),
      });
      if (!res.ok) { const d = await res.json(); ctToast(d.message||'Import error'); return; }
      const data = await res.json();
      closeStModal('studentModalOverlay');
      await loadStudents();
      ctToast(`${data.count} student(s) imported.`);
    } catch(e) { ctToast('Import failed.'); }
    return;
  }

  // Manual save
  const studentId = document.getElementById('st_studentId').value.trim();
  const name      = document.getElementById('st_name').value.trim();
  let valid = true;
  document.querySelectorAll('.st-field-err').forEach(e => e.style.display = 'none');
  if (!studentId) { document.getElementById('st_idErr').style.display   = 'block'; valid = false; }
  if (!name)      { document.getElementById('st_nameErr').style.display = 'block'; valid = false; }
  if (!valid) return;

  const payload = {
    student_id:  studentId,
    name,
    father_name: document.getElementById('st_father').value.trim(),
    home_phone:  document.getElementById('st_homePhone').value.trim(),
    phone:       document.getElementById('st_phone').value.trim(),
    status:      document.getElementById('st_status').value,
    course_id:   document.getElementById('st_course').value || null,
    batch_id:    document.getElementById('st_batch').value || null,
    photo_data:  _stPhotoDraft && _stPhotoDraft.startsWith('data:') ? _stPhotoDraft : null,
  };

  const isEdit = !!_editingStudent;
  const url    = isEdit ? `${STUDENTS_URL}/${_editingStudent.id}` : STUDENTS_URL;
  const method = isEdit ? 'PUT' : 'POST';

  try {
    const res = await fetch(url, {
      method,
      headers: { 'Content-Type':'application/json', 'Accept':'application/json', 'X-CSRF-TOKEN': csrfToken },
      body: JSON.stringify(payload),
    });
    const data = await res.json();
    if (!res.ok) {
      const msgs = data.errors ? Object.values(data.errors).flat() : [data.message || 'Error'];
      ctToast(msgs[0]); return;
    }
    closeStModal('studentModalOverlay');
    await loadStudents();
    ctToast(isEdit ? 'Student updated.' : 'Student added.');
  } catch(e) { console.error(e); ctToast('Something went wrong.'); }
});

// ── Delete ──
window.deleteStudent = function(id, name, studentId) {
  _delStudentId = id;
  document.getElementById('delStudentText').innerHTML =
    `Delete <b>${name}</b> (${studentId || ''})?<br>Their attendance history will also be removed.`;
  openStModal('delStudentOverlay');
};
document.getElementById('confirmDelStudent').addEventListener('click', async () => {
  if (!_delStudentId) return;
  try {
    await fetch(`${STUDENTS_URL}/${_delStudentId}`, {
      method: 'DELETE',
      headers: { 'Accept':'application/json', 'X-CSRF-TOKEN': csrfToken },
    });
    closeStModal('delStudentOverlay');
    _delStudentId = null;
    await loadStudents();
    ctToast('Student deleted.');
  } catch(e) { ctToast('Delete failed.'); }
});

/* =============================================
   ATTENDANCE — mark & save per batch per date
   ============================================= */
const ATT_BATCHES_URL  = '<?php echo e(url("/api/attendance/batches")); ?>';
const ATT_STUDENTS_URL = '<?php echo e(url("/api/attendance/students")); ?>';
const ATT_SAVE_URL     = '<?php echo e(url("/api/attendance/save")); ?>';

let _attStudents = []; // current loaded students with status

// ── Load batches into dropdown ──
async function loadAttBatches() {
  try {
    const res  = await fetch(ATT_BATCHES_URL, { headers: { 'Accept': 'application/json' } });
    const json = await res.json();
    const list = json.batches || json;
    const serverTime = json.server_time || '';

    const sel = document.getElementById('attBatchSelect');
    sel.innerHTML = '<option value="">Select a batch…</option>' +
      list.map(b => {
        let tag = '';
        if (b.has_today) {
          tag = ` ★`; // show ★ for ALL batches scheduled today
        }
        return `<option value="${b.id}"
          data-today="${b.has_today ? 1 : 0}"
          data-diff="${b.time_diff_mins !== null ? b.time_diff_mins : 99999}">
          ${b.name} (${b.students_count} students)${tag}
        </option>`;
      }).join('');

    // Auto-select: pick batch with smallest time difference (closest to now)
    // Works for ALL batches scheduled today — no 3-hour limit
    let bestOpt  = null;
    let bestDiff = Infinity;

    sel.querySelectorAll('option[data-today="1"]').forEach(opt => {
      const diff = parseInt(opt.dataset.diff);
      if (diff < bestDiff) {
        bestDiff = diff;
        bestOpt  = opt;
      }
    });

    if (bestOpt) {
      sel.value = bestOpt.value;
      await loadAttStudents();
    }
  } catch(e) { console.error(e); }
}

// ── Load students when batch or date changes ──
async function loadAttStudents() {
  const batchId = document.getElementById('attBatchSelect').value;
  const date    = document.getElementById('attDate').value;

  const list    = document.getElementById('attList');
  const empty   = document.getElementById('attEmpty');
  const summary = document.getElementById('attSummaryBar');
  const markAll = document.getElementById('attMarkAllPresent');
  const saveBtn = document.getElementById('saveAttendanceBtn');

  if (!batchId || !date) {
    list.innerHTML = '';
    empty.style.display = '';
    summary.style.display = 'none';
    markAll.style.display = 'none';
    saveBtn.style.display = 'none';
    document.getElementById('attClearAll').style.display = 'none';
    document.getElementById('attMarkedSection').style.display = 'none';
    return;
  }

  try {
    const res = await fetch(`${ATT_STUDENTS_URL}?batch_id=${batchId}&date=${date}`, {
      headers: { 'Accept': 'application/json' }
    });
    _attStudents = await res.json();

    if (!_attStudents.length) {
      list.innerHTML = '';
      empty.style.display = '';
      empty.querySelector('p').textContent = 'No students in this batch yet.';
      summary.style.display = 'none';
      markAll.style.display = 'none';
      saveBtn.style.display = 'none';
      document.getElementById('attClearAll').style.display = 'none';
      document.getElementById('attMarkedSection').style.display = 'none';
      return;
    }

    empty.style.display   = 'none';
    summary.style.display = '';
    markAll.style.display = '';
    saveBtn.style.display = '';
    document.getElementById('attClearAll').style.display = '';

    renderAttList();
    updateAttSummary();
  } catch(e) { console.error(e); ctToast('Failed to load students.'); }
}

// ── Render student rows ──
function attRowHtml(s) {
  const avatar = s.photo_url
    ? `<img src="${s.photo_url}" alt="${s.name}" style="width:100%;height:100%;object-fit:cover;border-radius:50%;">`
    : s.initials;
  return `<div class="att-row" id="att-row-${s.id}">
    <div class="att-info">
      <div class="row-avatar" style="background:${colorFor(s.id)};width:38px;height:38px;font-size:13px;">${avatar}</div>
      <div>
        <div class="att-name">${s.name}</div>
        <div class="att-id">${s.student_id || '—'}</div>
      </div>
    </div>
    <div class="status-toggle">
      <button class="status-btn" data-s="present" data-id="${s.id}" onclick="setAttStatus(${s.id},'present')">Present</button>
      <button class="status-btn" data-s="late"    data-id="${s.id}" onclick="setAttStatus(${s.id},'late')">Late</button>
      <button class="status-btn" data-s="absent"  data-id="${s.id}" onclick="setAttStatus(${s.id},'absent')">Absent</button>
    </div>
  </div>`;
}

function renderAttList() {
  const pendingList = document.getElementById('attList');
  const markedList  = document.getElementById('attMarkedList');
  const markedSec   = document.getElementById('attMarkedSection');
  const markedCount = document.getElementById('attMarkedCount');

  const pending = _attStudents.filter(s => !s.status);
  const marked  = _attStudents.filter(s => !!s.status);

  // Pending (unmarked) — sorted by name
  pendingList.innerHTML = pending
    .slice().sort((a, b) => a.name.localeCompare(b.name))
    .map(s => attRowHtml(s)).join('');

  // Marked — sorted: absent first, then late, then present
  const statusOrder = { absent: 0, late: 1, present: 2 };
  markedList.innerHTML = marked
    .slice().sort((a, b) => (statusOrder[a.status] ?? 0) - (statusOrder[b.status] ?? 0))
    .map(s => attRowHtml(s)).join('');

  // Show/hide marked section
  if (marked.length > 0) {
    markedSec.style.display = '';
    markedCount.textContent = marked.length;
  } else {
    markedSec.style.display = 'none';
  }

  // Apply active button states for all students
  _attStudents.forEach(s => applyStatus(s.id, s.status));
}

function applyStatus(studentId, status) {
  const row = document.getElementById('att-row-' + studentId);
  if (!row) return;
  row.querySelectorAll('.status-btn').forEach(btn => {
    btn.classList.toggle('active', btn.dataset.s === status);
  });
}

window.setAttStatus = function(studentId, status) {
  const s = _attStudents.find(x => x.id == studentId);
  if (s) s.status = status;
  updateAttSummary();

  // Re-render both containers with a quick fade
  const pendingList = document.getElementById('attList');
  const markedList  = document.getElementById('attMarkedList');
  pendingList.style.opacity = '0.5';
  markedList.style.opacity  = '0.5';
  setTimeout(() => {
    renderAttList();
    pendingList.style.transition = 'opacity .2s';
    markedList.style.transition  = 'opacity .2s';
    pendingList.style.opacity = '1';
    markedList.style.opacity  = '1';
  }, 120);
};

// ── Summary counts ──
function updateAttSummary() {
  const counts = { present: 0, late: 0, absent: 0, unmarked: 0 };
  _attStudents.forEach(s => {
    if (!s.status) counts.unmarked++;
    else counts[s.status] = (counts[s.status] || 0) + 1;
  });
  document.getElementById('attPresentN').textContent = counts.present;
  document.getElementById('attLateN').textContent    = counts.late;
  document.getElementById('attAbsentN').textContent  = counts.absent;
  document.getElementById('attTotalN').textContent   = _attStudents.length;
}

// ── Mark all present ──
document.getElementById('attMarkAllPresent').addEventListener('click', () => {
  _attStudents.forEach(s => { s.status = 'present'; applyStatus(s.id, 'present'); });
  updateAttSummary();
});

// ── Clear all ──
document.getElementById('attClearAll').addEventListener('click', () => {
  _attStudents.forEach(s => { s.status = null; });
  // re-sort alphabetically
  _attStudents.sort((a, b) => a.name.localeCompare(b.name));
  const pendingList = document.getElementById('attList');
  const markedList  = document.getElementById('attMarkedList');
  pendingList.style.opacity = '0.5';
  markedList.style.opacity  = '0.5';
  setTimeout(() => {
    renderAttList();
    pendingList.style.transition = 'opacity .2s';
    markedList.style.transition  = 'opacity .2s';
    pendingList.style.opacity = '1';
    markedList.style.opacity  = '1';
    updateAttSummary();
  }, 120);
});

// ── Listeners ──
document.getElementById('attBatchSelect').addEventListener('change', loadAttStudents);
document.getElementById('attDate').addEventListener('change', loadAttStudents);

// ── Save ──
document.getElementById('saveAttendanceBtn').addEventListener('click', async () => {
  const batchId = document.getElementById('attBatchSelect').value;
  const date    = document.getElementById('attDate').value;

  if (!batchId || !date || !_attStudents.length) {
    ctToast('Select a batch and date first.'); return;
  }

  const records = _attStudents.map(s => ({
    student_id: s.id,
    status: s.status || 'absent', // null → absent on save
  }));

  try {
    const res  = await fetch(ATT_SAVE_URL, {
      method:  'POST',
      headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'X-CSRF-TOKEN': csrfToken },
      body:    JSON.stringify({ batch_id: batchId, date, records }),
    });
    const data = await res.json();
    if (!res.ok) { ctToast(data.message || 'Save failed.'); return; }
    ctToast(`Attendance saved — ${data.saved} records.`);
    setTimeout(() => window.location.reload(), 800);
  } catch(e) { ctToast('Something went wrong.'); }
});

/* =============================================
   ATTENDANCE HISTORY — batch-wise past records
   ============================================= */
const ATT_HISTORY_URL    = '<?php echo e(url("/api/attendance/history")); ?>';
const ATT_UPDATE_URL     = '<?php echo e(url("/api/attendance/update")); ?>';
const ATT_DELETE_DAY_URL = '<?php echo e(url("/api/attendance/delete-day")); ?>';

async function loadAttHistory(batchId, month) {
  const body = document.getElementById('histBody');
  if (!batchId) {
    body.innerHTML = `<div class="hist-empty">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3v18h18"/><path d="M18 17V9M13 17V5M8 17v-4"/></svg>
      <p>Select a batch to view attendance history.</p></div>`;
    return;
  }
  body.innerHTML = '<div class="hist-empty">Loading…</div>';
  try {
    const url = `${ATT_HISTORY_URL}?batch_id=${batchId}${month ? '&month='+month : ''}`;
    const res  = await fetch(url, { headers: { 'Accept': 'application/json' } });
    const data = await res.json();
    const { dates, students, month_label, available_months } = data;
    const currentMonth = data.month;
    const currentBatchId = batchId;

    // Month navigation
    const monthNav = available_months && available_months.length > 1
      ? available_months.map(m =>
          `<button onclick="loadAttHistory(document.getElementById('histBatchSelect').value,'${m}')"
            style="padding:5px 12px;border-radius:8px;border:1px solid var(--line);background:${m===currentMonth?'var(--navy-950)':'var(--surface-2)'};color:${m===currentMonth?'#fff':'var(--ink-700)'};font-size:12px;font-weight:600;cursor:pointer;font-family:var(--font-body);">
            ${new Date(m+'-01').toLocaleDateString('en-GB',{month:'short',year:'numeric'})}
          </button>`).join('')
      : '';

    const navBar = `<div style="padding:14px 20px;border-bottom:1px solid var(--line);display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px;">
      <span style="font-size:13px;font-weight:700;color:var(--ink-900);">${month_label}</span>
      <div style="display:flex;gap:6px;flex-wrap:wrap;align-items:center;">
        ${monthNav}
        <button onclick="loadAllBatchData('${currentBatchId}')"
          style="padding:5px 13px;border-radius:8px;border:1px solid var(--teal-500);background:var(--teal-tint-14);color:var(--teal-500);font-size:12px;font-weight:700;cursor:pointer;font-family:var(--font-body);display:inline-flex;align-items:center;gap:5px;">
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M3 3v18h18"/><path d="M18 17V9M13 17V5M8 17v-4"/></svg>
          All Data
        </button>
        <button onclick="exportAttCsv('${currentBatchId}','${currentMonth}')"
          style="padding:5px 13px;border-radius:8px;border:1px solid var(--line);background:var(--surface-2);color:var(--ink-700);font-size:12px;font-weight:700;cursor:pointer;font-family:var(--font-body);display:inline-flex;align-items:center;gap:5px;">
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
          Export CSV
        </button>
      </div>
    </div>`;

    if (!dates.length || !students.length) {
      body.innerHTML = navBar + '<div class="hist-empty"><p>No attendance records for this month.</p></div>';
      return;
    }

    function shortDate(d) {
      return new Date(d+'T00:00:00').toLocaleDateString('en-GB',{day:'2-digit',month:'short'});
    }
    function dayName(d) {
      return new Date(d+'T00:00:00').toLocaleDateString('en-GB',{weekday:'short'});
    }
    function pctColor(p) {
      return p >= 75 ? 'var(--vivid-green)' : p >= 50 ? 'var(--vivid-amber)' : 'var(--coral-500)';
    }

    // ── View All btn removed — name click opens modal ──
    function clickableName(s) {
      return `<div onclick="openStudentHistModal(${s.id},'${s.student_name.replace(/'/g,"\\'")}')"
        style="font-weight:700;font-size:13px;color:var(--teal-500);cursor:pointer;text-decoration:underline;text-underline-offset:2px;text-decoration-style:dotted;">
        ${s.student_name}
      </div>
      <div style="font-size:11px;color:var(--ink-500);margin-bottom:2px;">${s.student_id}</div>`;
    }

    // ════════════════════════════════
    // DESKTOP — cross table
    // ════════════════════════════════
    const dateThs = dates.map(d =>
      `<th class="date-th" title="${d}">
        <div class="date-th-wrap">
          <div>${shortDate(d)}</div>
          <div style="font-weight:400;opacity:.7;">${dayName(d)}</div>
          <button class="date-del-btn" title="Delete this day's attendance"
            onclick="deleteAttDay('${currentBatchId}','${d}','${shortDate(d)}')">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg>
          </button>
        </div>
      </th>`
    ).join('');

    const tableRows = students.map(s => {
      const cells = s.cells.map((status, i) => {
        const d = dates[i];
        if (status === 'not_in_batch') return `<td style="text-align:center"><span class="att-cell" style="background:transparent;color:var(--ink-300);font-size:10px;">N/A</span></td>`;
        if (!status) return `<td style="text-align:center">
          <span class="att-cell none editable" title="Click to mark"
            onclick="editAttCell(this,'${currentBatchId}','${s.id}','${d}',null)">—</span></td>`;
        const lbl = status==='present'?'P':status==='late'?'L':'A';
        return `<td style="text-align:center">
          <span class="att-cell ${status} editable" title="Click to edit"
            onclick="editAttCell(this,'${currentBatchId}','${s.id}','${d}','${status}')">${lbl}</span></td>`;
      }).join('');
      const t   = s.total;
      const pct = t.eligible > 0 ? Math.round((t.present+t.late)/t.eligible*100) : 0;
      const tot = `<td style="text-align:center;white-space:nowrap;">
        <span style="color:var(--badge-green-text);font-weight:700;">${t.present}P</span>
        <span style="color:var(--ink-300);margin:0 2px;">/</span>
        <span style="color:var(--badge-amber-text);font-weight:700;">${t.late}L</span>
        <span style="color:var(--ink-300);margin:0 2px;">/</span>
        <span style="color:var(--badge-red-text);font-weight:700;">${t.absent}A</span>
      </td>`;
      return `<tr>
        <td>
          ${clickableName(s)}
        </td>${cells}${tot}
      </tr>`;
    }).join('');

    const desktopTable = `<div class="hist-table-outer">
      <div class="hist-table-wrap" id="histTableWrap">
        <table class="hist-cross">
          <thead><tr>
            <th style="min-width:170px;">Student</th>${dateThs}
            <th style="text-align:center;min-width:110px;">Total</th>
          </tr></thead>
          <tbody>${tableRows}</tbody>
        </table>
      </div>
      <div class="hist-fake-scroll" id="histFakeScroll">
        <div class="hist-fake-inner" id="histFakeInner"></div>
      </div>
    </div>`;

    // ════════════════════════════════
    // MOBILE — student cards
    // ════════════════════════════════
    const mobileCards = students.map(s => {
      const t   = s.total;
      const pct = t.eligible > 0 ? Math.round((t.present+t.late)/t.eligible*100) : 0;
      const pc  = pctColor(pct);
      // Eligible classes = dates that are not 'not_in_batch' for this student
      const eligibleCount = t.eligible;
      const chips = s.cells.map((status, i) => {
        const d = dates[i];
        if (status === 'not_in_batch') return '';
        const lbl = !status ? '—' : status==='present'?'P':status==='late'?'L':'A';
        const cls = !status ? 'none' : status;
        return `<div style="display:flex;flex-direction:column;align-items:center;gap:3px;flex-shrink:0;cursor:pointer;"
          onclick="editAttCell(this.querySelector('.att-cell'),'${currentBatchId}','${s.id}','${d}','${status||null}')">
          <span class="att-cell ${cls} editable">${lbl}</span>
          <span style="font-size:9.5px;font-weight:600;color:var(--ink-500);line-height:1.1;text-align:center;white-space:nowrap;">${shortDate(d)}</span>
          <span style="font-size:9px;color:var(--ink-300);line-height:1;text-align:center;">${dayName(d)}</span>
        </div>`;
      }).join('');
      const bar = `<div style="height:6px;border-radius:3px;background:var(--line);overflow:hidden;margin-top:6px;">
        <div style="height:100%;width:${pct}%;background:${pc};border-radius:3px;"></div></div>`;
      return `<div style="background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);box-shadow:var(--shadow-sm);overflow:hidden;">
        <div style="display:flex;align-items:center;justify-content:space-between;padding:14px 18px 10px;border-bottom:1px solid var(--line);gap:12px;flex-wrap:wrap;">
          <div style="display:flex;align-items:center;gap:12px;">
            <div style="width:38px;height:38px;border-radius:50%;background:linear-gradient(135deg,var(--teal-400),var(--navy-800));display:flex;align-items:center;justify-content:center;font-family:var(--font-display);font-weight:700;font-size:13px;color:#fff;flex-shrink:0;">
              ${s.student_name.split(' ').map(w=>w[0]).slice(0,2).join('').toUpperCase()}
            </div>
            <div onclick="openStudentHistModal(${s.id},'${s.student_name.replace(/'/g,"\\'")}')" style="cursor:pointer;">
              <div style="font-weight:700;font-size:14px;color:var(--teal-500);text-decoration:underline;text-underline-offset:2px;text-decoration-style:dotted;">${s.student_name}</div>
              <div style="font-size:11.5px;color:var(--ink-500);margin-top:1px;">${s.student_id}</div>
            </div>
          </div>
          <div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;">
            <span style="padding:4px 10px;border-radius:100px;font-size:11.5px;font-weight:700;background:var(--teal-tint-14);color:var(--badge-green-text);">${t.present}P</span>
            <span style="padding:4px 10px;border-radius:100px;font-size:11.5px;font-weight:700;background:var(--amber-tint-16);color:var(--badge-amber-text);">${t.late}L</span>
            <span style="padding:4px 10px;border-radius:100px;font-size:11.5px;font-weight:700;background:var(--badge-red-bg);color:var(--badge-red-text);">${t.absent}A</span>
            <span style="padding:4px 10px;border-radius:100px;font-size:11.5px;font-weight:700;background:var(--badge-slate-bg);color:var(--ink-700);">${dates.length} Classes</span>
            <span style="font-size:12px;font-weight:800;color:${pc};">${pct}%</span>
          </div>
        </div>
        <div style="padding:0 18px 2px;">${bar}</div>
        <div style="padding:12px 18px;display:grid;grid-template-columns:repeat(auto-fill,minmax(52px,1fr));gap:10px 8px;">
          ${chips || '<span style="font-size:12px;color:var(--ink-300);">No records</span>'}
        </div>
      </div>`;
    }).join('');

    // Render both, show/hide via CSS
    body.innerHTML = navBar +
      `<div class="hist-desktop-view">${desktopTable}</div>` +
      `<div class="hist-mobile-view">${mobileCards}</div>`;

    // Sync fake scrollbar with table wrap
    requestAnimationFrame(() => {
      const wrap  = document.getElementById('histTableWrap');
      const fake  = document.getElementById('histFakeScroll');
      const inner = document.getElementById('histFakeInner');
      if (!wrap || !fake || !inner) return;
      // Set fake inner width to match table scroll width
      inner.style.width = wrap.scrollWidth + 'px';
      // Sync: fake → table
      fake.addEventListener('scroll', () => { wrap.scrollLeft = fake.scrollLeft; });
      // Sync: table → fake (mouse/touch drag on table itself)
      wrap.addEventListener('scroll', () => { fake.scrollLeft = wrap.scrollLeft; });
    });

  } catch(e) {
    console.error(e);
    body.innerHTML = '<div class="hist-empty"><p>Failed to load history.</p></div>';
  }
}

// Sync history batch dropdown with attendance batch dropdown
document.getElementById('histBatchSelect').addEventListener('change', e => {
  loadAttHistory(e.target.value, null); // null = current month
});

function loadAllBatchData(batchId) {
  loadAttHistory(batchId, 'all');
}

// ── Export attendance CSV ──
const ATT_EXPORT_URL = '<?php echo e(url("/api/attendance/export")); ?>';
function exportAttCsv(batchId, month) {
  if (!batchId) return;
  const url = `${ATT_EXPORT_URL}?batch_id=${batchId}&month=${month || ''}`;
  // Trigger download
  const a = document.createElement('a');
  a.href = url;
  a.download = '';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

// Populate history batch dropdown when batches load
const _origLoadAttBatches = loadAttBatches;
loadAttBatches = async function() {
  await _origLoadAttBatches();
};

// Populate reports batch dropdown independently
async function loadReportsBatches() {
  try {
    const res  = await fetch(ATT_BATCHES_URL, { headers: { 'Accept': 'application/json' } });
    const json = await res.json();
    const list = json.batches || json;
    const sel  = document.getElementById('histBatchSelect');
    sel.innerHTML = '<option value="">Select batch…</option>' +
      list.map(b => `<option value="${b.id}">${b.name}</option>`).join('');
  } catch(e) { console.error(e); }
}

// ── Edit single attendance cell ──
window.editAttCell = function(el, batchId, studentId, date, currentStatus) {
  // Replace cell with inline dropdown
  const td = el.parentElement;
  const sel = document.createElement('select');
  sel.className = 'att-edit-select';
  sel.innerHTML = `
    <option value="present" ${currentStatus==='present'?'selected':''}>P</option>
    <option value="late"    ${currentStatus==='late'   ?'selected':''}>L</option>
    <option value="absent"  ${currentStatus==='absent' ?'selected':''}>A</option>
  `;
  td.innerHTML = '';
  td.appendChild(sel);
  sel.focus();

  async function saveEdit(newStatus) {
    if (!newStatus || newStatus === currentStatus) {
      // restore original cell
      const lbl = currentStatus==='present'?'P':currentStatus==='late'?'L':currentStatus==='absent'?'A':'—';
      const cls = currentStatus || 'none';
      td.innerHTML = `<span class="att-cell ${cls} editable"
        onclick="editAttCell(this,'${batchId}','${studentId}','${date}','${currentStatus||''}')">${lbl}</span>`;
      return;
    }
    try {
      const res = await fetch(ATT_UPDATE_URL, {
        method: 'PATCH',
        headers: {'Content-Type':'application/json','Accept':'application/json','X-CSRF-TOKEN':csrfToken},
        body: JSON.stringify({batch_id:batchId, student_id:studentId, date, status:newStatus}),
      });
      if (res.ok) {
        const lbl = newStatus==='present'?'P':newStatus==='late'?'L':'A';
        td.innerHTML = `<span class="att-cell ${newStatus} editable"
          onclick="editAttCell(this,'${batchId}','${studentId}','${date}','${newStatus}')">${lbl}</span>`;
        ctToast('Attendance updated.');
      }
    } catch(e) { ctToast('Update failed.'); }
  }

  sel.addEventListener('change', () => saveEdit(sel.value));
  sel.addEventListener('blur',   () => saveEdit(sel.value));
};

// ── Delete all attendance for a date ──
window.deleteAttDay = function(batchId, date, dateLabel) {
  if (!confirm(`Delete all attendance for ${dateLabel}? This cannot be undone.`)) return;
  fetch(ATT_DELETE_DAY_URL, {
    method: 'DELETE',
    headers: {'Content-Type':'application/json','Accept':'application/json','X-CSRF-TOKEN':csrfToken},
    body: JSON.stringify({batch_id:batchId, date}),
  }).then(r => r.json()).then(data => {
    if (data.success) {
      ctToast(`Deleted ${data.deleted} record(s) for ${dateLabel}.`);
      // Reload history for current batch
      const histSel = document.getElementById('histBatchSelect');
      loadAttHistory(histSel.value, null);
    }
  }).catch(() => ctToast('Delete failed.'));
};

// ── Transfer Students Page ──
const ATT_TRANSFERS_URL = '<?php echo e(url("/api/attendance/transfers")); ?>';
let _allTransfers = [];

async function loadTransfersPage() {
  const body = document.getElementById('transfersPageBody');
  if (!body) return;
  body.innerHTML = '<div class="tr-empty">Loading…</div>';
  try {
    const res  = await fetch(ATT_TRANSFERS_URL, { headers: { 'Accept': 'application/json' } });
    _allTransfers = await res.json();
    renderTransfersPage(_allTransfers);
  } catch(e) {
    console.error(e);
    body.innerHTML = '<div class="tr-empty">Failed to load.</div>';
  }
}

function renderTransfersPage(list) {
  const body = document.getElementById('transfersPageBody');
  if (!list.length) {
    body.innerHTML = `<div class="tr-empty">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M17 1l4 4-4 4"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><path d="M7 23l-4-4 4-4"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg>
      <p>No transfer students found.<br>Students who change batch will appear here.</p>
    </div>`;
    return;
  }

  function shortDate(d) { return new Date(d+'T00:00:00').toLocaleDateString('en-GB',{day:'2-digit',month:'short'}); }
  function dayLabel(d)  { return new Date(d+'T00:00:00').toLocaleDateString('en-GB',{weekday:'short'}); }
  function pctCol(p)    { return p===null ? 'var(--ink-400,#9AA3B5)' : p>=75 ? 'var(--vivid-green)' : p>=50 ? 'var(--vivid-amber)' : 'var(--coral-500)'; }

  body.innerHTML = list.map(s => {
    const bgColor = colorFor(s.student_id);

    const batchBlocks = s.batches.map(b => {
      const pc  = pctCol(b.att_pct);
      const pct = b.att_pct ?? 0;

      // Stats badges
      const present = Object.values(b.records).filter(v=>v==='present').length;
      const late    = Object.values(b.records).filter(v=>v==='late').length;
      const absent  = Object.values(b.records).filter(v=>v==='absent').length;

      const chips = (b.dates || []).map(d => {
        const st  = b.records[d] || null;
        const lbl = !st ? '—' : st==='present'?'P':st==='late'?'L':'A';
        const cls = st || 'none';
        return `<div class="tr-chip">
          <span class="tr-att-cell ${cls}">${lbl}</span>
          <span class="tr-chip-date">${shortDate(d)}</span>
          <span class="tr-chip-day">${dayLabel(d)}</span>
        </div>`;
      }).join('');

      return `<div class="tr-batch-block">
        <div class="tr-batch-header">
          <div class="tr-batch-name">
            ${b.batch_name}
            ${b.is_current ? `<span style="padding:2px 9px;border-radius:100px;font-size:10.5px;font-weight:600;background:var(--teal-tint-12);color:var(--badge-green-text);font-family:var(--font-body);">Current</span>` : `<span style="padding:2px 9px;border-radius:100px;font-size:10.5px;font-weight:600;background:var(--badge-slate-bg);color:var(--ink-500);font-family:var(--font-body);">Previous</span>`}
          </div>
          <div class="tr-batch-stats">
            <span style="padding:3px 9px;border-radius:100px;font-size:11px;font-weight:700;background:var(--teal-tint-14);color:var(--badge-green-text);">${present}P</span>
            <span style="padding:3px 9px;border-radius:100px;font-size:11px;font-weight:700;background:var(--amber-tint-16);color:var(--badge-amber-text);">${late}L</span>
            <span style="padding:3px 9px;border-radius:100px;font-size:11px;font-weight:700;background:var(--badge-red-bg);color:var(--badge-red-text);">${absent}A</span>
            <span style="padding:3px 9px;border-radius:100px;font-size:11px;font-weight:700;background:var(--badge-slate-bg);color:var(--ink-700);">${b.days} Classes</span>
            ${b.att_pct !== null ? `<span style="font-size:12px;font-weight:800;color:${pc};">${b.att_pct}%</span>` : ''}
          </div>
        </div>
        <div class="tr-progress">
          <div class="tr-progress-fill" style="width:${pct}%;background:${pc};"></div>
        </div>
        <div class="tr-chips">
          ${chips || '<span style="font-size:12px;color:var(--ink-300);">No records</span>'}
        </div>
      </div>`;
    }).join('');

    return `<div class="tr-card">
      <div class="tr-card-head">
        <div class="tr-avatar" style="background:${bgColor};">${s.initials}</div>
        <div>
          <div class="tr-student-name">${s.name}</div>
          <div class="tr-student-code">${s.student_code}</div>
        </div>
        <span class="tr-current-badge">
          <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" style="margin-right:4px;vertical-align:middle;"><path d="M17 1l4 4-4 4"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><path d="M7 23l-4-4 4-4"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg>
          ${s.current_batch}
        </span>
      </div>
      ${batchBlocks}
    </div>`;
  }).join('');
}

// Search
document.addEventListener('DOMContentLoaded', () => {
  const inp = document.getElementById('trSearch');
  if (inp) inp.addEventListener('input', () => {
    const q = inp.value.toLowerCase();
    renderTransfersPage(_allTransfers.filter(s =>
      s.name.toLowerCase().includes(q) || (s.student_code||'').toLowerCase().includes(q)
    ));
  });
});

/* =============================================
   NAVIGATION + other existing JS
   ============================================= */
const views    = document.querySelectorAll('.view');
const navItems = document.querySelectorAll('.nav-item');
const pageTitle   = document.getElementById('pageTitle');
const pageEyebrow = document.getElementById('pageEyebrow');

const titles = {
  dashboard:  ['Dashboard',          'Overview'],
  courses:    ['Courses',            'Academics'],
  batches:    ['Batches',            'Academics'],
  students:   ['Students',           'Academics'],
  attendance: ['Attendance',         'Tracking'],
  transfers:  ['Transfer Students',  'Tracking'],
  reports:    ['Reports',            'Tracking'],
  profile:    ['Admin Profile',      'Account'],
};

function switchView(name) {
  views.forEach(v => v.classList.toggle('active', v.id === 'view-' + name));
  navItems.forEach(n => n.classList.toggle('active', n.dataset.view === name));
  if (titles[name]) {
    pageTitle.textContent   = titles[name][0];
    pageEyebrow.textContent = titles[name][1];
  }
  document.getElementById('sidebar').classList.remove('open');
  document.getElementById('overlayBg').classList.remove('show');
  // White bg for profile, default for others
  const contentEl = document.querySelector('.content');
  if (contentEl) contentEl.style.background = name === 'profile' ? 'var(--surface)' : '';
  if (name === 'courses')    loadCourses();
  if (name === 'batches')    loadBatches();
  if (name === 'students')   loadStudents();
  if (name === 'attendance') {
    loadAttBatches();
    // set today's date if empty
    const d = document.getElementById('attDate');
    if (!d.value) d.value = new Date().toISOString().slice(0, 10);
  }
  if (name === 'reports')   { loadReportsBatches(); }
  if (name === 'transfers')   loadTransfersPage();
}
navItems.forEach(el => el.addEventListener('click', () => switchView(el.dataset.view)));

// ── Preload search data silently on page load ──
// So desktop/mobile search works from Dashboard without visiting each view first
(function preloadSearchData() {
  function silentLoad(url, onDone) {
    fetch(url, { headers: { 'Accept': 'application/json' } })
      .then(r => r.json())
      .then(onDone)
      .catch(() => {}); // silent fail
  }
  // Only load if not already loaded (avoid double-fetch if user navigates there)
  if (!_allStudents.length) silentLoad(STUDENTS_URL, data => { _allStudents = data; });
  if (!_allCourses.length)  silentLoad(COURSES_URL,  data => { _allCourses  = data; });
  if (!_allBatches.length)  silentLoad(BATCHES_URL,  data => { _allBatches  = data; });
})();

// Mobile sidebar
document.getElementById('menuToggle').addEventListener('click', () => {
  document.getElementById('sidebar').classList.add('open');
  document.getElementById('overlayBg').classList.add('show');
});
document.getElementById('overlayBg').addEventListener('click', () => {
  document.getElementById('sidebar').classList.remove('open');
  document.getElementById('overlayBg').classList.remove('show');
});

// Mobile nav active state
function updateMobileNav(name) {
  document.querySelectorAll('.mobile-nav-item').forEach(btn => {
    btn.classList.toggle('active', btn.dataset.view === name);
  });
}

// ── Unified Search Engine (desktop dropdown + mobile modal) ──
(function() {

  // ── shared helpers ──
  const FILTERS = ['all','students','courses','batches'];

  function buildResults(q, activeFilter) {
    const ql = q.toLowerCase();
    const matchStudents = activeFilter === 'all' || activeFilter === 'students';
    const matchCourses  = activeFilter === 'all' || activeFilter === 'courses';
    const matchBatches  = activeFilter === 'all' || activeFilter === 'batches';

    const students = matchStudents
      ? (_allStudents||[]).filter(s => s.name.toLowerCase().includes(ql)||(s.student_id||'').toLowerCase().includes(ql)).slice(0,6)
      : [];
    const courses = matchCourses
      ? (_allCourses||[]).filter(c => c.name.toLowerCase().includes(ql)||(c.code||'').toLowerCase().includes(ql)).slice(0,4)
      : [];
    const batches = matchBatches
      ? (_allBatches||[]).filter(b => b.name.toLowerCase().includes(ql)).slice(0,4)
      : [];

    return { students, courses, batches };
  }

  function buildStudentItemHtml(s, color, onCloseExtra) {
    const initials = s.name.split(' ').map(w=>w[0]).slice(0,2).join('').toUpperCase();
    const sub = s.student_id + (s.batch_name && s.batch_name !== '—' ? ' · ' + s.batch_name : '');
    // Click opens attendance modal, also closes search
    const onclick = `${onCloseExtra}openStudentHistModal(${s.id},'${s.name.replace(/'/g,"\\'")}');`;
    return `<div onclick="${onclick}"
      style="display:flex;align-items:center;gap:11px;padding:10px 14px;cursor:pointer;transition:background .1s;"
      onmouseover="this.style.background='var(--surface-2)'" onmouseout="this.style.background=''">
      <div style="width:32px;height:32px;border-radius:8px;background:${color};display:flex;align-items:center;justify-content:center;flex-shrink:0;color:#fff;font-size:10px;font-weight:700;">${initials}</div>
      <div style="min-width:0;flex:1;">
        <div style="font-size:13px;font-weight:600;color:var(--ink-900);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${s.name}</div>
        <div style="font-size:11.5px;color:var(--ink-500);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${sub}</div>
      </div>
      <div style="font-size:10px;color:var(--teal-500);font-weight:600;white-space:nowrap;flex-shrink:0;">View Attendance</div>
    </div>`;
  }

  function buildItemHtml(label, sub, view, color, onClickExtra) {
    const initials = label.split(' ').map(w=>w[0]).slice(0,2).join('').toUpperCase();
    return `<div onclick="${onClickExtra}switchView('${view}');"
      style="display:flex;align-items:center;gap:11px;padding:10px 14px;cursor:pointer;transition:background .1s;"
      onmouseover="this.style.background='var(--surface-2)'" onmouseout="this.style.background=''">
      <div style="width:32px;height:32px;border-radius:8px;background:${color};display:flex;align-items:center;justify-content:center;flex-shrink:0;color:#fff;font-size:10px;font-weight:700;">${initials}</div>
      <div style="min-width:0;"><div style="font-size:13px;font-weight:600;color:var(--ink-900);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${label}</div>
      <div style="font-size:11.5px;color:var(--ink-500);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${sub}</div></div>
    </div>`;
  }

  function buildSection(title) {
    return `<div style="padding:6px 14px 3px;font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.6px;color:var(--ink-400,#9AA3B5);background:var(--surface-2);border-bottom:1px solid var(--line);">${title}</div>`;
  }

  function renderHtml(students, courses, batches, onClickExtra) {
    if (!students.length && !courses.length && !batches.length) {
      return '<div style="padding:24px;text-align:center;font-size:13px;color:var(--ink-400,#9AA3B5);">No results found.</div>';
    }
    let html = '';
    if (students.length) {
      html += buildSection('Students');
      html += students.map(s => buildStudentItemHtml(s, colorFor(s.id), onClickExtra)).join('');
    }
    if (courses.length) {
      html += buildSection('Courses');
      html += courses.map(c => buildItemHtml(c.name, c.code+' · '+c.duration_months+' months', 'courses', '#2F6FE4', onClickExtra)).join('');
    }
    if (batches.length) {
      html += buildSection('Batches');
      html += batches.map(b => buildItemHtml(b.name, b.status, 'batches', '#7C4DE0', onClickExtra)).join('');
    }
    return html;
  }

  // ── Filter chips builder ──
  function filterChipsHtml(active, onChangeFn) {
    const labels = { all:'All', students:'Students', courses:'Courses', batches:'Batches' };
    return `<div id="${onChangeFn}_chips" style="display:flex;gap:6px;padding:10px 14px 8px;border-bottom:1px solid var(--line);flex-wrap:wrap;">` +
      FILTERS.map(f => `<button onclick="${onChangeFn}('${f}')"
        id="${onChangeFn}_chip_${f}"
        style="padding:4px 11px;border-radius:100px;font-size:11.5px;font-weight:600;cursor:pointer;border:1px solid ${f===active?'var(--teal-500)':'var(--line)'};background:${f===active?'var(--teal-tint-14)':'var(--surface-2)'};color:${f===active?'var(--teal-500)':'var(--ink-700)'};transition:all .12s;">
        ${labels[f]}
      </button>`).join('') +
    `</div>`;
  }

  // ══════════════════════════════════════════
  // DESKTOP SEARCH
  // ══════════════════════════════════════════
  const dInp = document.getElementById('desktopSearchInput');
  const dDd  = document.getElementById('desktopSearchDropdown');
  if (dInp && dDd) {
    let dTimer, dFilter = 'all';

    window._setDesktopFilter = function(f) {
      dFilter = f;
      FILTERS.forEach(x => {
        const chip = document.getElementById('_setDesktopFilter_chip_'+x);
        if (!chip) return;
        chip.style.border      = x===f ? '1px solid var(--teal-500)' : '1px solid var(--line)';
        chip.style.background  = x===f ? 'var(--teal-tint-14)' : 'var(--surface-2)';
        chip.style.color       = x===f ? 'var(--teal-500)' : 'var(--ink-700)';
      });
      renderDesktopResults();
    };

    function renderDesktopResults() {
      const q = dInp.value.trim();
      if (!q) { dDd.style.display = 'none'; return; }
      const { students, courses, batches } = buildResults(q, dFilter);
      const closeExtra = `document.getElementById('desktopSearchInput').value='';document.getElementById('desktopSearchDropdown').style.display='none';`;
      dDd.innerHTML = filterChipsHtml(dFilter, '_setDesktopFilter') + renderHtml(students, courses, batches, closeExtra);
      dDd.style.display = '';
    }

    dInp.addEventListener('input', () => {
      clearTimeout(dTimer);
      dTimer = setTimeout(renderDesktopResults, 180);
    });

    // Close on outside click
    document.addEventListener('click', e => {
      if (!dInp.closest('.topbar-search').contains(e.target) && !dDd.contains(e.target)) {
        dDd.style.display = 'none';
      }
    });

    // Keyboard: Escape closes dropdown
    dInp.addEventListener('keydown', e => {
      if (e.key === 'Escape') { dDd.style.display = 'none'; dInp.blur(); }
    });
  }

  // ══════════════════════════════════════════
  // MOBILE SEARCH
  // ══════════════════════════════════════════
  let mFilter = 'all';
  let mTimer;

  window.openMobileSearch = function() {
    const overlay = document.getElementById('mobileSearchOverlay');
    if (!overlay) return;
    overlay.style.display = 'flex';
    document.body.style.overflow = 'hidden';
    mFilter = 'all';
    // Reset chip visuals to "All"
    ['all','students','courses','batches'].forEach(f => {
      const chip = document.getElementById('_setMobileFilter_chip_'+f);
      if (!chip) return;
      chip.style.border     = f==='all' ? '1px solid var(--teal-500)' : '1px solid var(--line)';
      chip.style.background = f==='all' ? 'var(--teal-tint-14)' : 'var(--surface-2)';
      chip.style.color      = f==='all' ? 'var(--teal-500)' : 'var(--ink-700)';
    });
    setTimeout(() => document.getElementById('mobileSearchInput')?.focus(), 80);
  };

  window.closeMobileSearchModal = function() {
    const overlay = document.getElementById('mobileSearchOverlay');
    if (!overlay) return;
    overlay.style.display = 'none';
    document.body.style.overflow = '';
    const inp = document.getElementById('mobileSearchInput');
    if (inp) inp.value = '';
    const res = document.getElementById('mobileSearchResults');
    if (res) res.innerHTML = '<div style="padding:20px;text-align:center;font-size:13px;color:var(--ink-400,#9AA3B5);">Type to search…</div>';
    mFilter = 'all';
  };

  window._setMobileFilter = function(f) {
    mFilter = f;
    FILTERS.forEach(x => {
      const chip = document.getElementById('_setMobileFilter_chip_'+x);
      if (!chip) return;
      chip.style.border      = x===f ? '1px solid var(--teal-500)' : '1px solid var(--line)';
      chip.style.background  = x===f ? 'var(--teal-tint-14)' : 'var(--surface-2)';
      chip.style.color       = x===f ? 'var(--teal-500)' : 'var(--ink-700)';
    });
    renderMobileResults();
  };

  function renderMobileResults() {
    const res = document.getElementById('mobileSearchResults');
    if (!res) return;
    const q = (document.getElementById('mobileSearchInput')?.value || '').trim();
    if (!q) {
      res.innerHTML = '<div style="padding:20px;text-align:center;font-size:13px;color:var(--ink-400,#9AA3B5);">Type to search…</div>';
      return;
    }
    const { students, courses, batches } = buildResults(q, mFilter);
    res.innerHTML = renderHtml(students, courses, batches, 'closeMobileSearchModal();');
  }

  // Expose so the post-DOM wiring script can call it
  window._runMobileSearch = function(q) {
    const res = document.getElementById('mobileSearchResults');
    if (!res) return;
    if (!q) {
      res.innerHTML = '<div style="padding:20px;text-align:center;font-size:13px;color:var(--ink-400,#9AA3B5);">Type to search…</div>';
      return;
    }
    const { students, courses, batches } = buildResults(q, mFilter);
    res.innerHTML = renderHtml(students, courses, batches, 'closeMobileSearchModal();');
  };

  // Wire up mobile modal events — use once to avoid duplicate listeners
  const closeBtn = document.getElementById('closeMobileSearch');
  if (closeBtn) {
    closeBtn.onclick = function(e) { e.stopPropagation(); closeMobileSearchModal(); };
  }

  const mOverlay = document.getElementById('mobileSearchOverlay');
  if (mOverlay) {
    mOverlay.addEventListener('click', e => {
      if (e.target === mOverlay) closeMobileSearchModal();
    });
  }

  const mInp = document.getElementById('mobileSearchInput');
  if (mInp) {
    mInp.addEventListener('input', function() {
      clearTimeout(mTimer);
      mTimer = setTimeout(renderMobileResults, 180);
    });
  }

})();

// Handle Escape key for mobile search (outside IIFE so it doesn't clash)
document.addEventListener('keydown', function(e) {
  if (e.key === 'Escape') {
    if (document.getElementById('mobileSearchOverlay')?.style.display === 'flex') {
      closeMobileSearchModal();
    }
  }
});

// Close batch popups on outside click
document.addEventListener('click', e => {
  if (!e.target.closest('.batch-popup') && !e.target.closest('button[onclick*="classList.toggle"]')) {
    document.querySelectorAll('.batch-popup.show').forEach(p => p.classList.remove('show'));
  }
});

// ── Batch Breakdown Modal ──
const _todayBreakdown   = <?php echo json_encode($todayBatchBreakdown, 15, 512) ?>;
const _overallBreakdown = <?php echo json_encode($overallBatchBreakdown, 15, 512) ?>;

function openBdModal(type) {
  const overlay = document.getElementById('batchModalOverlay2');
  const eyebrow = document.getElementById('bdModalEyebrow');
  const title   = document.getElementById('bdModalTitle');
  const body    = document.getElementById('bdModalBody');

  if (type === 'today') {
    eyebrow.textContent = 'Today';
    title.textContent   = 'Batch Attendance Today';
    body.innerHTML = _todayBreakdown.map(b => {
      const pct = b.total > 0 ? Math.round(b.present / b.total * 100) : 0;
      const col = pct >= 75 ? 'var(--vivid-green)' : pct >= 50 ? 'var(--vivid-amber)' : 'var(--coral-500)';
      return `<div style="padding:10px 20px;border-bottom:1px solid var(--line);">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:6px;">
          <span style="font-size:13px;font-weight:600;color:var(--ink-900);">${b.batch}</span>
          <div style="display:flex;align-items:center;gap:8px;">
            <span style="font-size:12px;color:var(--ink-500);">${b.present}/${b.total} present</span>
            <span style="font-size:12px;font-weight:800;color:${col};">${pct}%</span>
          </div>
        </div>
        <div style="height:5px;border-radius:3px;background:var(--line);overflow:hidden;">
          <div style="height:100%;width:${pct}%;background:${col};border-radius:3px;"></div>
        </div>
      </div>`;
    }).join('');
  } else {
    eyebrow.textContent = 'All Time';
    title.textContent   = 'Overall Batch Breakdown';
    body.innerHTML = _overallBreakdown.map(b => {
      const col = b.pct >= 75 ? 'var(--vivid-green)' : b.pct >= 50 ? 'var(--vivid-amber)' : 'var(--coral-500)';
      return `<div style="padding:10px 20px;border-bottom:1px solid var(--line);">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:6px;">
          <span style="font-size:13px;font-weight:600;color:var(--ink-900);">${b.batch}</span>
          <span style="font-size:12px;font-weight:800;color:${col};">${b.pct}%</span>
        </div>
        <div style="display:flex;gap:8px;margin-bottom:6px;">
          <span style="padding:2px 8px;border-radius:100px;font-size:11px;font-weight:700;background:var(--teal-tint-14);color:var(--badge-green-text);">${b.present}P</span>
          <span style="padding:2px 8px;border-radius:100px;font-size:11px;font-weight:700;background:var(--amber-tint-16);color:var(--badge-amber-text);">${b.late}L</span>
          <span style="padding:2px 8px;border-radius:100px;font-size:11px;font-weight:700;background:var(--badge-red-bg);color:var(--badge-red-text);">${b.absent}A</span>
          <span style="padding:2px 8px;border-radius:100px;font-size:11px;font-weight:700;background:var(--badge-slate-bg);color:var(--ink-700);">${b.total} classes</span>
        </div>
        <div style="height:5px;border-radius:3px;background:var(--line);overflow:hidden;">
          <div style="height:100%;width:${b.pct}%;background:${col};border-radius:3px;"></div>
        </div>
      </div>`;
    }).join('');
  }

  overlay.style.display = 'flex';
  document.body.style.overflow = 'hidden';
}

function closeBdModal() {
  document.getElementById('batchModalOverlay2').style.display = 'none';
  document.body.style.overflow = '';
}

document.getElementById('batchModalOverlay2')?.addEventListener('click', e => {
  if (e.target === document.getElementById('batchModalOverlay2')) closeBdModal();
});

// Go to profile on avatar click
document.getElementById('topAccountBtn').addEventListener('click', () => switchView('profile'));

// ── Profile photo preview & auto-submit ──
(function() {
  const inp    = document.getElementById('profPhotoInput');
  const avatar = document.getElementById('profAvatar');
  const form   = document.getElementById('profileForm');
  if (!inp || !avatar || !form) return;

  // Show existing photo on load
  <?php if(auth()->user()->photo): ?>
    avatar.innerHTML = `<img src="<?php echo e(asset('storage/' . auth()->user()->photo)); ?>"
      style="width:100%;height:100%;object-fit:contain;border-radius:50%;background:#fff;">`;
  <?php endif; ?>

  inp.addEventListener('change', function() {
    const file = this.files[0];
    if (!file) return;
    // Preview
    const reader = new FileReader();
    reader.onload = e => {
      avatar.innerHTML = `<img src="${e.target.result}"
        style="width:100%;height:100%;object-fit:contain;border-radius:50%;background:#fff;">`;
    };
    reader.readAsDataURL(file);
    // Auto-submit form with photo
    form.submit();
  });
})();

// ── Student Full History Modal ──
const ATT_STUDENT_HIST_URL = '<?php echo e(url("/api/attendance/student")); ?>';
const ATT_STUDENT_EXPORT_URL = '<?php echo e(url("/api/attendance/student/export")); ?>';
let _currentShStudentId = null;

function exportStudentCsv() {
  if (!_currentShStudentId) return;
  const a = document.createElement('a');
  a.href = `${ATT_STUDENT_EXPORT_URL}?student_id=${_currentShStudentId}`;
  a.download = '';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

async function openStudentHistModal(studentDbId, studentName) {
  const overlay  = document.getElementById('shModalOverlay');
  const title    = document.getElementById('shModalTitle');
  const mbody    = document.getElementById('shModalBody');
  const exportBtn = document.getElementById('shExportCsvBtn');
  overlay.classList.add('open');
  document.body.style.overflow = 'hidden';
  _currentShStudentId = studentDbId;
  if (exportBtn) exportBtn.style.display = 'none'; // hide until data loads

  title.textContent = studentName || 'Loading…';
  mbody.innerHTML   = '<div class="hist-empty">Loading…</div>';

  try {
    const res  = await fetch(`${ATT_STUDENT_HIST_URL}?student_id=${studentDbId}`, { headers:{'Accept':'application/json'} });
    const data = await res.json();
    title.textContent = data.name + ' · ' + data.student_code;
    // Show export button now that data is loaded
    if (exportBtn) { exportBtn.style.display = 'inline-flex'; }

    function shortDate(d) { return new Date(d+'T00:00:00').toLocaleDateString('en-GB',{day:'2-digit',month:'short'}); }
    function dayName(d)   { return new Date(d+'T00:00:00').toLocaleDateString('en-GB',{weekday:'short'}); }
    function pctColor(p)  { return p>=75?'var(--vivid-green)':p>=50?'var(--vivid-amber)':'var(--coral-500)'; }

    if (!data.batches || !data.batches.length) {
      mbody.innerHTML = '<div class="hist-empty"><p>No attendance records found.</p></div>';
      return;
    }

    mbody.innerHTML = data.batches.map(b => {
      const t  = b.total;
      const pc = pctColor(t.pct);
      const bar = `<div style="height:5px;border-radius:3px;background:var(--line);overflow:hidden;margin:8px 0 12px;">
        <div style="height:100%;width:${t.pct}%;background:${pc};border-radius:3px;"></div></div>`;

      const chips = b.records.map(r => {
        const lbl = r.status==='present'?'P':r.status==='late'?'L':'A';
        return `<div style="display:flex;flex-direction:column;align-items:center;gap:3px;">
          <span class="att-cell ${r.status}">${lbl}</span>
          <span style="font-size:9.5px;font-weight:600;color:var(--ink-500);white-space:nowrap;">${shortDate(r.date)}</span>
          <span style="font-size:9px;color:var(--ink-300);">${dayName(r.date)}</span>
        </div>`;
      }).join('');

      const isCurrent = b.batch_name === data.current_batch;
      return `<div style="border:1px solid ${isCurrent?'var(--teal-500)':'var(--line)'};border-radius:var(--radius);overflow:hidden;">
        <div style="padding:12px 16px;background:${isCurrent?'var(--teal-tint-10)':'var(--surface-2)'};display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px;border-bottom:1px solid var(--line);">
          <div>
            <span style="font-weight:700;font-size:13.5px;color:var(--ink-900);">${b.batch_name}</span>
            ${isCurrent?'<span style="margin-left:8px;padding:2px 8px;border-radius:100px;font-size:10.5px;font-weight:700;background:var(--teal-tint-14);color:var(--badge-green-text);">Current</span>':''}
          </div>
          <div style="display:flex;gap:6px;align-items:center;flex-wrap:wrap;">
            <span style="padding:3px 9px;border-radius:100px;font-size:11px;font-weight:700;background:var(--teal-tint-14);color:var(--badge-green-text);">${t.present}P</span>
            <span style="padding:3px 9px;border-radius:100px;font-size:11px;font-weight:700;background:var(--amber-tint-16);color:var(--badge-amber-text);">${t.late}L</span>
            <span style="padding:3px 9px;border-radius:100px;font-size:11px;font-weight:700;background:var(--badge-red-bg);color:var(--badge-red-text);">${t.absent}A</span>
            <span style="padding:3px 9px;border-radius:100px;font-size:11px;font-weight:700;background:var(--badge-slate-bg);color:var(--ink-700);">${t.total} Classes</span>
            <span style="font-size:13px;font-weight:800;color:${pc};">${t.pct}%</span>
          </div>
        </div>
        <div style="padding:2px 16px 4px;">${bar}</div>
        <div style="padding:8px 16px 14px;display:grid;grid-template-columns:repeat(auto-fill,minmax(48px,1fr));gap:8px 6px;">
          ${chips || '<span style="font-size:12px;color:var(--ink-300);">No records</span>'}
        </div>
      </div>`;
    }).join('');

  } catch(e) {
    console.error(e);
    mbody.innerHTML = '<div class="hist-empty"><p>Failed to load.</p></div>';
  }
}

document.getElementById('closeShModal').addEventListener('click', () => {
  document.getElementById('shModalOverlay').classList.remove('open');
  document.body.style.overflow = '';
});
document.getElementById('shModalOverlay').addEventListener('click', e => {
  if (e.target === document.getElementById('shModalOverlay')) {
    document.getElementById('shModalOverlay').classList.remove('open');
    document.body.style.overflow = '';
  }
});
// ── Modal helpers ──
function openModal(overlayId) {
  const el = document.getElementById(overlayId);
  if (!el) return;
  el.classList.add('open');
  document.body.style.overflow = 'hidden';
}
function closeModal(overlayId) {
  const el = document.getElementById(overlayId);
  if (!el) return;
  el.classList.remove('open');
  document.body.style.overflow = '';
}

// Close on backdrop click
document.querySelectorAll('.sec-modal-overlay').forEach(overlay => {
  overlay.addEventListener('click', e => {
    if (e.target === overlay) closeModal(overlay.id);
  });
});

// ── Password eye toggle (inside modals) ──
document.querySelectorAll('.pass-eye').forEach(btn => {
  btn.addEventListener('click', () => {
    const input = document.getElementById(btn.dataset.target);
    if (!input) return;
    const show = input.type === 'password';
    input.type = show ? 'text' : 'password';
    btn.innerHTML = show
      ? `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>`
      : `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>`;
  });
});

// ── Client-side password match validation ──
const pmConf = document.getElementById('pm_conf');
const pmNew  = document.getElementById('pm_new');
const pmErr  = document.getElementById('pm_matchErr');
if (pmConf && pmNew && pmErr) {
  function checkMatch() {
    if (pmConf.value && pmNew.value !== pmConf.value) {
      pmErr.style.display = 'block';
    } else {
      pmErr.style.display = 'none';
    }
  }
  pmConf.addEventListener('input', checkMatch);
  pmNew.addEventListener('input', checkMatch);

  document.getElementById('passModalForm').addEventListener('submit', e => {
    if (pmNew.value !== pmConf.value) {
      e.preventDefault();
      pmErr.style.display = 'block';
      pmConf.focus();
    }
  });
}

// ── Auto-open modals on validation error ──
<?php if($errors->has('current_password') || $errors->has('password')): ?>
  openModal('passModalOverlay');
  switchView('profile');
<?php endif; ?>
<?php if($errors->has('current_access_code') || $errors->has('access_code')): ?>
  openModal('codeModalOverlay');
  switchView('profile');
<?php endif; ?>

// Dashboard weekly chart — real data from server
const weeklyTrend = <?php echo json_encode($weeklyTrend, 15, 512) ?>;
const chart = document.getElementById('weekChart');
const maxH  = 120;
if (chart) {
  chart.innerHTML = '';
  weeklyTrend.forEach(d => {
    const col = document.createElement('div');
    col.className = 'week-bar-col';
    const barH = d.total > 0 ? Math.max(8, Math.round(d.pct / 100 * maxH)) : 4;
    const opacity = d.total > 0 ? 1 : 0.3;
    col.innerHTML = `<div class="week-bar" style="height:${barH}px;opacity:${opacity}" title="${d.pct}% (${d.total} records)"></div><span>${d.day}</span>`;
    chart.appendChild(col);
  });
}

// Profile success flash
<?php if(session('profile_updated')): ?>
  const s = document.getElementById('profileSuccess');
  if (s) { s.style.display = 'block'; setTimeout(() => s.style.display = 'none', 3500); }
<?php endif; ?>

// Restore active view after redirect
<?php if(session('active_view')): ?>
  switchView('<?php echo e(session('active_view')); ?>');
<?php endif; ?>
</script>

<!-- Batch Breakdown Modal -->
<div id="batchModalOverlay2" style="display:none;position:fixed;inset:0;z-index:600;background:rgba(11,21,38,.5);backdrop-filter:blur(3px);align-items:center;justify-content:center;padding:20px;">
  <div style="background:var(--surface);border-radius:16px;width:100%;max-width:420px;box-shadow:var(--shadow-lg);overflow:hidden;">
    <div style="display:flex;align-items:center;justify-content:space-between;padding:16px 20px;border-bottom:1px solid var(--line);">
      <div>
        <div style="font-size:10.5px;font-weight:700;letter-spacing:.8px;text-transform:uppercase;color:var(--teal-500);margin-bottom:2px;" id="bdModalEyebrow">Today</div>
        <h3 style="font-family:var(--font-display);font-size:15px;font-weight:700;" id="bdModalTitle">Batch Breakdown</h3>
      </div>
      <button onclick="closeBdModal()" style="background:var(--surface-2);border:1px solid var(--line);border-radius:8px;width:30px;height:30px;display:flex;align-items:center;justify-content:center;cursor:pointer;color:var(--ink-700);">
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg>
      </button>
    </div>
    <div id="bdModalBody" style="padding:8px 0;max-height:60vh;overflow-y:auto;"></div>
  </div>
</div>

<!-- Student Full History Modal -->
<div class="sh-modal-overlay" id="shModalOverlay">
  <div class="sh-modal">
    <div class="sh-modal-head">
      <div>
        <div style="font-size:10.5px;font-weight:700;letter-spacing:.8px;text-transform:uppercase;color:var(--teal-500);margin-bottom:2px;">Full Attendance</div>
        <h3 id="shModalTitle">Student Name</h3>
      </div>
      <div style="display:flex;align-items:center;gap:8px;">
        <button id="shExportCsvBtn" onclick="exportStudentCsv()"
          style="display:none;padding:5px 12px;border-radius:8px;border:1px solid var(--line);background:var(--surface-2);color:var(--ink-700);font-size:12px;font-weight:600;cursor:pointer;font-family:var(--font-body);align-items:center;gap:5px;">
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
          Export CSV
        </button>
        <button class="sh-modal-close" id="closeShModal">
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg>
        </button>
      </div>
    </div>
    <div class="sh-modal-body" id="shModalBody">
      <div class="hist-empty">Loading…</div>
    </div>
  </div>
</div>

<!-- Mobile Search Modal — must be in DOM before JS wiring below -->
<div id="mobileSearchOverlay" style="display:none;position:fixed;inset:0;z-index:500;background:rgba(11,21,38,.55);backdrop-filter:blur(3px);align-items:flex-start;justify-content:center;padding:16px;">
  <div style="background:var(--surface);border-radius:16px;width:100%;max-width:480px;box-shadow:0 16px 40px rgba(11,21,38,.2);overflow:hidden;margin-top:8px;">
    <!-- Search input row -->
    <div style="display:flex;align-items:center;gap:10px;padding:12px 16px;border-bottom:1px solid var(--line);">
      <svg style="width:18px;height:18px;color:var(--ink-500);flex-shrink:0;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
      <input id="mobileSearchInput" type="text" placeholder="Search students, batches, courses…"
        style="flex:1;border:none;outline:none;font-size:15px;font-family:var(--font-body);color:var(--ink-900);background:transparent;">
      <button id="closeMobileSearch" style="background:var(--surface-2);border:none;border-radius:8px;width:28px;height:28px;display:flex;align-items:center;justify-content:center;cursor:pointer;color:var(--ink-500);">
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg>
      </button>
    </div>
    <!-- Filter chips -->
    <div style="display:flex;gap:6px;padding:10px 14px 8px;border-bottom:1px solid var(--line);flex-wrap:wrap;">
      <button id="_setMobileFilter_chip_all"      onclick="_setMobileFilter('all')"      style="padding:4px 11px;border-radius:100px;font-size:11.5px;font-weight:600;cursor:pointer;border:1px solid var(--teal-500);background:var(--teal-tint-14);color:var(--teal-500);transition:all .12s;">All</button>
      <button id="_setMobileFilter_chip_students" onclick="_setMobileFilter('students')" style="padding:4px 11px;border-radius:100px;font-size:11.5px;font-weight:600;cursor:pointer;border:1px solid var(--line);background:var(--surface-2);color:var(--ink-700);transition:all .12s;">Students</button>
      <button id="_setMobileFilter_chip_courses"  onclick="_setMobileFilter('courses')"  style="padding:4px 11px;border-radius:100px;font-size:11.5px;font-weight:600;cursor:pointer;border:1px solid var(--line);background:var(--surface-2);color:var(--ink-700);transition:all .12s;">Courses</button>
      <button id="_setMobileFilter_chip_batches"  onclick="_setMobileFilter('batches')"  style="padding:4px 11px;border-radius:100px;font-size:11.5px;font-weight:600;cursor:pointer;border:1px solid var(--line);background:var(--surface-2);color:var(--ink-700);transition:all .12s;">Batches</button>
    </div>
    <!-- Results -->
    <div id="mobileSearchResults" style="max-height:55vh;overflow-y:auto;padding:0;">
      <div style="padding:20px;text-align:center;font-size:13px;color:var(--ink-400,#9AA3B5);">Type to search…</div>
    </div>
  </div>
</div>

<!-- Mobile search wiring — runs after modal is in DOM -->
<script>
(function() {
  const closeBtn = document.getElementById('closeMobileSearch');
  const mOverlay = document.getElementById('mobileSearchOverlay');
  const mInp     = document.getElementById('mobileSearchInput');
  let mTimer2;

  if (closeBtn) {
    closeBtn.onclick = function(e) { e.stopPropagation(); closeMobileSearchModal(); };
  }
  if (mOverlay) {
    mOverlay.addEventListener('click', function(e) {
      if (e.target === mOverlay) closeMobileSearchModal();
    });
  }
  if (mInp) {
    mInp.addEventListener('input', function() {
      clearTimeout(mTimer2);
      const val = this.value.trim();
      mTimer2 = setTimeout(function() {
        const res = document.getElementById('mobileSearchResults');
        if (!res) return;
        if (!val) {
          res.innerHTML = '<div style="padding:20px;text-align:center;font-size:13px;color:var(--ink-400,#9AA3B5);">Type to search…</div>';
          return;
        }
        // Use the shared search engine exposed on window
        if (typeof window._runMobileSearch === 'function') window._runMobileSearch(val);
      }, 180);
    });
  }
})();
</script>

<!-- Student History Modal wiring — runs after modal is in DOM -->
<script>
(function() {
  var closeBtn = document.getElementById('closeShModal');
  var overlay  = document.getElementById('shModalOverlay');
  function closeShModal() {
    if (overlay) { overlay.classList.remove('open'); }
    document.body.style.overflow = '';
  }
  if (closeBtn) { closeBtn.onclick = function(e) { e.stopPropagation(); closeShModal(); }; }
  if (overlay)  { overlay.addEventListener('click', function(e) { if (e.target === overlay) closeShModal(); }); }
  // Escape key
  document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape' && overlay && overlay.classList.contains('open')) closeShModal();
  });
})();
</script>

<!-- Profile security modal wiring — DOM ready here -->
<script>
(function() {
  // eye toggle helper
  var eyeOpenSvg = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>';
  var eyeOffSvg  = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>';

  function wireEye(btnId, fieldId, valueId) {
    var btn   = document.getElementById(btnId);
    var field = document.getElementById(fieldId);
    var valEl = document.getElementById(valueId);
    if (!btn || !field) return;
    var realVal = valEl ? valEl.dataset.val : '';
    btn.addEventListener('click', function() {
      var shown = btn.dataset.shown === '1';
      if (!shown) {
        field.textContent         = realVal || '(not set)';
        field.style.letterSpacing = 'normal';
        field.style.fontSize      = '14px';
        field.style.color         = 'var(--ink-900)';
        btn.innerHTML             = eyeOffSvg;
        btn.title                 = 'Hide';
        btn.dataset.shown         = '1';
      } else {
        field.textContent         = '••••••••••';
        field.style.letterSpacing = '3px';
        field.style.fontSize      = '15px';
        field.style.color         = 'var(--ink-500)';
        btn.innerHTML             = eyeOpenSvg;
        btn.title                 = 'Show';
        btn.dataset.shown         = '0';
      }
    });
  }
  wireEye('passDisplayEye', 'passDisplayField', 'passValue');
  wireEye('codeDisplayEye', 'codeDisplayField', 'codeValue');

  // modal open/close
  document.getElementById('openPassModal')?.addEventListener('click',   function() { openModal('passModalOverlay'); });
  document.getElementById('closePassModal')?.addEventListener('click',  function() { closeModal('passModalOverlay'); });
  document.getElementById('cancelPassModal')?.addEventListener('click', function() { closeModal('passModalOverlay'); });
  document.getElementById('openCodeModal')?.addEventListener('click',   function() { openModal('codeModalOverlay'); });
  document.getElementById('closeCodeModal')?.addEventListener('click',  function() { closeModal('codeModalOverlay'); });
  document.getElementById('cancelCodeModal')?.addEventListener('click', function() { closeModal('codeModalOverlay'); });

  // backdrop click
  ['passModalOverlay','codeModalOverlay'].forEach(function(id) {
    var el = document.getElementById(id);
    if (el) el.addEventListener('click', function(e) { if (e.target === el) closeModal(id); });
  });
})();
</script>

<!-- Mobile Bottom Nav -->
<nav class="mobile-nav" id="mobileNav">
  <button class="mobile-nav-item" data-view="students" onclick="switchView('students');updateMobileNav('students')">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/></svg>
    Students
  </button>
  <button class="mobile-nav-item" data-view="batches" onclick="switchView('batches');updateMobileNav('batches')">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M3 10h18M8 2v4M16 2v4"/></svg>
    Batches
  </button>
  <button class="mobile-nav-item" data-view="attendance" onclick="switchView('attendance');updateMobileNav('attendance')">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg>
    Attend.
  </button>
  <button class="mobile-nav-item" data-view="reports" onclick="switchView('reports');updateMobileNav('reports')">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3v18h18"/><path d="M18 17V9M13 17V5M8 17v-4"/></svg>
    Reports
  </button>
  <button class="mobile-nav-item" data-view="transfers" onclick="switchView('transfers');updateMobileNav('transfers')">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 1l4 4-4 4"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><path d="M7 23l-4-4 4-4"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg>
    Transfer
  </button>
</nav>

</body>
</html>
<?php /**PATH C:\xampp\htdocs\class_track\resources\views/dashboard.blade.php ENDPATH**/ ?>