<?php
require_once 'includes/config.php';
requireLogin();
$uid = $_SESSION['user_id'];

// ── Safe self-migration: create syllabus_topics table if missing ──────────
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS syllabus_topics (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        subject_id INT NOT NULL,
        unit_name VARCHAR(150) DEFAULT NULL,
        topic_name VARCHAR(255) NOT NULL,
        is_completed TINYINT(1) DEFAULT 0,
        completed_at DATETIME DEFAULT NULL,
        sort_order INT DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
        FOREIGN KEY (subject_id) REFERENCES subjects(id) ON DELETE CASCADE
    ) ENGINE=InnoDB");
} catch (PDOException $e) { /* already exists */ }

// ── Add bookmark/difficult-topic column (safe self-migration) ────────────
try { $pdo->exec("ALTER TABLE syllabus_topics ADD COLUMN is_difficult TINYINT(1) DEFAULT 0"); } catch (PDOException $e) {}

try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS syllabus_templates (
        id INT AUTO_INCREMENT PRIMARY KEY,
        subject_name VARCHAR(150) NOT NULL,
        unit_name VARCHAR(150) DEFAULT 'General',
        topic_name VARCHAR(255) NOT NULL,
        sort_order INT DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        KEY idx_subject (subject_name)
    ) ENGINE=InnoDB");
} catch (PDOException $e) { /* already exists */ }

// ── Add spaced-repetition (SM-2) columns for the Revision Wheel ──────────
foreach ([
    "ALTER TABLE syllabus_topics ADD COLUMN ease_factor DECIMAL(3,2) DEFAULT 2.5",
    "ALTER TABLE syllabus_topics ADD COLUMN interval_days INT DEFAULT 0",
    "ALTER TABLE syllabus_topics ADD COLUMN repetitions INT DEFAULT 0",
    "ALTER TABLE syllabus_topics ADD COLUMN next_review_date DATE DEFAULT NULL",
    "ALTER TABLE syllabus_topics ADD COLUMN last_reviewed DATETIME DEFAULT NULL",
] as $migSql) {
    try { $pdo->exec($migSql); } catch (PDOException $e) {}
}

// ── SM-2 spaced repetition algorithm (shared logic with Flashcard Review) ─
function sm2Update($ef, $reps, $interval, $quality) {
    $quality = max(0, min(5, (int)$quality));
    if ($quality < 3) {
        $reps = 0;
        $interval = 1;
    } else {
        if ($reps == 0) $interval = 1;
        elseif ($reps == 1) $interval = 6;
        else $interval = (int)round($interval * $ef);
        $reps++;
    }
    $ef = $ef + (0.1 - (5 - $quality) * (0.08 + (5 - $quality) * 0.02));
    if ($ef < 1.3) $ef = 1.3;
    return [round($ef, 2), $reps, $interval];
}

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

    if ($action === 'add_topic') {
        $subId = (int)($_POST['subject_id'] ?? 0);
        $unit  = sanitize($_POST['unit_name'] ?? 'General');
        $raw   = $_POST['topic_name'] ?? '';

        // Support multiple topics at once — one per line
        $lines = preg_split('/\r\n|\r|\n/', $raw);
        $topics = [];
        foreach ($lines as $line) {
            $line = trim(sanitize($line));
            if ($line !== '') $topics[] = $line;
        }
        if (!$subId || empty($topics)) jsonResponse(['success'=>false,'message'=>'At least one topic name is required.']);

        $chk = $pdo->prepare("SELECT id FROM subjects WHERE id=? AND user_id=?");
        $chk->execute([$subId, $uid]);
        if (!$chk->fetch()) jsonResponse(['success'=>false,'message'=>'Invalid subject.']);

        $maxOrder = $pdo->prepare("SELECT COALESCE(MAX(sort_order),0) FROM syllabus_topics WHERE subject_id=? AND user_id=?");
        $maxOrder->execute([$subId, $uid]);
        $order = (int)$maxOrder->fetchColumn();

        $ins = $pdo->prepare("INSERT INTO syllabus_topics (user_id,subject_id,unit_name,topic_name,sort_order) VALUES (?,?,?,?,?)");
        foreach ($topics as $topic) {
            $ins->execute([$uid,$subId,$unit ?: 'General',$topic,++$order]);
        }
        $count = count($topics);
        jsonResponse(['success'=>true,'message'=>$count.' topic'.($count===1?'':'s').' added!']);
    }

    if ($action === 'toggle_topic') {
        $id = (int)($_POST['id'] ?? 0);
        $row = $pdo->prepare("SELECT is_completed, next_review_date FROM syllabus_topics WHERE id=? AND user_id=?");
        $row->execute([$id,$uid]); $row = $row->fetch();
        if (!$row) jsonResponse(['success'=>false,'message'=>'Not found']);
        $newVal = $row['is_completed'] ? 0 : 1;

        // First time a topic is marked complete, it joins the revision wheel (due immediately)
        if ($newVal && empty($row['next_review_date'])) {
            $pdo->prepare("UPDATE syllabus_topics SET is_completed=?, completed_at=?, next_review_date=CURDATE(), ease_factor=2.5, repetitions=0, interval_days=0 WHERE id=? AND user_id=?")
                ->execute([$newVal, date('Y-m-d H:i:s'), $id, $uid]);
        } else {
            $pdo->prepare("UPDATE syllabus_topics SET is_completed=?, completed_at=? WHERE id=? AND user_id=?")
                ->execute([$newVal, $newVal ? date('Y-m-d H:i:s') : null, $id, $uid]);
        }
        jsonResponse(['success'=>true,'is_completed'=>$newVal]);
    }

    if ($action === 'wheel_rate') {
        $id      = (int)($_POST['id'] ?? 0);
        $quality = (int)($_POST['quality'] ?? 0);

        $row = $pdo->prepare("SELECT ease_factor,repetitions,interval_days FROM syllabus_topics WHERE id=? AND user_id=?");
        $row->execute([$id, $uid]); $row = $row->fetch();
        if (!$row) jsonResponse(['success'=>false,'message'=>'Topic not found.']);

        $ef = $row['ease_factor'] ?: 2.5;
        [$newEf, $newReps, $newInterval] = sm2Update($ef, (int)$row['repetitions'], (int)$row['interval_days'], $quality);
        $nextDate = date('Y-m-d', strtotime("+{$newInterval} days"));

        $pdo->prepare("UPDATE syllabus_topics SET ease_factor=?, repetitions=?, interval_days=?, next_review_date=?, last_reviewed=NOW() WHERE id=? AND user_id=?")
            ->execute([$newEf, $newReps, $newInterval, $nextDate, $id, $uid]);

        jsonResponse(['success'=>true, 'next_review_date'=>$nextDate, 'interval_days'=>$newInterval]);
    }

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

    // ── Bulk-import the admin's official syllabus template for this subject ──
    if ($action === 'load_official_syllabus') {
        $subId = (int)($_POST['subject_id'] ?? 0);
        $chk = $pdo->prepare("SELECT id,name FROM subjects WHERE id=? AND user_id=?");
        $chk->execute([$subId, $uid]);
        $subject = $chk->fetch();
        if (!$subject) jsonResponse(['success'=>false,'message'=>'Invalid subject.']);

        $tpl = $pdo->prepare("SELECT unit_name,topic_name,sort_order FROM syllabus_templates WHERE subject_name=? ORDER BY sort_order,id");
        $tpl->execute([$subject['name']]);
        $templateTopics = $tpl->fetchAll();

        if (empty($templateTopics)) {
            jsonResponse(['success'=>false,'message'=>"No official syllabus is available yet for \"{$subject['name']}\". Ask an admin to add it."]);
        }

        // Skip topics the student already has (by exact name) so re-clicking is safe
        $existing = $pdo->prepare("SELECT topic_name FROM syllabus_topics WHERE user_id=? AND subject_id=?");
        $existing->execute([$uid, $subId]);
        $existingNames = array_map('strtolower', array_column($existing->fetchAll(), 'topic_name'));

        $maxOrder = $pdo->prepare("SELECT COALESCE(MAX(sort_order),0) FROM syllabus_topics WHERE subject_id=? AND user_id=?");
        $maxOrder->execute([$subId, $uid]);
        $order = (int)$maxOrder->fetchColumn();

        $ins = $pdo->prepare("INSERT INTO syllabus_topics (user_id,subject_id,unit_name,topic_name,sort_order) VALUES (?,?,?,?,?)");
        $added = 0;
        foreach ($templateTopics as $t) {
            if (in_array(strtolower($t['topic_name']), $existingNames)) continue;
            $ins->execute([$uid, $subId, $t['unit_name'] ?: 'General', $t['topic_name'], ++$order]);
            $added++;
        }

        if ($added === 0) jsonResponse(['success'=>true,'added'=>0,'message'=>'Your syllabus already has all these topics!']);
        jsonResponse(['success'=>true,'added'=>$added,'message'=>"$added topic(s) loaded from the official syllabus!"]);
    }

    if ($action === 'toggle_difficult') {
        $id = (int)($_POST['id'] ?? 0);
        $row = $pdo->prepare("SELECT is_difficult FROM syllabus_topics WHERE id=? AND user_id=?");
        $row->execute([$id,$uid]); $row = $row->fetch();
        if (!$row) jsonResponse(['success'=>false,'message'=>'Not found']);
        $newVal = $row['is_difficult'] ? 0 : 1;
        $pdo->prepare("UPDATE syllabus_topics SET is_difficult=? WHERE id=? AND user_id=?")
            ->execute([$newVal, $id, $uid]);
        jsonResponse(['success'=>true,'is_difficult'=>$newVal]);
    }
}

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

// Which of the student's subjects have an admin-provided official syllabus?
$templateSubjectNames = $pdo->query("SELECT DISTINCT subject_name FROM syllabus_templates")->fetchAll(PDO::FETCH_COLUMN);
$hasTemplate = [];
foreach ($subjects as $s) $hasTemplate[$s['id']] = in_array($s['name'], $templateSubjectNames);

$topicsStmt = $pdo->prepare("SELECT * FROM syllabus_topics WHERE user_id=? ORDER BY subject_id, sort_order, id");
$topicsStmt->execute([$uid]); $allTopics = $topicsStmt->fetchAll();

$bySubject = [];
foreach ($allTopics as $t) $bySubject[$t['subject_id']][] = $t;

$totalTopics = count($allTopics);
$totalDone   = count(array_filter($allTopics, fn($t) => $t['is_completed']));
$overallPct  = $totalTopics ? round($totalDone / $totalTopics * 100) : 0;

$subjectById = [];
foreach ($subjects as $s) $subjectById[$s['id']] = $s;

$difficultTopics = array_values(array_filter($allTopics, fn($t) => !empty($t['is_difficult'])));

$today = date('Y-m-d');
$dueRevisionTopics = array_values(array_filter($allTopics, fn($t) =>
    !empty($t['is_completed']) && !empty($t['next_review_date']) && $t['next_review_date'] <= $today
));
$inRevisionCycle = array_values(array_filter($allTopics, fn($t) => !empty($t['next_review_date'])));

require_once 'includes/header.php';
renderHeader('Syllabus Tracker', 'syllabus');
?>

<style>
.sy-page-header { display:flex; align-items:center; justify-content:space-between; gap:16px; margin-bottom:20px; flex-wrap:wrap; }
.sy-page-title { font-size:22px; font-weight:800; color:var(--text-primary); font-family:'Sora',sans-serif; letter-spacing:-.3px; }
.sy-page-sub { font-size:13px; color:var(--text-muted); margin-top:4px; }

.sy-overall-card { display:flex; align-items:center; gap:16px; background:var(--bg-card); border:1px solid var(--border); border-radius:14px; padding:16px 20px; margin-bottom:22px; }
.sy-overall-ring { flex-shrink:0; }
.sy-overall-text { font-size:13px; color:var(--text-secondary); }
.sy-overall-pct { font-size:26px; font-weight:800; color:var(--text-primary); font-family:'Sora',sans-serif; }

.sy-subject-tabs { display:flex; gap:8px; overflow-x:auto; margin-bottom:20px; padding-bottom:4px; }
.sy-subject-tab {
  display:flex; align-items:center; gap:8px; padding:9px 16px; border-radius:11px;
  background:var(--bg-secondary); border:1px solid var(--border); cursor:pointer;
  font-size:13px; font-weight:600; color:var(--text-secondary); white-space:nowrap; transition:all .18s;
  flex-shrink:0;
}
.sy-subject-tab.active { background:var(--bg-card); border-color:var(--accent); color:var(--text-primary); box-shadow:0 2px 10px rgba(99,102,241,.15); }
.sy-subject-dot { width:9px; height:9px; border-radius:50%; flex-shrink:0; }
.sy-subject-pct { font-size:11px; color:var(--text-muted); background:var(--bg-primary); padding:1px 7px; border-radius:99px; }

.sy-unit-block { margin-bottom:18px; }
.sy-unit-title { font-size:12px; font-weight:700; color:var(--text-muted); text-transform:uppercase; letter-spacing:.6px; margin-bottom:8px; display:flex; align-items:center; gap:8px; }
.sy-unit-title::after { content:''; flex:1; height:1px; background:var(--border); }

.sy-topic-row {
  display:flex; align-items:center; gap:12px; padding:11px 14px; background:var(--bg-card);
  border:1px solid var(--border); border-radius:10px; margin-bottom:6px; transition:all .15s;
}
.sy-topic-row:hover { border-color:var(--border-light); }
.sy-topic-row.done { opacity:.55; }
.sy-check {
  width:22px; height:22px; border-radius:7px; border:2px solid var(--border); flex-shrink:0; cursor:pointer;
  display:flex; align-items:center; justify-content:center; transition:all .15s; background:var(--bg-secondary);
}
.sy-check.checked { background:var(--gradient); border-color:transparent; }
.sy-topic-name { flex:1; font-size:13px; font-weight:500; color:var(--text-primary); }
.sy-topic-row.done .sy-topic-name { text-decoration:line-through; color:var(--text-muted); }
.sy-topic-del { width:26px; height:26px; border-radius:7px; border:1px solid var(--border); background:var(--bg-secondary); color:var(--text-muted); cursor:pointer; display:flex; align-items:center; justify-content:center; font-size:12px; flex-shrink:0; opacity:0; transition:all .15s; }
.sy-topic-row:hover .sy-topic-del { opacity:1; }
.sy-topic-del:hover { border-color:rgba(239,68,68,.4); color:#ef4444; background:rgba(239,68,68,.08); }

.sy-progress-wrap { margin-bottom:20px; }
.sy-progress-label { display:flex; justify-content:space-between; font-size:12px; color:var(--text-secondary); margin-bottom:6px; }

.sy-add-row { display:flex; gap:8px; flex-wrap:wrap; margin-top:14px; align-items:flex-start; }
.sy-add-row input { flex:1; min-width:140px; }
.sy-add-row textarea { flex:2; min-width:200px; resize:vertical; min-height:42px; font-family:inherit; }
.sy-add-hint { font-size:11px; color:var(--text-muted); margin-top:6px; width:100%; }

.sy-bookmark-btn { width:26px; height:26px; border-radius:7px; border:1px solid var(--border); background:var(--bg-secondary); color:var(--text-muted); cursor:pointer; display:flex; align-items:center; justify-content:center; flex-shrink:0; transition:all .15s; }
.sy-bookmark-btn svg { width:13px; height:13px; }
.sy-bookmark-btn.bookmarked { background:rgba(245,158,11,.14); border-color:rgba(245,158,11,.4); color:#f59e0b; }
.sy-bookmark-btn:hover { border-color:rgba(245,158,11,.5); color:#f59e0b; }

.sy-view-tabs { display:flex; gap:4px; background:var(--bg-secondary); border:1px solid var(--border); border-radius:12px; padding:4px; margin-bottom:20px; max-width:420px; }
.sy-view-tab { flex:1; padding:8px 14px; border-radius:9px; border:none; background:transparent; color:var(--text-secondary); font-size:13px; font-weight:600; cursor:pointer; transition:all .18s; display:flex; align-items:center; justify-content:center; gap:6px; font-family:inherit; white-space:nowrap; }
.sy-view-tab.active { background:var(--bg-card); color:var(--text-primary); box-shadow:0 1px 4px rgba(0,0,0,.2); }
.sy-view-panel { display:none; }
.sy-view-panel.active { display:block; }

.sy-review-item { display:flex; align-items:center; gap:12px; padding:12px 16px; border-bottom:1px solid var(--border); }
.sy-review-item:last-child { border-bottom:none; }
.sy-review-subject { font-size:11px; color:var(--text-muted); margin-top:2px; }

.sy-wheel-stat-row { display:grid; grid-template-columns:repeat(3,1fr); gap:12px; margin-bottom:22px; }
.sy-wheel-stat-card { background:var(--bg-card); border:1px solid var(--border); border-radius:14px; padding:16px; text-align:center; }
.sy-wheel-stat-num { font-size:26px; font-weight:800; font-family:'Sora',sans-serif; color:var(--text-primary); }
.sy-wheel-stat-label { font-size:11px; color:var(--text-muted); text-transform:uppercase; letter-spacing:.5px; margin-top:4px; }

.sy-wheel-wrap { display:flex; flex-direction:column; align-items:center; gap:22px; padding:20px 0 10px; }
.sy-wheel-outer { position:relative; width:260px; height:260px; max-width:80vw; max-height:80vw; }
.sy-wheel-pointer {
  position:absolute; top:-8px; left:50%; transform:translateX(-50%); width:0; height:0;
  border-left:13px solid transparent; border-right:13px solid transparent; border-top:22px solid var(--accent);
  z-index:5; filter:drop-shadow(0 2px 5px rgba(0,0,0,.5));
}
.sy-wheel-dial {
  width:100%; height:100%; border-radius:50%; border:6px solid var(--bg-card);
  box-shadow:0 8px 30px rgba(0,0,0,.4), inset 0 0 0 2px rgba(255,255,255,.06);
  transition:transform 4s cubic-bezier(.17,.67,.16,.99); position:relative;
}
.sy-wheel-center {
  position:absolute; top:50%; left:50%; width:58px; height:58px; transform:translate(-50%,-50%);
  border-radius:50%; background:var(--bg-card); border:3px solid var(--border);
  display:flex; align-items:center; justify-content:center; font-size:24px; box-shadow:0 2px 10px rgba(0,0,0,.3);
}
.sy-wheel-spin-btn { min-width:200px; }
.sy-wheel-spin-btn:disabled { opacity:.6; cursor:not-allowed; }

.sy-wheel-result-card { display:none; width:100%; max-width:440px; margin:0 auto; }
.sy-wheel-result-card.show { display:block; animation:sywrFadeIn .3s ease both; }
@keyframes sywrFadeIn { from{opacity:0;transform:translateY(8px)} to{opacity:1;transform:translateY(0)} }
.sy-wheel-result-subject { font-size:11px; font-weight:700; color:var(--text-muted); text-transform:uppercase; letter-spacing:.5px; margin-bottom:8px; text-align:center; }
.sy-wheel-result-topic { font-size:17px; font-weight:700; color:var(--text-primary); margin-bottom:20px; text-align:center; line-height:1.5; }
.sy-wheel-rating-row { display:grid; grid-template-columns:repeat(2,1fr); gap:10px; }
@media (min-width:500px) { .sy-wheel-rating-row { grid-template-columns:repeat(4,1fr); } }
.sy-wheel-rate-btn { padding:12px 6px; border-radius:11px; border:none; font-size:12.5px; font-weight:700; cursor:pointer; color:#fff; transition:transform .15s; }
.sy-wheel-rate-btn:hover { transform:translateY(-2px); }
.sy-wr-again { background:linear-gradient(135deg,#ef4444,#dc2626); }
.sy-wr-hard  { background:linear-gradient(135deg,#f59e0b,#d97706); }
.sy-wr-good  { background:linear-gradient(135deg,#6366f1,#4f46e5); }
.sy-wr-easy  { background:linear-gradient(135deg,#10b981,#059669); }
</style>

<div class="sy-page-header">
  <div>
    <div class="sy-page-title">📘 Syllabus Tracker</div>
    <div class="sy-page-sub">Track how much of each subject's syllabus you've covered</div>
  </div>
</div>

<?php if (empty($subjects)): ?>
  <div class="card">
    <div class="empty-state">
      <div class="empty-icon">📚</div>
      <h3>No subjects yet</h3>
      <p>Add subjects first, then come back here to track your syllabus.</p>
      <a href="<?= SITE_URL ?>/subjects" class="btn btn-primary" style="margin-top:14px;display:inline-flex">Go to Subjects</a>
    </div>
  </div>
<?php else: ?>

<div class="sy-view-tabs">
  <button class="sy-view-tab active" data-view="subjects" onclick="sySwitchView('subjects')">📚 By Subject</button>
  <button class="sy-view-tab" data-view="review" onclick="sySwitchView('review')">🔖 Review Later (<?= count($difficultTopics) ?>)</button>
  <button class="sy-view-tab" data-view="wheel" onclick="sySwitchView('wheel')">🎡 Revision Wheel (<?= count($dueRevisionTopics) ?>)</button>
</div>

<div class="sy-view-panel active" id="syView-subjects">

<div class="sy-overall-card">
  <svg class="sy-overall-ring" width="64" height="64" viewBox="0 0 64 64">
    <circle cx="32" cy="32" r="27" fill="none" stroke="var(--border)" stroke-width="7"/>
    <circle cx="32" cy="32" r="27" fill="none" stroke="url(#syGrad)" stroke-width="7" stroke-linecap="round"
      stroke-dasharray="<?= round(2*M_PI*27) ?>" stroke-dashoffset="<?= round(2*M_PI*27 * (1 - $overallPct/100)) ?>"
      transform="rotate(-90 32 32)"/>
    <defs><linearGradient id="syGrad" x1="0" y1="0" x2="1" y2="1"><stop offset="0%" stop-color="#6366f1"/><stop offset="100%" stop-color="#a855f7"/></linearGradient></defs>
  </svg>
  <div>
    <div class="sy-overall-pct"><?= $overallPct ?>%</div>
    <div class="sy-overall-text"><?= $totalDone ?> of <?= $totalTopics ?> topics completed across all subjects</div>
  </div>
</div>

<div class="sy-subject-tabs" id="syTabs">
  <?php foreach ($subjects as $i => $s):
      $topics = $bySubject[$s['id']] ?? [];
      $done = count(array_filter($topics, fn($t) => $t['is_completed']));
      $pct  = count($topics) ? round($done/count($topics)*100) : 0;
  ?>
  <div class="sy-subject-tab <?= $i===0?'active':'' ?>" data-subid="<?= $s['id'] ?>" onclick="sySwitchTab(<?= $s['id'] ?>)">
    <span class="sy-subject-dot" style="background:<?= htmlspecialchars($s['color']) ?>"></span>
    <?= htmlspecialchars($s['name']) ?>
    <span class="sy-subject-pct"><?= count($topics) ? $pct.'%' : '—' ?></span>
  </div>
  <?php endforeach; ?>
</div>

<?php foreach ($subjects as $i => $s):
    $topics = $bySubject[$s['id']] ?? [];
    $done = count(array_filter($topics, fn($t) => $t['is_completed']));
    $pct  = count($topics) ? round($done/count($topics)*100) : 0;
    $grouped = [];
    foreach ($topics as $t) $grouped[$t['unit_name'] ?: 'General'][] = $t;
?>
<div class="sy-subject-panel" id="syPanel<?= $s['id'] ?>" style="<?= $i===0?'':'display:none' ?>">
  <div class="card">
    <div class="card-header">
      <div class="card-title">
        <span class="card-icon" style="background:<?= htmlspecialchars($s['color']) ?>22;color:<?= htmlspecialchars($s['color']) ?>">📖</span>
        <?= htmlspecialchars($s['name']) ?>
      </div>
      <?php if (!empty($hasTemplate[$s['id']])): ?>
      <button class="btn btn-primary btn-sm" onclick="syLoadOfficial(<?= $s['id'] ?>, this)">📥 Load Official Syllabus</button>
      <?php endif; ?>
    </div>

    <?php if (!empty($topics)): ?>
    <div class="sy-progress-wrap">
      <div class="sy-progress-label"><span><?= $done ?> / <?= count($topics) ?> completed</span><span><?= $pct ?>%</span></div>
      <div class="progress-bar"><div class="progress-fill" style="width:<?= $pct ?>%"></div></div>
    </div>

    <?php foreach ($grouped as $unit => $unitTopics): ?>
    <div class="sy-unit-block">
      <div class="sy-unit-title"><?= htmlspecialchars($unit) ?></div>
      <?php foreach ($unitTopics as $t): ?>
      <div class="sy-topic-row <?= $t['is_completed']?'done':'' ?>" id="syTopic<?= $t['id'] ?>">
        <div class="sy-check <?= $t['is_completed']?'checked':'' ?>" onclick="syToggle(<?= $t['id'] ?>)">
          <?php if ($t['is_completed']): ?><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="3"><polyline points="20 6 9 17 4 12"/></svg><?php endif; ?>
        </div>
        <div class="sy-topic-name"><?= htmlspecialchars($t['topic_name']) ?></div>
        <button class="sy-bookmark-btn <?= !empty($t['is_difficult'])?'bookmarked':'' ?>" onclick="syToggleDifficult(<?= $t['id'] ?>)" title="Mark as difficult / review later">
          <svg viewBox="0 0 24 24" fill="<?= !empty($t['is_difficult'])?'currentColor':'none' ?>" stroke="currentColor" stroke-width="2"><path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/></svg>
        </button>
        <button class="sy-topic-del" onclick="syDelete(<?= $t['id'] ?>)">✕</button>
      </div>
      <?php endforeach; ?>
    </div>
    <?php endforeach; ?>
    <?php else: ?>
    <div class="empty-state">
      <div class="empty-icon">📝</div>
      <h3>No topics yet</h3>
      <?php if (!empty($hasTemplate[$s['id']])): ?>
      <p>Click <strong>📥 Load Official Syllabus</strong> above to auto-fill this subject, or add topics manually below.</p>
      <?php else: ?>
      <p>Add topics manually below to start tracking this subject.</p>
      <?php endif; ?>
    </div>
    <?php endif; ?>

    <div class="sy-add-row">
      <input type="text" class="form-control" placeholder="Unit (e.g. Mechanics)" id="syUnitInput<?= $s['id'] ?>" style="max-width:180px">
      <textarea class="form-control" rows="1" placeholder="Topic name(s) — one per line to add many at once" id="syTopicInput<?= $s['id'] ?>"></textarea>
      <button class="btn btn-secondary" onclick="syAddTopic(<?= $s['id'] ?>)">+ Add Topic(s)</button>
      <div class="sy-add-hint">💡 Tip: paste or type several topics, one on each line, to add them all to this unit in one go.</div>
    </div>
  </div>
</div>
<?php endforeach; ?>

</div>

<div class="sy-view-panel" id="syView-review">
  <div class="card" style="padding:0">
    <?php if (empty($difficultTopics)): ?>
    <div class="empty-state">
      <div class="empty-icon">🔖</div>
      <h3>No topics bookmarked yet</h3>
      <p>Tap the 🔖 icon next to any topic to save it here for extra revision later.</p>
    </div>
    <?php else: foreach ($difficultTopics as $t):
      $sub = $subjectById[$t['subject_id']] ?? null;
    ?>
    <div class="sy-review-item" id="syReview<?= $t['id'] ?>">
      <div class="sy-check <?= $t['is_completed']?'checked':'' ?>" onclick="syToggle(<?= $t['id'] ?>, true)">
        <?php if ($t['is_completed']): ?><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="3"><polyline points="20 6 9 17 4 12"/></svg><?php endif; ?>
      </div>
      <div style="flex:1;min-width:0">
        <div class="sy-topic-name" style="<?= $t['is_completed']?'text-decoration:line-through;color:var(--text-muted)':'' ?>"><?= htmlspecialchars($t['topic_name']) ?></div>
        <div class="sy-review-subject">
          <?php if ($sub): ?><span class="sy-subject-dot" style="display:inline-block;background:<?= htmlspecialchars($sub['color']) ?>"></span> <?= htmlspecialchars($sub['name']) ?><?php endif; ?>
          <?= htmlspecialchars($t['unit_name'] ?: '') ?>
        </div>
      </div>
      <button class="sy-bookmark-btn bookmarked" onclick="syToggleDifficult(<?= $t['id'] ?>, true)" title="Remove from Review Later">
        <svg viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" stroke-width="2"><path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/></svg>
      </button>
    </div>
    <?php endforeach; endif; ?>
  </div>
</div>

<div class="sy-view-panel" id="syView-wheel">
  <div class="sy-wheel-stat-row">
    <div class="sy-wheel-stat-card"><div class="sy-wheel-stat-num"><?= count($dueRevisionTopics) ?></div><div class="sy-wheel-stat-label">Due Today</div></div>
    <div class="sy-wheel-stat-card"><div class="sy-wheel-stat-num"><?= count($inRevisionCycle) ?></div><div class="sy-wheel-stat-label">In Revision Cycle</div></div>
    <div class="sy-wheel-stat-card"><div class="sy-wheel-stat-num"><?= $totalDone ?></div><div class="sy-wheel-stat-label">Topics Completed</div></div>
  </div>

  <?php if (empty($dueRevisionTopics)): ?>
  <div class="card">
    <div class="empty-state">
      <div class="empty-icon">🎡</div>
      <h3>Nothing due for revision right now</h3>
      <p>Tick off topics as "complete" in <strong>By Subject</strong> — they'll join the Revision Wheel using spaced repetition, and pop up here exactly when it's time to review them again.</p>
    </div>
  </div>
  <?php else: ?>
  <div class="card">
    <div class="sy-wheel-wrap" id="wheelWrapMain">
      <div class="sy-wheel-outer">
        <div class="sy-wheel-pointer"></div>
        <div class="sy-wheel-dial" id="wheelDial">
          <div class="sy-wheel-center">🎡</div>
        </div>
      </div>
      <button class="btn btn-primary sy-wheel-spin-btn" id="wheelSpinBtn" onclick="wheelSpin()">🎯 Spin the Wheel</button>
    </div>

    <div class="sy-wheel-result-card" id="wheelResultCard">
      <div class="sy-wheel-result-subject" id="wheelResultSubject"></div>
      <div class="sy-wheel-result-topic" id="wheelResultTopic"></div>
      <div class="sy-wheel-rating-row">
        <button class="sy-wheel-rate-btn sy-wr-again" onclick="wheelRate(0)">Again<br><small style="font-weight:500;opacity:.85">&lt;1 day</small></button>
        <button class="sy-wheel-rate-btn sy-wr-hard" onclick="wheelRate(3)">Hard<br><small style="font-weight:500;opacity:.85">1 day</small></button>
        <button class="sy-wheel-rate-btn sy-wr-good" onclick="wheelRate(4)">Good<br><small style="font-weight:500;opacity:.85">a few days</small></button>
        <button class="sy-wheel-rate-btn sy-wr-easy" onclick="wheelRate(5)">Easy<br><small style="font-weight:500;opacity:.85">longer</small></button>
      </div>
    </div>

    <div id="wheelSummary" style="display:none"></div>
  </div>
  <?php endif; ?>
</div>

<?php endif; ?>

<script>
function sySwitchTab(subId) {
  document.querySelectorAll('.sy-subject-tab').forEach(t => t.classList.toggle('active', t.dataset.subid == subId));
  document.querySelectorAll('.sy-subject-panel').forEach(p => p.style.display = (p.id === 'syPanel'+subId) ? '' : 'none');
}

function sySwitchView(view) {
  document.querySelectorAll('.sy-view-tab').forEach(t => t.classList.toggle('active', t.dataset.view === view));
  document.querySelectorAll('.sy-view-panel').forEach(p => p.classList.toggle('active', p.id === 'syView-'+view));
}

async function syPost(data) {
  const fd = new FormData();
  for (const k in data) fd.append(k, data[k]);
  const res = await fetch(location.href, { method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'} });
  return res.json();
}

async function syToggle(id) {
  const row = document.getElementById('syTopic'+id) || document.getElementById('syReview'+id);
  const check = row.querySelector('.sy-check');
  const r = await syPost({ action:'toggle_topic', id });
  if (r.success) {
    if (row.classList.contains('sy-topic-row')) row.classList.toggle('done', !!r.is_completed);
    check.classList.toggle('checked', !!r.is_completed);
    check.innerHTML = r.is_completed ? '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="3"><polyline points="20 6 9 17 4 12"/></svg>' : '';
    setTimeout(()=>location.reload(), 350);
  }
}

async function syToggleDifficult(id) {
  const r = await syPost({ action:'toggle_difficult', id });
  if (r.success) location.reload();
}

async function syDelete(id) {
  if (!(await stConfirm('Delete this topic?'))) return;
  const r = await syPost({ action:'delete_topic', id });
  if (r.success) location.reload();
}

async function syAddTopic(subId) {
  const unitEl = document.getElementById('syUnitInput'+subId);
  const topicEl = document.getElementById('syTopicInput'+subId);
  const unit = unitEl.value.trim() || 'General';
  const topicText = topicEl.value.trim();
  if (!topicText) { topicEl.focus(); return; }
  const r = await syPost({ action:'add_topic', subject_id:subId, unit_name:unit, topic_name:topicText });
  if (r.success) location.reload();
  else alert(r.message);
}

async function syLoadOfficial(subId, btn) {
  btn.disabled = true;
  btn.textContent = '⏳ Loading...';
  const r = await syPost({ action:'load_official_syllabus', subject_id:subId });
  if (r.success) {
    if (r.added > 0) location.reload();
    else { alert(r.message); btn.disabled = false; btn.textContent = '📥 Load Official Syllabus'; }
  } else {
    alert(r.message);
    btn.disabled = false;
    btn.textContent = '📥 Load Official Syllabus';
  }
}

// Auto-grow topic textareas as the user types/pastes multiple lines
document.addEventListener('input', function(e) {
  if (e.target && e.target.id && e.target.id.startsWith('syTopicInput')) {
    e.target.style.height = 'auto';
    e.target.style.height = Math.min(e.target.scrollHeight, 160) + 'px';
  }
});

// ── Revision Wheel ──────────────────────────────────────────────────────
let wheelTopics = <?= json_encode(array_map(fn($t) => [
    'id'      => (int)$t['id'],
    'topic'   => $t['topic_name'],
    'subject' => $subjectById[$t['subject_id']]['name'] ?? '',
    'color'   => $subjectById[$t['subject_id']]['color'] ?? '#6366f1',
], $dueRevisionTopics)) ?>;
let wheelRotation = 0;
let wheelCurrentTopic = null;
let wheelSpinning = false;

function wheelBuildDial() {
  const dial = document.getElementById('wheelDial');
  if (!dial || wheelTopics.length === 0) return;
  const n = wheelTopics.length;
  const slice = 360 / n;
  const stops = wheelTopics.map((t, i) => `${t.color} ${i*slice}deg ${(i+1)*slice}deg`);
  dial.style.background = `conic-gradient(${stops.join(',')})`;
}
wheelBuildDial();

function wheelSpin() {
  if (wheelSpinning || wheelTopics.length === 0) return;
  wheelSpinning = true;
  document.getElementById('wheelSpinBtn').disabled = true;
  document.getElementById('wheelResultCard').classList.remove('show');

  const n = wheelTopics.length;
  const slice = 360 / n;
  const chosenIndex = Math.floor(Math.random() * n);
  wheelCurrentTopic = wheelTopics[chosenIndex];

  // Pointer is fixed at the top (0deg). Land the wheel so the chosen
  // slice's center ends up under the pointer, after a few extra full spins.
  const sliceCenter = chosenIndex * slice + slice / 2;
  const extraSpins = 5 + Math.floor(Math.random() * 3);
  const baseRotation = wheelRotation - (wheelRotation % 360);
  const targetRotation = baseRotation + extraSpins * 360 + (360 - sliceCenter);

  const dial = document.getElementById('wheelDial');
  dial.style.transform = `rotate(${targetRotation}deg)`;
  wheelRotation = targetRotation;

  setTimeout(() => {
    wheelSpinning = false;
    document.getElementById('wheelResultSubject').textContent = wheelCurrentTopic.subject;
    document.getElementById('wheelResultTopic').textContent = '🎯 ' + wheelCurrentTopic.topic;
    document.getElementById('wheelResultCard').classList.add('show');
  }, 4150);
}

async function wheelRate(quality) {
  if (!wheelCurrentTopic) return;
  const fd = new FormData();
  fd.append('action', 'wheel_rate');
  fd.append('id', wheelCurrentTopic.id);
  fd.append('quality', quality);
  fetch(location.href, { method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'} }).catch(()=>{});

  wheelTopics = wheelTopics.filter(t => t.id !== wheelCurrentTopic.id);
  wheelCurrentTopic = null;
  document.getElementById('wheelResultCard').classList.remove('show');
  document.getElementById('wheelSpinBtn').disabled = false;

  if (wheelTopics.length === 0) {
    document.getElementById('wheelWrapMain').style.display = 'none';
    const summary = document.getElementById('wheelSummary');
    summary.style.display = 'block';
    summary.innerHTML = `
      <div class="empty-state">
        <div class="empty-icon">🎉</div>
        <h3>All revised for today!</h3>
        <p>Great work — come back tomorrow for the next round on the Revision Wheel.</p>
      </div>`;
  } else {
    wheelBuildDial();
  }
}
</script>

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