<?php
/* ========================================================================
   EDEN LMS — Student Dashboard (2025, Mobile Fix Pack v2)
   - Desktop unchanged; Mobile polished for iOS/Android
   - Mobile: hero mini "Upcoming", per-course Due/Overdue badges
   - Deep "Resume" link (lms_last_seen / lms_progress)
   ===================================================================== */
declare(strict_types=1);
if (session_status() === PHP_SESSION_NONE) session_start();

/* ---------- helpers ---------- */
if (!function_exists('esc')) {
  function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); }
}
function t_exists(mysqli $db, string $t): bool {
  $t = $db->real_escape_string($t);
  $r = $db->query("SHOW TABLES LIKE '$t'");
  $ok = $r && $r->num_rows>0; if ($r) $r->close(); return $ok;
}
function c_exists(mysqli $db, string $t, string $c): bool {
  $t=$db->real_escape_string($t); $c=$db->real_escape_string($c);
  $r=$db->query("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='$t' AND COLUMN_NAME='$c' LIMIT 1");
  $ok=$r&&$r->num_rows>0; if($r)$r->close(); return $ok;
}

/* ---------- DB ---------- */
require_once __DIR__.'/../includes/db.php';
$mysqli = isset($mysqli) && $mysqli instanceof mysqli ? $mysqli
        : (isset($conn) && $conn instanceof mysqli ? $conn : null);
if (!$mysqli) die('DB missing');
@$mysqli->set_charset('utf8mb4');

/* ---------- current student ---------- */
$student_id   = (int)($_SESSION['student_id'] ?? $_SESSION['id'] ?? 0);
$student_name = (string)($_SESSION['student_name'] ?? $_SESSION['name'] ?? 'Student');

/* ---------- schema shortcuts ---------- */
$T_COURSES = 'courses';
$T_BATCHES = 'batches';
$T_ENROLL  = 'enrollments';
$T_ASSESS  = t_exists($mysqli,'lms_assessments') ? 'lms_assessments' : (t_exists($mysqli,'assessments')?'assessments':null);
$T_SUBMIT  = t_exists($mysqli,'lms_submissions') ? 'lms_submissions' : (t_exists($mysqli,'submissions') ? 'submissions' : null);
$T_BMOD    = t_exists($mysqli,'batch_modules') ? 'batch_modules' : null;

/* ---------- Deep link for Resume ---------- */
function get_resume_href(mysqli $db, int $student_id): string {
  if ($student_id <= 0) return "/elms/student/modules.php";
  // 1) lms_last_seen
  if (t_exists($db,'lms_last_seen')) {
    $hasUrl = c_exists($db,'lms_last_seen','last_url');
    $hasMod = c_exists($db,'lms_last_seen','module_id');
    if ($hasUrl || $hasMod) {
      $sql = "SELECT ".($hasUrl?'last_url':'module_id')." AS v, updated_at
              FROM lms_last_seen WHERE student_id={$student_id}
              ORDER BY updated_at DESC LIMIT 1";
      if ($r=$db->query($sql)) {
        if ($row=$r->fetch_assoc()) {
          $v = (string)($row['v'] ?? '');
          if ($hasUrl && $v) { $r->close(); return $v; }
          if ($hasMod && $v) { $r->close(); return "/elms/student/learn/index.php?module_id=".(int)$v; }
        }
        $r->close();
      }
    }
  }
  // 2) lms_progress
  if (t_exists($db,'lms_progress') && c_exists($db,'lms_progress','student_id') && c_exists($db,'lms_progress','module_id')) {
    $sql="SELECT module_id FROM lms_progress WHERE student_id={$student_id} ORDER BY updated_at DESC, id DESC LIMIT 1";
    if ($r=$db->query($sql)) {
      if ($row=$r->fetch_row()) { $r->close(); return "/elms/student/learn/index.php?module_id=".(int)$row[0]; }
      $r->close();
    }
  }
  return "/elms/student/modules.php";
}
$resume_href = get_resume_href($mysqli,$student_id);

/* ---------- batches for this student ---------- */
$batchIds = [];
if ($student_id>0 && t_exists($mysqli,$T_ENROLL) && c_exists($mysqli,$T_ENROLL,'batch_id') && c_exists($mysqli,$T_ENROLL,'student_id')) {
  if ($r=$mysqli->query("SELECT DISTINCT batch_id FROM {$T_ENROLL} WHERE student_id={$student_id}")) {
    while($row=$r->fetch_row()) $batchIds[(int)$row[0]]=1;
    $r->close();
  }
}
$batchIdsList = $batchIds ? implode(',',array_keys($batchIds)) : '0';

/* ---------- preferred course list ---------- */
$courses = [];
if ($T_BMOD && $batchIds) {
  $q = "SELECT DISTINCT c.id, COALESCE(c.course_name, CONCAT('Course ',c.id)) AS label
        FROM {$T_BMOD} bm
        JOIN {$T_COURSES} c ON c.id=bm.source_course_id
        WHERE bm.batch_id IN ($batchIdsList)
        ORDER BY label";
  if ($r=$mysqli->query($q)) { while($row=$r->fetch_assoc()) $courses[]=['id'=>(int)$row['id'],'label'=>$row['label']]; $r->close(); }
}
if (!$courses && $student_id>0) {
  $q="SELECT DISTINCT c.id, COALESCE(c.course_name, CONCAT('Course ',c.id)) AS label
      FROM {$T_ENROLL} e
      JOIN {$T_BATCHES} b ON b.id=e.batch_id
      JOIN {$T_COURSES} c ON c.id=b.course_id
      WHERE e.student_id={$student_id}
      ORDER BY label";
  if ($r=$mysqli->query($q)) { while($row=$r->fetch_assoc()) $courses[]=['id'=>(int)$row['id'],'label'=>$row['label']]; $r->close(); }
}
$course_id = (int)($_GET['course'] ?? ($courses[0]['id'] ?? 0));

/* ---------- modules count for selected course ---------- */
$modulesInCourse = 0;
if ($T_BMOD && $course_id>0 && $batchIds) {
  $q="SELECT COUNT(DISTINCT bm.course_module_id)
      FROM {$T_BMOD} bm
      WHERE bm.batch_id IN ($batchIdsList) AND bm.source_course_id={$course_id}";
  if ($r=$mysqli->query($q)) { $modulesInCourse=(int)($r->fetch_row()[0]??0); $r->close(); }
}

/* ---------- assessments + submissions ---------- */
$assessments=[]; $submitted_ids=[];
if ($T_ASSESS) {
  $sel = "id, title, course_id, due_at";
  if ($r=$mysqli->query("SELECT $sel FROM {$T_ASSESS}")) {
    while($row=$r->fetch_assoc()){
      $assessments[]=[
        'id'=>(int)$row['id'],
        'title'=>(string)($row['title'] ?: 'Assessment #'.$row['id']),
        'course_id'=>(int)($row['course_id'] ?? 0),
        'due_at'=>$row['due_at']?:null
      ];
    }
    $r->close();
  }
}
if ($T_SUBMIT) {
  if ($r=$mysqli->query("SELECT assessment_id FROM {$T_SUBMIT} WHERE student_id={$student_id}")) {
    while($row=$r->fetch_row()) $submitted_ids[(int)$row[0]]=true; $r->close();
  }
}

/* ---------- KPI + per-course badges ---------- */
$now=time(); $week=7*86400; $LOOKAHEAD=30*86400;
$activeCourses  = count($courses);
$enrolledBatches= count($batchIds);
$totalAssess = 0; $due7=0; $overdue=0; $submitted=0; $completionPct=0;
$upcoming=[]; $calendar=[];
$per_course = [];
foreach($courses as $c){ $per_course[$c['id']] = ['label'=>$c['label'],'t'=>0,'s'=>0,'due'=>0,'overdue'=>0]; }

foreach($assessments as $a){
  $aid=(int)$a['id']; $cid=(int)($a['course_id'] ?? 0);
  $dueTs=!empty($a['due_at'])?strtotime($a['due_at']):null;
  $isSub=!empty($submitted_ids[$aid]);

  if ($course_id==0 || ($a['course_id'] && $a['course_id']==$course_id)) {
    $totalAssess++; if ($isSub) $submitted++;
    if ($dueTs){
      if ($dueTs < $now && !$isSub) $overdue++;
      if ($dueTs >= $now && $dueTs <= $now+$week && !$isSub) $due7++;
      if ($dueTs >= $now-86400 && $dueTs <= $now+$LOOKAHEAD) {
        $calendar[]=['date'=>date('Y-m-d',$dueTs),'time'=>date('H:i',$dueTs),'title'=>$a['title'],'href'=>'/elms/student/assessments/index.php','kind'=>$isSub?'done':'assessment'];
      }
      if (!$isSub && $dueTs >= $now && $dueTs <= $now+$LOOKAHEAD) {
        $upcoming[]=['title'=>$a['title'],'date'=>date('Y-m-d',$dueTs),'time'=>date('H:i',$dueTs),'cid'=>$cid];
      }
    }
  }
  if ($cid && isset($per_course[$cid])) {
    $per_course[$cid]['t']++; if ($isSub) $per_course[$cid]['s']++;
    if ($dueTs){
      if ($dueTs < $now && !$isSub) $per_course[$cid]['overdue']++;
      if ($dueTs >= $now && $dueTs <= $now+$week && !$isSub) $per_course[$cid]['due']++;
    }
  }
}
$completionPct = $totalAssess ? (int)round(($submitted/$totalAssess)*100) : 0;

/* next upcoming (for mobile hero) */
usort($upcoming, fn($a,$b)=>strcmp(($a['date'].$a['time']), ($b['date'].$b['time'])));
$next_up = $upcoming[0] ?? null;

$cal_json = json_encode(['events'=>$calendar], JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
$upc_json = json_encode($upcoming, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);

/* ---------- page shell ---------- */
$PAGE_TITLE='Dashboard';
$ACTIVE_MENU='dashboard';
require __DIR__.'/studentlayout_top.php';
?>
<style>
  :root{
    --accent:#0B3C89; --accent2:#2563EB;
    --bg:#eef3ff; --panel:#fff; --ink:#0b1220; --muted:#64748b; --line:rgba(2,8,23,.12);
    --k1:#eef2ff; --k2:#ecfeff; --k3:#f1fff3; --k4:#fff7ed; --k5:#ffeef3; --k6:#edf7ff;
    --ok:#16a34a; --warn:#f59e0b; --bad:#ef4444; --info:#2563eb;
    --shadow:0 14px 34px rgba(2,8,23,.06);
    --r-lg:20px; --r-md:14px; --r-sm:10px;
  }
  .theme-dark{
    --bg:#0b1220; --panel:#0f172a; --ink:#e6e9f2; --muted:#9aa4b2; --line:rgba(255,255,255,.08);
    --k1:#10204d; --k2:#0d2a3a; --k3:#0f2a22; --k4:#2a1d0f; --k5:#311427; --k6:#0f2236;
    --shadow:0 14px 38px rgba(0,0,0,.5);
  }
  /* stretch main container to 100% width */
  body .container, body .container-fluid, body .content, body .content-wrapper,
  body main, body .page-content, body .page-wrapper, body .app-content {
    max-width:none !important; width:100% !important; padding-left:18px !important; padding-right:18px !important;
  }
  body{ background:linear-gradient(180deg,var(--bg) 0,#eaf1ff 1200px) fixed; }

  .dash{ font-family:Inter, ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Noto Sans, Arial, Helvetica Neue, sans-serif; color:var(--ink) }
  .muted{ color:var(--muted) }

  .hero{
    background:linear-gradient(90deg,var(--accent),var(--accent2)); color:#fff;
    border-radius:var(--r-lg); padding:18px 20px; display:flex; gap:12px; align-items:center; justify-content:space-between; box-shadow:var(--shadow); margin-top:8px
  }
  .hero h1{ margin:0; font-weight:900; font-size:20px }
  .hero .right{ display:flex; gap:8px; align-items:center }
  .hero .mini-up{ display:none; font-size:12px; background:rgba(255,255,255,.12); padding:8px 10px; border-radius:999px }
  @media (max-width:960px){
    .hero{ flex-direction:column; align-items:flex-start; gap:10px; padding:16px }
    .hero h1{ font-size:clamp(16px, 4vw, 20px) }
    .hero .right{ width:100%; justify-content:space-between; gap:8px; flex-wrap:wrap }
    .hero .mini-up{ display:inline-flex; gap:8px; align-items:center }
  }

  .pill{ border:1px solid var(--line); background:var(--panel); color:var(--ink); border-radius:999px; padding:8px 12px; display:inline-flex; align-items:center; gap:8px; min-width:0 }
  .select{ border:0; outline:0; background:transparent; color:inherit; font-size:16px; min-width:0; max-width:100%; white-space:nowrap; text-overflow:ellipsis }

  .grid{ display:grid; gap:14px }
  .kpis{ grid-template-columns: repeat(6,minmax(0,1fr)); margin-top:14px }
  @media (max-width:1400px){ .kpis{ grid-template-columns: repeat(3,minmax(0,1fr)); } }
  @media (max-width:960px){ .kpis{ grid-template-columns: repeat(2,minmax(0,1fr)); } }
  .kpi{ background:var(--panel); border:1px solid var(--line); border-radius:var(--r-lg); display:flex; gap:12px; align-items:center; padding:16px; box-shadow:var(--shadow); min-height:72px }
  .kpi i{ width:40px; height:40px; border-radius:12px; display:grid; place-items:center; font-style:normal; font-size:18px }
  .kpi .t{ color:var(--muted); font-weight:800; font-size:12px }
  .kpi .v{ font-weight:900; font-size:22px }

  .btn{ background:var(--panel); border:1px solid var(--line); color:var(--ink); border-radius:12px; padding:10px 14px; cursor:pointer; text-decoration:none; display:inline-flex; align-items:center; justify-content:center }
  .btn-primary{ background:linear-gradient(90deg,var(--accent),var(--accent2)); color:#fff; border-color:transparent }

  .quick-row{ display:flex; gap:12px; margin:14px 0; flex-wrap:wrap }
  @media (max-width:960px){
    .quick-row{ display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:10px }
    .btn{ width:100%; padding:12px 10px; font-weight:600 }
  }

  .row{ display:grid; gap:14px; grid-template-columns: 1fr 1fr; }
  @media (max-width:1100px){ .row{ grid-template-columns: 1fr; } }
  .card{ background:var(--panel); border:1px solid var(--line); border-radius:16px; box-shadow:var(--shadow) }
  .card-h{ padding:12px 14px; border-bottom:1px solid var(--line); display:flex; align-items:center; justify-content:space-between; gap:10px }
  .card-c{ padding:14px }

  .courses-grid{ display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:12px; min-width:0; max-width:100% }
  @media (max-width:960px){ .courses-grid{ grid-template-columns:1fr; } }
  .course{ border:1px solid var(--line); border-radius:14px; padding:12px 14px; display:flex; flex-direction:column; gap:8px }
  .course .badges{ display:flex; gap:6px; flex-wrap:wrap }
  .badge{ display:inline-block; font-size:.78rem; padding:4px 8px; border-radius:999px; border:1px solid var(--line) }
  .badge.due{ background:#fff3e6; color:#7a2e0e }
  .badge.over{ background:#ffe6e6; color:#7f1d1d }
  .progress{ height:8px; background:rgba(2,8,23,.1); border-radius:999px; overflow:hidden }
  .progress>i{ display:block; height:100%; background:linear-gradient(90deg,var(--accent),var(--accent2)); width:0% }

  /* Calendar */
  .cal{ padding:12px }
  .cal-grid{ display:grid; grid-template-columns: repeat(7,1fr); gap:6px; min-width:0; max-width:100% }
  .dow{ text-align:center; font-size:12px; color:var(--muted) }
  .day{ min-height:60px; border:1px solid var(--line); background:var(--panel); border-radius:12px; padding:6px; display:flex; flex-direction:column; gap:4px }
  .day.muted{ opacity:.45 }
  .d{ font-weight:800; font-size:12px }
  .dots{ display:flex; gap:4px; flex-wrap:wrap }
  .dot{ width:8px; height:8px; border-radius:999px; border:1px solid rgba(0,0,0,.08) }
  .dot.assess{ background:var(--bad) } .dot.done{ background:var(--ok) }

  /* Mobile-only: collapse calendar + safe area bottom */
  .cal-collapse-toggle{ display:none }
  @media (max-width:960px){
    .cal-collapse-toggle{ display:flex; width:100%; justify-content:space-between; align-items:center; padding:10px 14px; }
    .cal-collapsed .cal{ display:none }
    .mobile-bottom-nav{
      position:sticky; bottom:0; left:0; right:0; background:var(--panel);
      border-top:1px solid var(--line); display:grid; grid-template-columns:repeat(4,1fr); gap:0; z-index:50;
      padding-bottom: env(safe-area-inset-bottom);
    }
    .mobile-bottom-nav a{ padding:12px 6px; text-align:center; text-decoration:none; color:var(--ink); font-size:13px }
    .mobile-bottom-nav a strong{ display:block; font-size:12px }
  }

  /* ===== Mobile/iOS hardening ===== */
  html, body{ width:100%; max-width:100%; overflow-x:hidden; -webkit-text-size-adjust:100% }
  .cal-grid, .kpis, .courses-grid, .row{ min-width:0; max-width:100% }
  select, input, textarea { font-size:16px; } /* prevent iOS zoom */

  /* ===== MOBILE FIX PACK v2 (≤430px = super compact) ===== */
  @media (max-width:430px){
    .hero{ padding:14px 16px; border-radius:14px; }
    .hero .right{ flex-wrap:wrap; gap:8px; width:100%; }
    .hero .pill{ width:100%; min-width:0; overflow:hidden; }
    .hero .pill .select{ width:100%; min-width:0; font-size:16px; line-height:1.2; }

    .kpis{ grid-template-columns: 1fr !important; gap:10px; }
    .kpi{ min-height:64px; padding:12px; border-radius:12px; }
    .kpi i{ width:34px; height:34px; font-size:16px; border-radius:10px; }
    .kpi .v{ font-size:20px; }
    .kpi .t{ font-size:11px; }

    .quick-row{ grid-template-columns: 1fr !important; gap:10px; }
    .quick-row .btn{ width:100%; padding:14px 12px; border-radius:14px; }

    .courses-grid{ grid-template-columns: 1fr !important; gap:10px; }
    .course{ padding:12px; border-radius:12px; }
    .progress{ height:6px; }

    .cal-grid{ gap:4px; }
    .day{ min-height:48px; padding:6px; border-radius:10px; }
    .d{ font-size:11px; }
    .dot{ width:7px; height:7px; }

    .card{ border-radius:12px; }
    .card-h{ padding:10px 12px; }
    .card-c{ padding:12px; }

    .mobile-bottom-nav a{ padding:12px 6px; }
    body{ background:linear-gradient(180deg,var(--bg) 0,#eaf1ff 700px) fixed; }
  }
</style>

<div class="dash">
  <!-- HERO -->
  <div class="hero">
    <div>
      <h1>Welcome back, <?= esc($student_name) ?>!</h1>
      <div class="muted" style="font-size:12px">Resume your learning journey</div>

      <?php if ($next_up): ?>
        <!-- Mobile-only mini Upcoming -->
        <div class="mini-up" title="Next due within 30 days">
          ⏰ <strong><?= esc($next_up['title']) ?></strong>
          <span style="opacity:.9">· <?= esc($next_up['date']) ?> <?= esc($next_up['time']) ?></span>
          <a href="/elms/student/assessments/index.php" class="pill" style="margin-left:6px; padding:4px 10px">Open</a>
        </div>
      <?php endif; ?>
    </div>

    <div class="right" style="width:100%">
      <?php if ($courses): ?>
      <!-- Safe, no-overflow form -->
      <form method="get" style="display:flex; gap:8px; align-items:center; width:100%" aria-label="Preferred course">
        <span class="pill" style="width:100%; min-width:0; overflow:hidden">
          <span class="muted" style="font-size:12px; flex:0 0 auto">Course</span>
          <select name="course" class="select" style="flex:1 1 auto; min-width:0; max-width:100%" onchange="this.form.submit()">
            <?php foreach($courses as $c): ?>
              <option value="<?= (int)$c['id'] ?>" <?= ((int)$c['id']===$course_id)?'selected':'' ?>>
                <?= esc($c['label']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </span>
      </form>
      <?php endif; ?>
      <div class="pill" id="themeBtn" style="cursor:pointer; flex:0 0 auto">🌓 Theme</div>
    </div>
  </div>

  <!-- KPIs -->
  <div class="grid kpis" aria-label="Key stats">
    <div class="kpi kpi-1"><i>📚</i><div><div class="t">Active Courses</div><div class="v"><?= (int)$activeCourses ?></div></div></div>
    <div class="kpi kpi-2"><i>🏷️</i><div><div class="t">Enrolled Batches</div><div class="v"><?= (int)$enrolledBatches ?></div></div></div>
    <div class="kpi kpi-3"><i>🗂️</i><div><div class="t">Total Assessments</div><div class="v"><?= (int)$totalAssess ?></div></div></div>
    <div class="kpi kpi-4"><i>⏳</i><div><div class="t">Due in 7 days</div><div class="v"><?= (int)$due7 ?></div></div></div>
    <div class="kpi kpi-5"><i>⚠️</i><div><div class="t">Overdue</div><div class="v"><?= (int)$overdue ?></div></div></div>
    <div class="kpi kpi-6"><i>✅</i><div><div class="t">Submitted · Completion</div><div class="v"><?= (int)$submitted ?> · <?= (int)$completionPct ?>%</div></div></div>
  </div>

  <!-- Quick actions -->
  <div class="quick-row" role="navigation" aria-label="Quick actions">
    <a class="btn btn-primary" href="<?= esc($resume_href) ?>">▶ Resume learning</a>
    <a class="btn" href="/elms/student/assessments/index.php">Assessments</a>
    <a class="btn" href="/elms/student/results.php">My Results</a>
    <a class="btn" href="/elms/student/profile.php">Profile</a>
  </div>

  <!-- Courses + Upcoming -->
  <div class="row">
    <div class="card">
      <div class="card-h"><b>My Courses</b><span class="muted">Progress + Due status</span></div>
      <div class="card-c">
        <?php if (!$courses): ?>
          <div class="muted">No courses found.</div>
        <?php else: ?>
          <div class="courses-grid">
            <?php foreach($per_course as $cid=>$st):
              $pct = $st['t'] ? (int)round(($st['s']/$st['t'])*100) : 0; ?>
              <div class="course">
                <div style="display:flex; align-items:center; justify-content:space-between; gap:8px">
                  <div style="font-weight:800; min-width:0; overflow:hidden; text-overflow:ellipsis"><?= esc($st['label']) ?></div>
                  <div class="muted"><?= $pct ?>%</div>
                </div>
                <div class="progress" aria-label="progress bar"><i style="width:<?= $pct ?>%"></i></div>
                <div class="badges">
                  <?php if ($st['due']>0): ?><span class="badge due">Due: <?= (int)$st['due'] ?></span><?php endif; ?>
                  <?php if ($st['overdue']>0): ?><span class="badge over">Overdue: <?= (int)$st['overdue'] ?></span><?php endif; ?>
                  <?php if ($st['due']==0 && $st['overdue']==0): ?><span class="badge" style="background:#eef8ff">All clear</span><?php endif; ?>
                </div>
                <small class="muted"><?= (int)$st['s'] ?> submitted · <?= (int)$st['t'] ?> total</small>
              </div>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>
    </div>

    <div class="card">
      <div class="card-h">
        <b>Upcoming (next 30 days)</b>
        <span class="muted">Selected course · Modules in course: <?= (int)$modulesInCourse ?></span>
      </div>
      <div class="card-c" id="upcomingBox"></div>
    </div>
  </div>

  <!-- Calendar (collapsible on mobile) -->
  <div class="card cal-collapsed" id="calendarCard" style="margin-top:14px">
    <div class="card-h cal-collapse-toggle">
      <strong>Calendar</strong>
      <button class="btn" id="calToggle">Show</button>
    </div>

    <div class="card-h desktop-only" style="display:flex; gap:8px; align-items:center">
      <strong id="calTitle">Calendar</strong>
      <div style="display:flex; gap:8px; margin-left:auto">
        <button class="btn" id="calPrev">◀</button>
        <button class="btn" id="calToday">Today</button>
        <button class="btn" id="calNext">▶</button>
      </div>
    </div>

    <div class="card-c cal">
      <div class="muted" style="font-size:12px;margin-bottom:6px">
        • <span style="color:var(--bad)">red</span> = due ·
        <span style="color:var(--ok)">green</span> = submitted
      </div>
      <div class="cal-grid" id="calGrid">
        <?php foreach(['Mon','Tue','Wed','Thu','Fri','Sat','Sun'] as $d): ?>
          <div class="dow"><?= $d ?></div>
        <?php endforeach; ?>
      </div>
      <div id="dayPanel" style="display:none; margin-top:10px">
        <div style="font-weight:800; margin-bottom:6px">Selected: <span id="selDate"></span></div>
        <ul id="selList" style="list-style:none; padding:0; margin:0"></ul>
      </div>

      <!-- Mobile sticky nav -->
      <div class="mobile-bottom-nav">
        <a href="/elms/student/modules.php">📘<strong>Learn</strong></a>
        <a href="/elms/student/assessments/index.php">📝<strong>Assess</strong></a>
        <a href="/elms/student/results.php">✅<strong>Results</strong></a>
        <a href="/elms/student/profile.php">👤<strong>Profile</strong></a>
      </div>
    </div>
  </div>
</div>

<script id="cal-data" type="application/json"><?= $cal_json ?></script>
<script id="upc-data" type="application/json"><?= $upc_json ?></script>
<script>
(function(){
  // Theme toggle
  const key='eden_theme';
  const root=document.documentElement;
  const apply=(v)=>{ if(v==='dark'){ root.classList.add('theme-dark'); } else { root.classList.remove('theme-dark'); } };
  apply(localStorage.getItem(key)||'');
  document.getElementById('themeBtn')?.addEventListener('click',()=>{
    const dark=root.classList.contains('theme-dark');
    localStorage.setItem(key, dark?'':'dark');
    apply(dark?'light':'dark');
  });

  // Mobile calendar collapse
  const calendarCard=document.getElementById('calendarCard');
  const calToggle=document.getElementById('calToggle');
  function isMobile(){ return window.matchMedia('(max-width: 960px)').matches; }
  function syncCalHeader(){
    const hdr = calendarCard.querySelector('.desktop-only');
    if (hdr) hdr.style.display = isMobile() ? 'none' : 'flex';
  }
  calToggle?.addEventListener('click',()=>{
    calendarCard.classList.toggle('cal-collapsed');
    calToggle.textContent = calendarCard.classList.contains('cal-collapsed') ? 'Show' : 'Hide';
  });
  window.addEventListener('resize', syncCalHeader); syncCalHeader();

  // Upcoming list
  const upc=JSON.parse(document.getElementById('upc-data').textContent||'[]');
  const box=document.getElementById('upcomingBox');
  if(box){
    if(!upc.length){ box.innerHTML='<div class="muted">Nothing due in the next 30 days.</div>'; }
    else{
      upc.sort((a,b)=>(a.date+a.time).localeCompare(b.date+b.time));
      box.innerHTML='';
      upc.slice(0,12).forEach(ev=>{
        const el=document.createElement('div');
        el.className='up-item';
        el.style.cssText='padding:10px;border:1px dashed var(--line);border-radius:12px;display:flex;justify-content:space-between;align-items:center;gap:10px;margin-bottom:10px';
        el.innerHTML=`
          <div style="display:flex;gap:10px;align-items:center">
            <span class="badge" style="background:#fff3e6;color:#7a2e0e">Due</span>
            <div>
              <div style="font-weight:800">${ev.title||'Assessment'}</div>
              <div class="muted" style="font-size:12px">${ev.date} · ${ev.time}</div>
            </div>
          </div>
          <a class="btn" href="/elms/student/assessments/index.php">Open</a>
        `;
        box.appendChild(el);
      });
    }
  }

  // Calendar
  const payload=JSON.parse(document.getElementById('cal-data').textContent||'{"events":[]}');
  const events=Array.isArray(payload.events)?payload.events:[];
  const calGrid=document.getElementById('calGrid');
  const calTitle=document.getElementById('calTitle');
  const panel=document.getElementById('dayPanel');
  const selDate=document.getElementById('selDate');
  const selList=document.getElementById('selList');
  const byDate={}; events.forEach(e=>{ const d=(e.date||'').slice(0,10); if(!d) return; (byDate[d] ||= []).push(e); });

  let cursor=new Date();
  const ymd=d=>d.toISOString().slice(0,10);
  const label=d=>d.toLocaleString(undefined,{month:'long',year:'numeric'});

  function render(){
    while(calGrid.children.length>7) calGrid.removeChild(calGrid.lastChild);
    const y=cursor.getFullYear(), m=cursor.getMonth();
    if (calTitle) calTitle.textContent="Calendar — "+label(cursor);
    const first=new Date(y,m,1), start=new Date(first);
    const shift=(first.getDay()+6)%7; start.setDate(first.getDate()-shift);
    for(let i=0;i<42;i++){
      const d=new Date(start); d.setDate(start.getDate()+i); const key=ymd(d);
      const cell=document.createElement('div');
      cell.className='day'+(d.getMonth()!==m?' muted':'');
      cell.innerHTML='<div class="d">'+d.getDate()+'</div><div class="dots"></div>';
      const dots=cell.querySelector('.dots');
      const list=byDate[key]||[];
      if(list.length){
        list.forEach(ev=>{ const dot=document.createElement('span'); dot.className='dot '+(ev.kind==='done'?'done':'assess'); dots.appendChild(dot); });
        cell.style.cursor='pointer'; cell.addEventListener('click',()=>openDay(key));
      } else {
        cell.addEventListener('click',()=>{ panel.style.display='none'; selList.innerHTML=''; selDate.textContent='';});
      }
      calGrid.appendChild(cell);
    }
  }
  function openDay(key){
    selDate.textContent=key; selList.innerHTML='';
    (byDate[key]||[]).forEach(ev=>{
      const li=document.createElement('li');
      li.style.cssText='background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:10px;margin:6px 0;display:flex;gap:10px;cursor:pointer;';
      const ico=document.createElement('div'); ico.textContent=ev.kind==='done'?'✅':'📘';
      const box=document.createElement('div'); const t=document.createElement('div'); t.style.fontWeight='800'; t.textContent=ev.title||'Assessment';
      const s=document.createElement('div'); s.className='muted'; s.style.fontSize='12px'; s.textContent=ev.time||'';
      box.appendChild(t); box.appendChild(s); li.appendChild(ico); li.appendChild(box);
      li.addEventListener('click',()=>{ if(ev.href) location.href=ev.href; }); selList.appendChild(li);
    });
    panel.style.display='block';
  }
  document.getElementById('calPrev')?.addEventListener('click',()=>{ cursor.setMonth(cursor.getMonth()-1); render(); });
  document.getElementById('calNext')?.addEventListener('click',()=>{ cursor.setMonth(cursor.getMonth()+1); render(); });
  document.getElementById('calToday')?.addEventListener('click',()=>{ cursor=new Date(); render(); const k=ymd(new Date()); if(byDate[k]) openDay(k); });
  render();

  /* ===== MOBILE FIX PACK v2 JS ===== */
  const sel = document.querySelector('.hero .pill .select');
  const clamp = () => { if (sel) sel.style.maxWidth = (document.documentElement.clientWidth - 64) + 'px'; };
  clamp(); window.addEventListener('resize', clamp);

  document.documentElement.style.overflowX = 'hidden';
  document.body.style.overflowX = 'hidden';

  const fixOverflow = () => {
    const w = document.documentElement.clientWidth;
    Array.from(document.body.children).forEach(el => {
      if (el.scrollWidth > w + 1) el.style.maxWidth = '100%';
    });
  };
  fixOverflow(); window.addEventListener('resize', fixOverflow);
})();
</script>

<?php require __DIR__.'/studentlayout_bottom.php'; ?>
