<?php
require_once 'includes/config.php';
requireLogin();
$uid = $_SESSION['user_id'];
// Add lesson column if missing
try { $pdo->exec("ALTER TABLE past_papers ADD COLUMN lesson VARCHAR(120) DEFAULT NULL"); } catch(PDOException $e){}

// ── AJAX ──────────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    $action = $_POST['action'] ?? '';

    if ($action === 'add_bulk') {
        $subId  = (int)($_POST['subject_id'] ?? 0);
        $lesson = sanitize($_POST['lesson'] ?? '');
        $fromY  = (int)($_POST['from_year'] ?? 0);
        $toY    = (int)($_POST['to_year'] ?? 0);
        $papers = $_POST['papers'] ?? [1];
        if (!$subId || !$fromY || !$toY) jsonResponse(['success'=>false,'message'=>'Subject and year range required.']);
        if ($fromY > $toY) jsonResponse(['success'=>false,'message'=>'From year must be ≤ To year.']);
        $added = 0; $skipped = 0;
        $lessonVal = $lesson ?: null;
        for ($y = $fromY; $y <= $toY; $y++) {
            foreach ((array)$papers as $pno) {
                $pno = (int)$pno;
                $chk = $pdo->prepare("SELECT id FROM past_papers WHERE user_id=? AND subject_id=? AND year=? AND paper_no=?");
                $chk->execute([$uid,$subId,$y,$pno]);
                if ($chk->fetch()) { $skipped++; continue; }
                $pdo->prepare("INSERT INTO past_papers (user_id,subject_id,year,paper_no,lesson) VALUES (?,?,?,?,?)")
                    ->execute([$uid,$subId,$y,$pno,$lessonVal]);
                $added++;
            }
        }
        jsonResponse(['success'=>true,'message'=>"Added $added paper".($added!=1?'s':'').($skipped?" ($skipped skipped)":''),'added'=>$added]);
    }

    if ($action === 'add_single') {
        $subId  = (int)($_POST['subject_id'] ?? 0);
        $year   = (int)($_POST['year'] ?? 0);
        $pno    = (int)($_POST['paper_no'] ?? 1);
        $lesson = sanitize($_POST['lesson'] ?? '');
        if (!$subId || !$year) jsonResponse(['success'=>false,'message'=>'Subject and year required.']);
        $chk = $pdo->prepare("SELECT id FROM past_papers WHERE user_id=? AND subject_id=? AND year=? AND paper_no=?");
        $chk->execute([$uid,$subId,$year,$pno]);
        if ($chk->fetch()) jsonResponse(['success'=>false,'message'=>'This paper already exists.']);
        $pdo->prepare("INSERT INTO past_papers (user_id,subject_id,year,paper_no,lesson) VALUES (?,?,?,?,?)")
            ->execute([$uid,$subId,$year,$pno,$lesson?:null]);
        jsonResponse(['success'=>true,'message'=>'Paper added!','id'=>$pdo->lastInsertId()]);
    }

    if ($action === 'toggle') {
        $id   = (int)($_POST['id'] ?? 0);
        $done = (int)($_POST['done'] ?? 0);
        $pdo->prepare("UPDATE past_papers SET done=?, done_date=? WHERE id=? AND user_id=?")
            ->execute([$done, $done ? date('Y-m-d') : null, $id, $uid]);
        jsonResponse(['success'=>true]);
    }

    if ($action === 'save_score') {
        $id    = (int)($_POST['id'] ?? 0);
        $scoreRaw = trim($_POST['score'] ?? '');
        $totalRaw = trim($_POST['total'] ?? '');
        $score = ($scoreRaw !== '') ? (float)$scoreRaw : null;
        $total = ($totalRaw !== '') ? (float)$totalRaw : 100;
        $notes = sanitize($_POST['notes'] ?? '');
        if (!$id) jsonResponse(["success"=>false,"message"=>"Invalid paper ID."]);
        $pdo->prepare("UPDATE past_papers SET score=?,total_marks=?,notes=?,done=1,done_date=IFNULL(done_date,CURDATE()) WHERE id=? AND user_id=?")
            ->execute([$score,$total,$notes,$id,$uid]);
        $pct = ($score !== null && $total > 0) ? round(($score/$total)*100,1) : null;
        jsonResponse(["success"=>true,"message"=>"Score saved!","pct"=>$pct]);
    }

    if ($action === 'delete_one') {
        $pdo->prepare("DELETE FROM past_papers WHERE id=? AND user_id=?")->execute([(int)$_POST['id'],$uid]);
        jsonResponse(['success'=>true]);
    }

    if ($action === 'delete_subject') {
        $subId = (int)($_POST['subject_id'] ?? 0);
        $pdo->prepare("DELETE FROM past_papers WHERE user_id=? AND subject_id=?")->execute([$uid,$subId]);
        jsonResponse(['success'=>true]);
    }

    if ($action === 'delete_year') {
        $subId = (int)($_POST['subject_id'] ?? 0);
        $year  = (int)($_POST['year'] ?? 0);
        $pdo->prepare("DELETE FROM past_papers WHERE user_id=? AND subject_id=? AND year=?")->execute([$uid,$subId,$year]);
        jsonResponse(['success'=>true]);
    }
}

// ── DATA ─────────────────────────────────────────────────────────────────
$subFilter = (int)($_GET['subject'] ?? 0);
$subSQL    = $subFilter ? "AND pp.subject_id=$subFilter" : '';

$papers = $pdo->prepare("
    SELECT pp.*, s.name as subject_name, s.color as subject_color
    FROM past_papers pp JOIN subjects s ON pp.subject_id=s.id
    WHERE pp.user_id=? $subSQL
    ORDER BY s.name ASC, pp.year DESC, pp.paper_no ASC
");
$papers->execute([$uid]);
$papers = $papers->fetchAll();

$subjects = $pdo->prepare("SELECT id,name,color FROM subjects WHERE user_id=? ORDER BY name");
$subjects->execute([$uid]);
$subjects = $subjects->fetchAll();

$total     = count($papers);
$done      = count(array_filter($papers, fn($p) => $p['done']));
$notDone   = $total - $done;
$pct       = $total > 0 ? round(($done/$total)*100) : 0;
$withScore = array_filter($papers, fn($p) => $p['done'] && $p['score'] !== null && $p['total_marks'] > 0);
$avgScore  = count($withScore) > 0
    ? round(array_sum(array_map(fn($p) => ($p['score']/$p['total_marks'])*100, $withScore)) / count($withScore), 1)
    : null;

$bySubject = [];
foreach ($papers as $p) $bySubject[$p['subject_name']][] = $p;

// Chart data
$scoreTrend = [];
foreach ($papers as $p) {
    if ($p['done'] && $p['score'] !== null && $p['total_marks'] > 0) {
        $yr = (int)$p['year'];
        if (!isset($scoreTrend[$yr])) $scoreTrend[$yr] = ['sum'=>0,'cnt'=>0];
        $scoreTrend[$yr]['sum'] += ($p['score']/$p['total_marks'])*100;
        $scoreTrend[$yr]['cnt']++;
    }
}
ksort($scoreTrend);
$trendLabels = array_keys($scoreTrend);
$trendData   = array_map(fn($v) => round($v['sum']/$v['cnt'],1), $scoreTrend);

$subPerf = [];
foreach ($bySubject as $sName => $sps) {
    $sc = array_filter($sps, fn($p)=>$p['done']&&$p['score']!==null&&$p['total_marks']>0);
    if (count($sc)) $subPerf[] = ['name'=>$sName,'avg'=>round(array_sum(array_map(fn($p)=>($p['score']/$p['total_marks'])*100,$sc))/count($sc),1),'color'=>$sps[0]['subject_color']];
}

require_once 'includes/header.php';
renderHeader('Past Papers', 'past-papers');
?>
<style>
@import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;600;700;800;900&family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap');
:root{--pf:'Outfit',sans-serif;--pb:'Plus Jakarta Sans',sans-serif;}

/* ── Theme white-flash fix ── */
/* Set bg on html immediately — no flash, no transition needed */
html{background:var(--bg-primary)!important;}
body{background:var(--bg-primary)!important;color:var(--text-primary)!important;}
.app-layout,.main-content,.page-content{background:var(--bg-primary)!important;}
/* Explicit dark/light values as fallback if CSS vars not yet resolved */
html:not([data-theme="light"]){background:#0a0a0f!important;}
html:not([data-theme="light"]) body{background:#0a0a0f!important;}
[data-theme="light"] html,[data-theme="light"] body{background:#f1f5f9!important;}

.ppw{font-family:var(--pb);padding-bottom:56px;max-width:1280px;}

/* Stats */
.pp-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:18px;}
@media(max-width:860px){.pp-stats{grid-template-columns:repeat(2,1fr);}}
.pp-st{background:var(--bg-card);border:1px solid var(--border);border-radius:18px;padding:20px 20px 16px;position:relative;overflow:hidden;transition:transform .18s,box-shadow .18s;animation:pprise .45s ease both;}
.pp-st:hover{transform:translateY(-3px);box-shadow:0 12px 32px rgba(0,0,0,.18);}
.pp-st::before{content:'';position:absolute;width:100px;height:100px;border-radius:50%;top:-24px;right:-24px;pointer-events:none;}
.st1::before{background:rgba(99,102,241,.14)}.st2::before{background:rgba(16,185,129,.14)}.st3::before{background:rgba(239,68,68,.12)}.st4::before{background:rgba(245,158,11,.13)}
.pp-st:nth-child(1){animation-delay:.04s}.pp-st:nth-child(2){animation-delay:.08s}.pp-st:nth-child(3){animation-delay:.12s}.pp-st:nth-child(4){animation-delay:.16s}
.pp-st-ico{width:38px;height:38px;border-radius:11px;display:flex;align-items:center;justify-content:center;margin-bottom:14px;}
.pp-st-val{font-family:var(--pf);font-size:28px;font-weight:800;color:var(--text-primary);line-height:1;letter-spacing:-.5px;margin-bottom:4px;}
.pp-st-lbl{font-size:12px;color:var(--text-muted);font-weight:600;}

/* Progress */
.pp-prog{background:var(--bg-card);border:1px solid var(--border);border-radius:18px;padding:18px 22px;margin-bottom:18px;animation:pprise .45s .1s ease both;}
.pp-prog-hd{display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;}
.pp-prog-t{font-family:var(--pf);font-size:14px;font-weight:700;color:var(--text-primary);}
.pp-prog-p{font-size:13px;font-weight:700;color:var(--accent);}
.pp-bar{height:8px;background:var(--bg-secondary);border-radius:99px;overflow:hidden;}
.pp-bar-fill{height:100%;border-radius:99px;background:var(--gradient);transition:width 1s cubic-bezier(.4,0,.2,1);}

/* Toolbar */
.pp-tb{display:flex;flex-wrap:wrap;gap:10px;align-items:center;margin-bottom:18px;animation:pprise .45s .12s ease both;}
.pp-sel{background:var(--bg-card);border:1.5px solid var(--border);border-radius:11px;color:var(--text-primary);font-family:var(--pb);font-size:13px;padding:9px 14px;outline:none;transition:border-color .2s;cursor:pointer;}
.pp-sel:focus{border-color:var(--accent);}
.ppb{display:inline-flex;align-items:center;gap:7px;padding:9px 18px;border-radius:11px;font-family:var(--pb);font-size:13px;font-weight:700;cursor:pointer;border:none;transition:all .18s;white-space:nowrap;text-decoration:none;}
.ppb-pri{background:var(--gradient);color:#fff;box-shadow:0 4px 14px rgba(99,102,241,.3);}
.ppb-pri:hover{transform:translateY(-1px);box-shadow:0 8px 24px rgba(99,102,241,.4);}
.ppb-sec{background:var(--bg-card);border:1.5px solid var(--border);color:var(--text-secondary);}
.ppb-sec:hover{border-color:var(--accent);color:var(--accent);background:rgba(99,102,241,.06);}

/* Section title */
.pp-sec{font-family:var(--pf);font-size:15px;font-weight:800;color:var(--text-primary);letter-spacing:-.3px;margin:22px 0 12px;display:flex;align-items:center;gap:8px;}

/* Charts */
.pp-charts{display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:18px;}
@media(max-width:860px){.pp-charts{grid-template-columns:1fr;}}
.pp-card{background:var(--bg-card);border:1px solid var(--border);border-radius:18px;padding:20px 22px;animation:pprise .45s .18s ease both;}
.pp-card-hd{display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;}
.pp-card-t{font-family:var(--pf);font-size:14px;font-weight:700;color:var(--text-primary);letter-spacing:-.2px;}
.pp-chart-h{height:200px;}

/* Subject block */
.pp-subj{background:var(--bg-card);border:1px solid var(--border);border-radius:18px;margin-bottom:14px;overflow:hidden;animation:pprise .45s .2s ease both;}
.pp-subj-hd{display:flex;align-items:center;justify-content:space-between;padding:15px 20px 11px;border-bottom:1px solid var(--border);cursor:pointer;user-select:none;transition:background .15s;}
.pp-subj-hd:hover{background:var(--bg-secondary);}
.pp-subj-nm{display:flex;align-items:center;gap:10px;font-family:var(--pf);font-size:15px;font-weight:700;color:var(--text-primary);}
.pp-dot{width:10px;height:10px;border-radius:50%;flex-shrink:0;}
.pp-subj-right{display:flex;align-items:center;gap:10px;flex-shrink:0;}
.pp-badge{padding:3px 10px;border-radius:99px;font-size:11px;font-weight:700;}
.pbg{background:rgba(16,185,129,.12);color:#10b981;}
.pby{background:rgba(245,158,11,.12);color:#f59e0b;}
.pbr{background:rgba(239,68,68,.12);color:#ef4444;}
.pbb{background:rgba(99,102,241,.12);color:#6366f1;}
.pp-toggle-icon{font-size:14px;color:var(--text-muted);transition:transform .25s;display:flex;align-items:center;}
.pp-toggle-icon.open{transform:rotate(180deg);}

/* Mini progress */
.pp-mini-bar-wrap{padding:6px 20px 0;}
.pp-mini-bar{height:4px;background:var(--bg-secondary);border-radius:99px;overflow:hidden;margin-bottom:12px;}
.pp-mini-fill{height:100%;border-radius:99px;transition:width .8s cubic-bezier(.4,0,.2,1);}

/* Year group */
.pp-body{padding:0 20px 16px;}
.pp-yr-row{display:flex;align-items:center;justify-content:space-between;margin:12px 0 7px;}
.pp-yr-lbl{font-size:11px;font-weight:700;color:var(--text-muted);text-transform:uppercase;letter-spacing:.8px;}
.pp-yr-del{display:flex;align-items:center;gap:5px;background:none;border:none;cursor:pointer;font-size:11px;font-weight:600;color:var(--text-muted);padding:3px 8px;border-radius:6px;transition:all .15s;}
.pp-yr-del:hover{color:#ef4444;background:rgba(239,68,68,.08);}
.pp-chips{display:flex;flex-wrap:wrap;gap:8px;}

/* Paper chip */
.pchip{display:flex;align-items:center;gap:8px;background:var(--bg-secondary);border:1.5px solid var(--border);border-radius:12px;padding:9px 13px;cursor:pointer;transition:all .18s;user-select:none;position:relative;}
.pchip:hover{border-color:var(--border-light);background:var(--bg-card-hover);}
.pchip.done{background:rgba(16,185,129,.08);border-color:rgba(16,185,129,.28);}
.pchip.done .pchip-lbl{color:#10b981;}
.pchk{width:20px;height:20px;border-radius:6px;border:2px solid var(--border-light);display:flex;align-items:center;justify-content:center;flex-shrink:0;transition:all .18s;background:transparent;}
.pchip.done .pchk{background:#10b981;border-color:#10b981;}
.pchip-lbl{font-size:13px;font-weight:600;color:var(--text-secondary);transition:color .18s;white-space:nowrap;}
.pchip-sub{font-size:10px;color:var(--text-muted);white-space:nowrap;max-width:90px;overflow:hidden;text-overflow:ellipsis;}
.pchip-score{font-size:11px;font-weight:700;padding:2px 7px;border-radius:99px;flex-shrink:0;}
.pchip-addscore{font-size:11px;color:var(--accent);border:1px dashed rgba(99,102,241,.35);border-radius:6px;padding:2px 8px;cursor:pointer;background:none;font-family:var(--pb);font-weight:600;white-space:nowrap;transition:all .15s;}
.pchip-addscore:hover{background:rgba(99,102,241,.08);border-color:var(--accent);}
.pchip-del{width:20px;height:20px;border-radius:5px;background:none;border:none;color:var(--text-muted);cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:12px;opacity:0;transition:opacity .15s;flex-shrink:0;}
.pchip:hover .pchip-del{opacity:1;}
.pchip-del:hover{color:#ef4444;background:rgba(239,68,68,.1);}

/* Del subject btn */
.pp-subj-del{display:inline-flex;align-items:center;gap:5px;background:none;border:1px solid rgba(239,68,68,.25);color:#ef4444;border-radius:8px;padding:4px 10px;font-size:11px;font-weight:600;cursor:pointer;transition:all .15s;font-family:var(--pb);}
.pp-subj-del:hover{background:rgba(239,68,68,.1);border-color:rgba(239,68,68,.4);}

/* Empty */
.pp-empty{text-align:center;padding:52px 20px;}
.pp-empty-icon{font-size:44px;margin-bottom:14px;}
.pp-empty h3{font-family:var(--pf);font-size:16px;font-weight:700;color:var(--text-secondary);margin-bottom:6px;}
.pp-empty p{font-size:13px;color:var(--text-muted);}

/* Modals */
.pp-modal{max-width:500px;}
.pp-msm{max-width:380px;}
.pp-mt{font-family:var(--pf);font-size:17px;font-weight:800;color:var(--text-primary);}
.pp-lbl{font-size:11px;font-weight:700;color:var(--text-muted);text-transform:uppercase;letter-spacing:.7px;margin-bottom:7px;display:block;}
.pp-inp{width:100%;background:var(--bg-secondary);border:1.5px solid var(--border);border-radius:11px;color:var(--text-primary);font-family:var(--pb);font-size:14px;padding:11px 14px;outline:none;transition:border-color .2s,box-shadow .2s;}
.pp-inp:focus{border-color:var(--accent);box-shadow:0 0 0 3px rgba(99,102,241,.12);}
.pp-inp::placeholder{color:var(--text-muted);opacity:.7;}
.pp-row2{display:grid;grid-template-columns:1fr 1fr;gap:14px;}
.pp-fg{margin-bottom:16px;}
.pp-yr-range{display:flex;align-items:center;gap:10px;}
.pp-yr-range span{font-size:13px;color:var(--text-muted);font-weight:600;flex-shrink:0;}
.pp-pchecks{display:flex;gap:12px;flex-wrap:wrap;margin-top:4px;}
.pp-pchk{display:flex;align-items:center;gap:6px;cursor:pointer;}
.pp-pchk input{accent-color:var(--accent);width:15px;height:15px;cursor:pointer;}
.pp-pchk span{font-size:13px;font-weight:600;color:var(--text-secondary);}
.pp-preview{background:rgba(99,102,241,.08);border:1px solid rgba(99,102,241,.2);border-radius:11px;padding:11px 14px;font-size:13px;color:var(--text-secondary);margin-bottom:16px;}
.pp-savebtn{width:100%;padding:13px;font-family:var(--pb);font-size:14px;font-weight:700;letter-spacing:.2px;}
.pp-alert{padding:11px 14px;border-radius:11px;font-size:13px;font-weight:600;display:flex;align-items:center;gap:9px;margin-bottom:16px;animation:alertPopIn .28s cubic-bezier(.34,1.3,.64,1);}
@keyframes alertPopIn{from{opacity:0;transform:translateY(-6px) scale(.98)}to{opacity:1;transform:translateY(0) scale(1)}}
.pa-ok{background:rgba(16,185,129,.1);border:1px solid rgba(16,185,129,.25);color:#10b981;}
.pa-err{background:rgba(239,68,68,.1);border:1px solid rgba(239,68,68,.25);color:#ef4444;}
[data-theme="light"] .pa-ok{color:#047857;}[data-theme="light"] .pa-err{color:#b91c1c;}
.pp-spin{display:inline-block;width:14px;height:14px;border:2px solid rgba(255,255,255,.35);border-top-color:#fff;border-radius:50%;animation:ppspin .7s linear infinite;vertical-align:middle;}
@keyframes ppspin{to{transform:rotate(360deg);}}
@keyframes pprise{from{opacity:0;transform:translateY(16px)}to{opacity:1;transform:translateY(0)}}

/* Collapsed body hidden */
.pp-content{display:block;}
.pp-content.collapsed{display:none;}
</style>

<div class="ppw">

<!-- Stats -->
<div class="pp-stats">
  <div class="pp-st st1">
    <div class="pp-st-ico" style="background:rgba(99,102,241,.12)">
      <svg width="18" height="18" fill="none" stroke="#6366f1" stroke-width="2.2" viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
    </div>
    <div class="pp-st-val"><?= $total ?></div>
    <div class="pp-st-lbl">Total Papers</div>
  </div>
  <div class="pp-st st2">
    <div class="pp-st-ico" style="background:rgba(16,185,129,.12)">
      <svg width="18" height="18" fill="none" stroke="#10b981" stroke-width="2.2" viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"/></svg>
    </div>
    <div class="pp-st-val"><?= $done ?></div>
    <div class="pp-st-lbl">Completed</div>
  </div>
  <div class="pp-st st3">
    <div class="pp-st-ico" style="background:rgba(239,68,68,.1)">
      <svg width="18" height="18" fill="none" stroke="#ef4444" stroke-width="2.2" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
    </div>
    <div class="pp-st-val"><?= $notDone ?></div>
    <div class="pp-st-lbl">Remaining</div>
  </div>
  <div class="pp-st st4">
    <div class="pp-st-ico" style="background:rgba(245,158,11,.12)">
      <svg width="18" height="18" fill="none" stroke="#f59e0b" stroke-width="2.2" viewBox="0 0 24 24"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>
    </div>
    <div class="pp-st-val"><?= $avgScore !== null ? $avgScore.'%' : '—' ?></div>
    <div class="pp-st-lbl">Avg Score</div>
  </div>
</div>

<!-- Progress -->
<?php if ($total > 0): ?>
<div class="pp-prog">
  <div class="pp-prog-hd">
    <span class="pp-prog-t">Overall Progress</span>
    <span class="pp-prog-p"><?= $done ?> / <?= $total ?> &nbsp;·&nbsp; <?= $pct ?>%</span>
  </div>
  <div class="pp-bar"><div class="pp-bar-fill" style="width:<?= $pct ?>%"></div></div>
</div>
<?php endif; ?>

<!-- Toolbar -->
<div class="pp-tb">
  <select class="pp-sel" onchange="location.href='?subject='+this.value">
    <option value="0">All Subjects</option>
    <?php foreach ($subjects as $s): ?>
    <option value="<?= $s['id'] ?>" <?= $subFilter==$s['id']?'selected':'' ?>><?= htmlspecialchars($s['name']) ?></option>
    <?php endforeach; ?>
  </select>
  <button class="ppb ppb-sec" onclick="openSingle()">
    <svg width="13" height="13" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>Add Single
  </button>
  <button class="ppb ppb-pri" style="margin-left:auto" onclick="openBulk()">
    <svg width="13" height="13" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>Add by Year Range
  </button>
</div>

<!-- Analysis -->
<?php if (!empty($scoreTrend) || !empty($subPerf)): ?>
<div class="pp-sec">
  <svg width="15" height="15" fill="none" stroke="var(--accent)" stroke-width="2.2" viewBox="0 0 24 24"><polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/><polyline points="17 6 23 6 23 12"/></svg>
  Performance Analysis
</div>
<div class="pp-charts">
  <?php if (!empty($scoreTrend)): ?>
  <div class="pp-card">
    <div class="pp-card-hd"><span class="pp-card-t">Score Trend by Year</span><span style="font-size:11px;color:var(--text-muted)"><?= count($trendLabels) ?> year<?= count($trendLabels)!=1?'s':'' ?></span></div>
    <div class="pp-chart-h"><canvas id="trendChart"></canvas></div>
  </div>
  <?php endif; ?>
  <?php if (!empty($subPerf)): ?>
  <div class="pp-card">
    <div class="pp-card-hd"><span class="pp-card-t">Avg Score by Subject</span><span style="font-size:11px;color:var(--text-muted)"><?= count($subPerf) ?> subject<?= count($subPerf)!=1?'s':'' ?></span></div>
    <div class="pp-chart-h"><canvas id="subChart"></canvas></div>
  </div>
  <?php endif; ?>
</div>
<?php endif; ?>

<!-- Papers -->
<?php if (empty($papers)): ?>
<div class="pp-card"><div class="pp-empty">
  <div class="pp-empty-icon">📄</div>
  <h3>No past papers yet</h3>
  <p>Click "Add by Year Range" to quickly add multiple papers at once.</p>
</div></div>
<?php else: ?>
<div class="pp-sec">
  <svg width="15" height="15" fill="none" stroke="var(--accent)" stroke-width="2.2" viewBox="0 0 24 24"><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>
  Papers
</div>
<?php foreach ($bySubject as $subName => $subPapers):
  $sid      = $subPapers[0]['subject_id'];
  $subDone  = count(array_filter($subPapers, fn($p)=>$p['done']));
  $subTotal = count($subPapers);
  $subPct   = $subTotal > 0 ? round(($subDone/$subTotal)*100) : 0;
  $subColor = $subPapers[0]['subject_color'];
  $subSc    = array_filter($subPapers, fn($p)=>$p['done']&&$p['score']!==null&&$p['total_marks']>0);
  $subAvg   = count($subSc)>0 ? round(array_sum(array_map(fn($p)=>($p['score']/$p['total_marks'])*100,$subSc))/count($subSc),1) : null;
  $byYear   = []; foreach ($subPapers as $p) $byYear[(int)$p['year']][] = $p; krsort($byYear);
  $blockId  = 'subj-'.$sid;
?>
<div class="pp-subj" id="block-<?= $sid ?>">
  <!-- Header (click to toggle) -->
  <div class="pp-subj-hd" onclick="toggleSubj('<?= $blockId ?>')">
    <div class="pp-subj-nm">
      <span class="pp-dot" style="background:<?= htmlspecialchars($subColor) ?>"></span>
      <?= htmlspecialchars($subName) ?>
    </div>
    <div class="pp-subj-right">
      <?php if ($subAvg !== null): ?>
        <span class="pp-badge <?= $subAvg>=75?'pbg':($subAvg>=55?'pby':'pbr') ?>">Avg <?= $subAvg ?>%</span>
      <?php endif; ?>
      <span style="font-size:12px;color:var(--text-muted);font-weight:600"><?= $subDone ?>/<?= $subTotal ?></span>
      <button class="pp-subj-del" onclick="event.stopPropagation();delSubject(<?= $sid ?>,<?= json_encode($subName) ?>)">
        <svg width="11" height="11" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><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"/></svg>
        Delete All
      </button>
      <span class="pp-toggle-icon open" id="icon-<?= $blockId ?>">
        <svg width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><polyline points="6 9 12 15 18 9"/></svg>
      </span>
    </div>
  </div>

  <!-- Collapsible content -->
  <div class="pp-content" id="<?= $blockId ?>">
    <div class="pp-mini-bar-wrap">
      <div class="pp-mini-bar">
        <div class="pp-mini-fill" style="width:<?= $subPct ?>%;background:<?= htmlspecialchars($subColor) ?>"></div>
      </div>
    </div>
    <div class="pp-body">
      <?php foreach ($byYear as $yr => $yPapers): ?>
      <div class="pp-yr-row">
        <span class="pp-yr-lbl"><?= $yr ?></span>
        <button class="pp-yr-del" onclick="delYear(<?= $sid ?>,<?= $yr ?>,<?= json_encode($subName) ?>)">
          <svg width="10" height="10" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><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"/></svg>
          Delete <?= $yr ?>
        </button>
      </div>
      <div class="pp-chips">
        <?php foreach ($yPapers as $p):
          $scorePct = ($p['score']!==null && $p['total_marks']>0) ? round(($p['score']/$p['total_marks'])*100) : null;
          $sc = $scorePct!==null ? ($scorePct>=75?'#10b981':($scorePct>=55?'#f59e0b':'#ef4444')) : '';
        ?>
        <div class="pchip <?= $p['done']?'done':'' ?>" id="chip-<?= $p['id'] ?>" onclick="toggleChip(<?= $p['id'] ?>,<?= $p['done']?0:1 ?>)">
          <div class="pchk">
            <?php if ($p['done']): ?>
            <svg width="11" height="11" fill="none" stroke="#fff" stroke-width="3" viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"/></svg>
            <?php endif; ?>
          </div>
          <div>
            <div class="pchip-lbl">Paper <?= $p['paper_no'] ?></div>
            <?php if (!empty($p['lesson'])): ?>
            <div class="pchip-sub"><?= htmlspecialchars($p['lesson']) ?></div>
            <?php endif; ?>
          </div>
          <?php if ($scorePct !== null): ?>
            <span class="pchip-score" style="background:<?= $sc ?>22;color:<?= $sc ?>;cursor:pointer" onclick="event.stopPropagation();openScore(<?= $p['id'] ?>,<?= (float)($p['score']??0) ?>,<?= (float)($p['total_marks']??100) ?>,<?= json_encode($p['notes'] ?? '') ?>)" title="Edit score"><?= $scorePct ?>%</span>
          <?php else: ?>
            <button class="pchip-addscore" onclick="event.stopPropagation();openScore(<?= $p['id'] ?>,<?= (float)($p['score']??0) ?>,<?= (float)($p['total_marks']??100) ?>,<?= json_encode($p['notes'] ?? '') ?>)">+ Mark</button>
          <?php endif; ?>
          <button class="pchip-del" onclick="event.stopPropagation();delOne(<?= $p['id'] ?>)" title="Delete">
            <svg width="11" height="11" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          </button>
        </div>
        <?php endforeach; ?>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
</div>
<?php endforeach; endif; ?>

<!-- ══ BULK MODAL ══ -->
<div class="modal-overlay" id="bulkModal">
  <div class="modal pp-modal">
    <div class="modal-header">
      <span class="pp-mt">Add Papers by Year Range</span>
      <button class="modal-close" onclick="closeBulk()">✕</button>
    </div>
    <div id="bulkMsg" style="display:none" class="pp-alert"></div>
    <div class="pp-fg">
      <label class="pp-lbl">Subject</label>
      <select id="bSub" class="pp-inp">
        <option value="">— Select subject —</option>
        <?php foreach ($subjects as $s): ?>
        <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="pp-fg">
      <label class="pp-lbl">Lesson / Topic (optional)</label>
      <input type="text" id="bLesson" class="pp-inp" placeholder="e.g. Mechanics, Organic Chemistry…">
    </div>
    <div class="pp-fg">
      <label class="pp-lbl">Year Range</label>
      <div class="pp-yr-range">
        <input type="number" id="bFrom" class="pp-inp" placeholder="From e.g. 2015" min="2000" max="<?= date('Y') ?>" style="text-align:center">
        <span>→</span>
        <input type="number" id="bTo" class="pp-inp" placeholder="To e.g. <?= date('Y')-1 ?>" min="2000" max="<?= date('Y') ?>" style="text-align:center">
      </div>
    </div>
    <div class="pp-fg">
      <label class="pp-lbl">Papers to Include</label>
      <div class="pp-pchecks">
        <label class="pp-pchk"><input type="checkbox" name="bPp" value="1" checked><span>Paper 1</span></label>
        <label class="pp-pchk"><input type="checkbox" name="bPp" value="2"><span>Paper 2</span></label>
        <label class="pp-pchk"><input type="checkbox" name="bPp" value="3"><span>Paper 3</span></label>
      </div>
    </div>
    <div id="bPrev" style="display:none" class="pp-preview"></div>
    <button class="btn btn-primary pp-savebtn" id="bulkBtn" onclick="saveBulk()">Add Papers</button>
  </div>
</div>

<!-- ══ SINGLE MODAL ══ -->
<div class="modal-overlay" id="singleModal">
  <div class="modal pp-msm">
    <div class="modal-header">
      <span class="pp-mt">Add Single Paper</span>
      <button class="modal-close" onclick="closeSingle()">✕</button>
    </div>
    <div id="singleMsg" style="display:none" class="pp-alert"></div>
    <div class="pp-fg">
      <label class="pp-lbl">Subject</label>
      <select id="sSub" class="pp-inp">
        <option value="">— Select —</option>
        <?php foreach ($subjects as $s): ?>
        <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="pp-fg">
      <label class="pp-lbl">Lesson / Topic (optional)</label>
      <input type="text" id="sLesson" class="pp-inp" placeholder="e.g. Waves, Electrostatics…">
    </div>
    <div class="pp-row2">
      <div class="pp-fg">
        <label class="pp-lbl">Year</label>
        <input type="number" id="sYear" class="pp-inp" min="2000" max="<?= date('Y') ?>" value="<?= date('Y')-1 ?>">
      </div>
      <div class="pp-fg">
        <label class="pp-lbl">Paper No.</label>
        <select id="sPno" class="pp-inp">
          <option value="1">Paper 1</option>
          <option value="2">Paper 2</option>
          <option value="3">Paper 3</option>
        </select>
      </div>
    </div>
    <button class="btn btn-primary pp-savebtn" id="singleBtn" onclick="saveSingle()">Add Paper</button>
  </div>
</div>

<!-- ══ SCORE MODAL ══ -->
<div class="modal-overlay" id="scoreModal">
  <div class="modal pp-msm">
    <div class="modal-header">
      <span class="pp-mt">Add Mark</span>
      <button class="modal-close" onclick="closeScore()">✕</button>
    </div>
    <div id="scoreMsg" style="display:none" class="pp-alert"></div>
    <input type="hidden" id="scoreId">
    <div class="pp-row2">
      <div class="pp-fg">
        <label class="pp-lbl">Score</label>
        <input type="number" id="scoreVal" class="pp-inp" placeholder="e.g. 75" step="0.5">
      </div>
      <div class="pp-fg">
        <label class="pp-lbl">Out of</label>
        <input type="number" id="scoreTot" class="pp-inp" value="100" step="0.5">
      </div>
    </div>
    <div class="pp-fg">
      <label class="pp-lbl">Notes (optional)</label>
      <textarea id="scoreNotes" class="pp-inp" rows="2" placeholder="Topics to revisit…"></textarea>
    </div>
    <button class="btn btn-primary pp-savebtn" id="scoreBtn" onclick="saveScore()">Save Mark</button>
  </div>
</div>

</div><!-- .ppw -->

<script>
// ── Toggle subject collapse ──────────────────────────────────────────
function toggleSubj(id) {
  var el   = document.getElementById(id);
  var icon = document.getElementById('icon-'+id);
  if (el.classList.contains('collapsed')) {
    // Expand
    el.classList.remove('collapsed');
    el.style.maxHeight = '0';
    el.style.overflow  = 'hidden';
    el.style.opacity   = '0';
    el.style.display   = 'block';
    requestAnimationFrame(function(){
      el.style.transition = 'max-height .35s ease, opacity .25s ease';
      el.style.maxHeight  = el.scrollHeight + 'px';
      el.style.opacity    = '1';
    });
    setTimeout(function(){ el.style.maxHeight=''; el.style.overflow=''; el.style.transition=''; }, 380);
    icon.classList.add('open');
  } else {
    // Collapse
    el.style.maxHeight  = el.scrollHeight + 'px';
    el.style.overflow   = 'hidden';
    el.style.transition = 'max-height .3s ease, opacity .22s ease';
    requestAnimationFrame(function(){
      el.style.maxHeight = '0';
      el.style.opacity   = '0';
    });
    setTimeout(function(){ el.classList.add('collapsed'); el.style.maxHeight=''; el.style.overflow=''; el.style.transition=''; el.style.opacity=''; }, 320);
    icon.classList.remove('open');
  }
}

// ── Modal helpers ────────────────────────────────────────────────────
function openBulk()    { document.getElementById('bulkModal').classList.add('active'); }
function closeBulk()   { document.getElementById('bulkModal').classList.remove('active'); document.getElementById('bulkMsg').style.display='none'; }
function openSingle()  { document.getElementById('singleModal').classList.add('active'); }
function closeSingle() { document.getElementById('singleModal').classList.remove('active'); document.getElementById('singleMsg').style.display='none'; }
function closeScore()  { document.getElementById('scoreModal').classList.remove('active'); }

// ── Live preview ─────────────────────────────────────────────────────
function upPrev() {
  var from=parseInt(document.getElementById('bFrom').value)||0;
  var to=parseInt(document.getElementById('bTo').value)||0;
  var pps=Array.from(document.querySelectorAll('input[name="bPp"]:checked')).map(function(c){return c.value;});
  var sub=document.getElementById('bSub').value;
  var prev=document.getElementById('bPrev');
  if(from&&to&&from<=to&&pps.length&&sub){
    var yrs=to-from+1,cnt=yrs*pps.length;
    prev.textContent='Will add '+cnt+' paper'+(cnt!==1?'s':'')+' — '+yrs+' year'+(yrs!==1?'s':'')+' × Paper '+pps.join(', ');
    prev.style.display='block';
  } else { prev.style.display='none'; }
}
['bFrom','bTo','bSub'].forEach(function(id){document.getElementById(id).addEventListener('input',upPrev);});
document.querySelectorAll('input[name="bPp"]').forEach(function(cb){cb.addEventListener('change',upPrev);});

// ── Bulk save ────────────────────────────────────────────────────────
async function saveBulk() {
  var msg=document.getElementById('bulkMsg'),btn=document.getElementById('bulkBtn');
  var sub=document.getElementById('bSub').value;
  var from=document.getElementById('bFrom').value;
  var to=document.getElementById('bTo').value;
  var pps=Array.from(document.querySelectorAll('input[name="bPp"]:checked')).map(function(c){return c.value;});
  if(!sub||!from||!to){showMsg(msg,'Please fill in all fields.','err');return;}
  if(parseInt(from)>parseInt(to)){showMsg(msg,'From year must be ≤ To year.','err');return;}
  if(!pps.length){showMsg(msg,'Select at least one paper.','err');return;}
  var orig=btn.innerHTML; btn.disabled=true; btn.innerHTML='<span class="pp-spin"></span>&nbsp;Adding…'; msg.style.display='none';
  var fd=new FormData();
  fd.append('action','add_bulk');fd.append('subject_id',sub);fd.append('from_year',from);fd.append('to_year',to);
  fd.append('lesson',document.getElementById('bLesson').value);
  pps.forEach(function(p){fd.append('papers[]',p);});
  try{
    var res=await fetch(location.href,{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:fd});
    var data=await res.json();
    showMsg(msg,data.message,data.success?'ok':'err');
    if(data.success&&data.added>0)setTimeout(function(){location.reload();},900);
  }catch(e){showMsg(msg,'Connection error.','err');}
  btn.disabled=false;btn.innerHTML=orig;
}

// ── Single save ──────────────────────────────────────────────────────
async function saveSingle() {
  var msg=document.getElementById('singleMsg'),btn=document.getElementById('singleBtn');
  var sub=document.getElementById('sSub').value,yr=document.getElementById('sYear').value;
  if(!sub||!yr){showMsg(msg,'Subject and year required.','err');return;}
  var orig=btn.innerHTML;btn.disabled=true;btn.innerHTML='<span class="pp-spin"></span>&nbsp;Adding…';msg.style.display='none';
  var fd=new FormData();
  fd.append('action','add_single');fd.append('subject_id',sub);fd.append('year',yr);
  fd.append('paper_no',document.getElementById('sPno').value);
  fd.append('lesson',document.getElementById('sLesson').value);
  try{
    var res=await fetch(location.href,{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:fd});
    var data=await res.json();
    showMsg(msg,data.message,data.success?'ok':'err');
    if(data.success)setTimeout(function(){location.reload();},800);
  }catch(e){showMsg(msg,'Error.','err');}
  btn.disabled=false;btn.innerHTML=orig;
}

// ── Toggle chip ──────────────────────────────────────────────────────
async function toggleChip(id,done){
  var chip=document.getElementById('chip-'+id);
  chip.classList.toggle('done',!!done);
  var chk=chip.querySelector('.pchk');
  chk.innerHTML=done?'<svg width="11" height="11" fill="none" stroke="#fff" stroke-width="3" viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"/></svg>':'';
  chip.onclick=function(){toggleChip(id,done?0:1);};
  var fd=new FormData();fd.append('action','toggle');fd.append('id',id);fd.append('done',done);
  await fetch(location.href,{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:fd});
}

// ── Score ────────────────────────────────────────────────────────────
function openScore(id,score,total,notes){
  document.getElementById('scoreId').value=id;
  document.getElementById('scoreVal').value=score||'';
  document.getElementById('scoreTot').value=total||100;
  document.getElementById('scoreNotes').value=notes||'';
  document.getElementById('scoreMsg').style.display='none';
  document.getElementById('scoreModal').classList.add('active');
}
async function saveScore(){
  var msg=document.getElementById('scoreMsg'),btn=document.getElementById('scoreBtn');
  var orig=btn.innerHTML;btn.disabled=true;btn.innerHTML='<span class="pp-spin"></span>&nbsp;Saving…';msg.style.display='none';
  var fd=new FormData();
  fd.append('action','save_score');fd.append('id',document.getElementById('scoreId').value);
  fd.append('score',document.getElementById('scoreVal').value);fd.append('total',document.getElementById('scoreTot').value);
  fd.append('notes',document.getElementById('scoreNotes').value);
  try{
    var res=await fetch(location.href,{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:fd});
    var data=await res.json();
    showMsg(msg,data.message,data.success?'ok':'err');
    if(data.success)setTimeout(function(){location.reload();},800);
  }catch(e){showMsg(msg,'Error.','err');}
  btn.disabled=false;btn.innerHTML=orig;
}

// ── Delete helpers ────────────────────────────────────────────────────
async function delOne(id){
  ppConfirm('Remove this paper?', async function(){
    var chip=document.getElementById('chip-'+id);
    if(chip){chip.style.opacity='.3';chip.style.pointerEvents='none';}
    var fd=new FormData();fd.append('action','delete_one');fd.append('id',id);
    try{
      await fetch(location.href,{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:fd});
      if(chip) chip.remove();
    }catch(e){ if(chip){chip.style.opacity='1';chip.style.pointerEvents='';} }
  });
}
async function delYear(subId,year,subName){
  ppConfirm('Delete all '+subName+' '+year+' papers?', async function(){
    var fd=new FormData();fd.append('action','delete_year');fd.append('subject_id',subId);fd.append('year',year);
    try{
      await fetch(location.href,{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:fd});
      location.reload();
    }catch(e){}
  });
}
async function delSubject(subId,subName){
  ppConfirm('Delete ALL '+subName+' past papers? Cannot be undone.', async function(){
    var fd=new FormData();fd.append('action','delete_subject');fd.append('subject_id',subId);
    try{
      await fetch(location.href,{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:fd});
      var el=document.getElementById('block-'+subId);if(el)el.remove();
    }catch(e){}
  });
}

// ── Custom confirm (avoids browser dialog blocks) ─────────────────
function ppConfirm(msg, onYes){
  var ov=document.createElement('div');
  ov.style.cssText='position:fixed;inset:0;z-index:99999;background:rgba(0,0,0,.55);display:flex;align-items:center;justify-content:center;padding:20px;backdrop-filter:blur(3px)';
  ov.innerHTML='<div style="background:var(--bg-card);border:1px solid var(--border);border-radius:18px;padding:24px 26px;max-width:340px;width:100%;box-shadow:0 20px 60px rgba(0,0,0,.4)">'+
    '<div style="font-family:var(--pf,sans-serif);font-size:15px;font-weight:700;color:var(--text-primary,#f1f5f9);margin-bottom:8px">Confirm</div>'+
    '<div style="font-size:13px;color:var(--text-secondary,#94a3b8);margin-bottom:20px;line-height:1.6">'+msg+'</div>'+
    '<div style="display:flex;gap:10px">'+
    '<button id="ppCfmNo"  style="flex:1;padding:10px;border-radius:10px;border:1.5px solid var(--border,#2a2a3d);background:var(--bg-secondary,#111);color:var(--text-secondary,#94a3b8);font-size:13px;font-weight:600;cursor:pointer;font-family:inherit">Cancel</button>'+
    '<button id="ppCfmYes" style="flex:1;padding:10px;border-radius:10px;border:none;background:linear-gradient(135deg,#ef4444,#dc2626);color:#fff;font-size:13px;font-weight:700;cursor:pointer;font-family:inherit">Delete</button>'+
    '</div></div>';
  document.body.appendChild(ov);
  ov.querySelector('#ppCfmNo').onclick  = function(){ document.body.removeChild(ov); };
  ov.querySelector('#ppCfmYes').onclick = function(){ document.body.removeChild(ov); onYes(); };
  ov.onclick = function(e){ if(e.target===ov) document.body.removeChild(ov); };
}

// ── Helper ───────────────────────────────────────────────────────────
function showMsg(el,msg,type){
  el.className='pp-alert pa-'+type;
  el.innerHTML=(type==='ok'?'✅ ':'⚠️ ')+msg;
  el.style.display='flex';
}

// ── Charts ────────────────────────────────────────────────────────────
(function(){
  var dark=document.documentElement.getAttribute('data-theme')!=='light';
  var gc=dark?'rgba(42,42,61,.4)':'rgba(203,213,225,.5)';
  var tc=dark?'#64748b':'#94a3b8';
  var tbg=dark?'rgba(16,16,24,.97)':'#fff';
  var tbdr=dark?'rgba(99,102,241,.3)':'rgba(99,102,241,.25)';
  var baseOpts={
    responsive:true,maintainAspectRatio:false,
    plugins:{legend:{display:false},tooltip:{backgroundColor:tbg,borderColor:tbdr,borderWidth:1,cornerRadius:10,padding:12,
      titleColor:dark?'#f1f5f9':'#1e293b',bodyColor:dark?'#94a3b8':'#475569',
      titleFont:{family:"'Plus Jakarta Sans',sans-serif",size:12},
      bodyFont:{family:"'Plus Jakarta Sans',sans-serif",size:13,weight:'700'}}},
    scales:{
      x:{grid:{display:false},border:{display:false},ticks:{color:tc,font:{family:"'Plus Jakarta Sans',sans-serif",size:11}}},
      y:{grid:{color:gc},border:{display:false},ticks:{color:tc,font:{family:"'Plus Jakarta Sans',sans-serif",size:11},callback:function(v){return v+'%';}},max:100,min:0}
    },
    animation:{duration:700,easing:'easeInOutCubic'}
  };
  var tEl=document.getElementById('trendChart');
  if(tEl){
    new Chart(tEl.getContext('2d'),{type:'line',data:{
      labels:<?= json_encode(array_map('strval',$trendLabels)) ?>,
      datasets:[{label:'Avg',data:<?= json_encode(array_values($trendData)) ?>,
        borderColor:'#6366f1',backgroundColor:'rgba(99,102,241,.08)',
        pointBackgroundColor:'#6366f1',pointRadius:5,pointHoverRadius:7,
        borderWidth:2.5,fill:true,tension:.35}]
    },options:baseOpts});
  }
  var sEl=document.getElementById('subChart');
  if(sEl){
    var sd=<?= json_encode(array_values($subPerf)) ?>;
    new Chart(sEl.getContext('2d'),{type:'bar',data:{
      labels:sd.map(function(d){return d.name;}),
      datasets:[{data:sd.map(function(d){return d.avg;}),
        backgroundColor:sd.map(function(d){return d.color+'99';}),
        hoverBackgroundColor:sd.map(function(d){return d.color;}),
        borderRadius:8,borderSkipped:false,borderWidth:0}]
    },options:Object.assign({},baseOpts,{plugins:Object.assign({},baseOpts.plugins,{
      tooltip:Object.assign({},baseOpts.plugins.tooltip,{callbacks:{label:function(ctx){return '  '+ctx.raw+'%';}}})
    })})});
  }
})();
</script>

<?php require_once 'includes/footer.php'; renderFooter(); ?>