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

// ── Safe self-migration ─────────────────────────────────────────────────
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS quiz_questions (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        subject_id INT DEFAULT NULL,
        question TEXT NOT NULL,
        option_a VARCHAR(500) NOT NULL,
        option_b VARCHAR(500) NOT NULL,
        option_c VARCHAR(500) NOT NULL,
        option_d VARCHAR(500) NOT NULL,
        correct_option ENUM('a','b','c','d') NOT NULL,
        explanation TEXT DEFAULT NULL,
        year VARCHAR(20) DEFAULT NULL,
        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 SET NULL
    ) ENGINE=InnoDB");
} catch (PDOException $e) {}

try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS quiz_attempts (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        subject_id INT DEFAULT NULL,
        total_questions INT NOT NULL,
        correct_count INT NOT NULL,
        score_percent DECIMAL(5,2) NOT NULL,
        taken_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
    ) ENGINE=InnoDB");
} catch (PDOException $e) {}

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

    if ($action === 'add_question') {
        $subId = (int)($_POST['subject_id'] ?? 0) ?: null;
        $q     = sanitize($_POST['question'] ?? '');
        $a     = sanitize($_POST['option_a'] ?? '');
        $b     = sanitize($_POST['option_b'] ?? '');
        $c     = sanitize($_POST['option_c'] ?? '');
        $d     = sanitize($_POST['option_d'] ?? '');
        $corr  = in_array($_POST['correct_option'] ?? '', ['a','b','c','d']) ? $_POST['correct_option'] : 'a';
        $exp   = sanitize($_POST['explanation'] ?? '');
        $year  = sanitize($_POST['year'] ?? '');
        if (!$q || !$a || !$b || !$c || !$d) jsonResponse(['success'=>false,'message'=>'Question and all 4 options are required.']);

        $pdo->prepare("INSERT INTO quiz_questions (user_id,subject_id,question,option_a,option_b,option_c,option_d,correct_option,explanation,year) VALUES (?,?,?,?,?,?,?,?,?,?)")
            ->execute([$uid,$subId,$q,$a,$b,$c,$d,$corr,$exp,$year]);
        jsonResponse(['success'=>true,'message'=>'Question added to your bank!']);
    }

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

    if ($action === 'start_quiz') {
        $subId = (int)($_POST['subject_id'] ?? 0) ?: null;
        $count = max(1, min(50, (int)($_POST['count'] ?? 10)));

        $sql = "SELECT id,question,option_a,option_b,option_c,option_d FROM quiz_questions WHERE user_id=?";
        $params = [$uid];
        if ($subId) { $sql .= " AND subject_id=?"; $params[] = $subId; }
        $sql .= " ORDER BY RAND() LIMIT " . $count;
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $questions = $stmt->fetchAll();

        if (empty($questions)) jsonResponse(['success'=>false,'message'=>'No questions found. Add some questions to your bank first!']);

        $_SESSION['quiz_active'] = [
            'subject_id'   => $subId,
            'question_ids' => array_column($questions, 'id'),
            'started_at'   => time(),
        ];
        jsonResponse(['success'=>true,'questions'=>$questions]);
    }

    if ($action === 'submit_quiz') {
        $session = $_SESSION['quiz_active'] ?? null;
        if (!$session) jsonResponse(['success'=>false,'message'=>'Quiz session expired. Please start again.']);

        $answers = json_decode($_POST['answers'] ?? '{}', true) ?: [];
        $ids = $session['question_ids'];
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $stmt = $pdo->prepare("SELECT id,question,option_a,option_b,option_c,option_d,correct_option,explanation FROM quiz_questions WHERE id IN ($placeholders) AND user_id=?");
        $stmt->execute(array_merge($ids, [$uid]));
        $qRows = $stmt->fetchAll();
        $byId = [];
        foreach ($qRows as $r) $byId[$r['id']] = $r;

        $correct = 0;
        $results = [];
        foreach ($ids as $qid) {
            if (!isset($byId[$qid])) continue;
            $row = $byId[$qid];
            $selected = $answers[$qid] ?? null;
            $isCorrect = ($selected === $row['correct_option']);
            if ($isCorrect) $correct++;
            $results[] = [
                'id' => $qid,
                'question' => $row['question'],
                'options' => ['a'=>$row['option_a'],'b'=>$row['option_b'],'c'=>$row['option_c'],'d'=>$row['option_d']],
                'correct_option' => $row['correct_option'],
                'selected' => $selected,
                'is_correct' => $isCorrect,
                'explanation' => $row['explanation'],
            ];
        }

        $total = count($ids);
        $pct = $total ? round($correct / $total * 100, 2) : 0;

        $pdo->prepare("INSERT INTO quiz_attempts (user_id,subject_id,total_questions,correct_count,score_percent) VALUES (?,?,?,?,?)")
            ->execute([$uid, $session['subject_id'], $total, $correct, $pct]);

        unset($_SESSION['quiz_active']);
        jsonResponse(['success'=>true,'correct'=>$correct,'total'=>$total,'score_percent'=>$pct,'results'=>$results]);
    }
}

// ── 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();

$questions = $pdo->prepare("SELECT q.*, s.name as subject_name, s.color as subject_color FROM quiz_questions q LEFT JOIN subjects s ON q.subject_id=s.id WHERE q.user_id=? ORDER BY q.created_at DESC");
$questions->execute([$uid]); $questions = $questions->fetchAll();

$attempts = $pdo->prepare("SELECT a.*, s.name as subject_name, s.color as subject_color FROM quiz_attempts a LEFT JOIN subjects s ON a.subject_id=s.id WHERE a.user_id=? ORDER BY a.taken_at DESC LIMIT 30");
$attempts->execute([$uid]); $attempts = $attempts->fetchAll();

$qCountBySubject = [];
foreach ($questions as $q) $qCountBySubject[$q['subject_id'] ?: 0] = ($qCountBySubject[$q['subject_id'] ?: 0] ?? 0) + 1;

require_once 'includes/header.php';
renderHeader('Quiz Practice', 'quiz');
?>

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

.qz-tab-bar { display:flex; gap:4px; background:var(--bg-secondary); border:1px solid var(--border); border-radius:12px; padding:4px; margin-bottom:22px; }
.qz-tab-btn { flex:1; padding:8px 18px; 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:7px; white-space:nowrap; font-family:inherit; }
.qz-tab-btn.active { background:var(--bg-card); color:var(--text-primary); box-shadow:0 1px 4px rgba(0,0,0,.2); }
.qz-tab-panel { display:none; }
.qz-tab-panel.active { display:block; }

.qz-setup-grid { display:grid; grid-template-columns:1fr 1fr; gap:14px; margin-bottom:18px; }
@media (max-width:600px){ .qz-setup-grid{ grid-template-columns:1fr; } }

.qz-question-box { background:var(--bg-card); border:1px solid var(--border); border-radius:14px; padding:22px; margin-bottom:16px; }
.qz-qnum { font-size:11px; font-weight:700; color:var(--accent); text-transform:uppercase; letter-spacing:.6px; margin-bottom:8px; }
.qz-qtext { font-size:15px; font-weight:600; color:var(--text-primary); margin-bottom:16px; line-height:1.6; }
.qz-option { display:flex; align-items:center; gap:12px; padding:12px 14px; border-radius:10px; border:1.5px solid var(--border); margin-bottom:8px; cursor:pointer; transition:all .15s; }
.qz-option:hover { border-color:var(--accent); background:rgba(99,102,241,.05); }
.qz-option.selected { border-color:var(--accent); background:rgba(99,102,241,.1); }
.qz-option-letter { width:26px; height:26px; border-radius:8px; background:var(--bg-secondary); display:flex; align-items:center; justify-content:center; font-size:12px; font-weight:700; color:var(--text-secondary); flex-shrink:0; }
.qz-option.selected .qz-option-letter { background:var(--gradient); color:#fff; }
.qz-option-text { font-size:13.5px; color:var(--text-primary); }

.qz-option.correct { border-color:var(--success); background:rgba(16,185,129,.08); }
.qz-option.wrong { border-color:var(--danger); background:rgba(239,68,68,.08); }
.qz-option.correct .qz-option-letter { background:var(--success); color:#fff; }
.qz-option.wrong .qz-option-letter { background:var(--danger); color:#fff; }
.qz-explanation { margin-top:12px; padding:12px 14px; background:rgba(99,102,241,.06); border:1px solid rgba(99,102,241,.15); border-radius:10px; font-size:12.5px; color:var(--text-secondary); line-height:1.6; }

.qz-score-hero { text-align:center; padding:32px 20px; }
.qz-score-num { font-size:52px; font-weight:900; font-family:'Sora',sans-serif; background:var(--gradient); -webkit-background-clip:text; background-clip:text; -webkit-text-fill-color:transparent; }
.qz-score-sub { font-size:14px; color:var(--text-muted); margin-top:6px; }

.qz-bank-item { display:flex; align-items:flex-start; gap:14px; padding:14px 18px; border-bottom:1px solid var(--border); }
.qz-bank-item:last-child { border-bottom:none; }
.qz-bank-q { font-size:13px; font-weight:600; color:var(--text-primary); margin-bottom:4px; }
.qz-bank-opts { font-size:12px; color:var(--text-muted); }
.qz-bank-correct { color:var(--success); font-weight:700; }

.qz-history-row { display:flex; align-items:center; justify-content:space-between; padding:12px 16px; border-bottom:1px solid var(--border); font-size:13px; }
.qz-history-row:last-child { border-bottom:none; }
.qz-score-badge { font-weight:700; padding:3px 10px; border-radius:99px; font-size:12px; }
.qz-score-badge.hi { background:rgba(16,185,129,.12); color:#34d399; }
.qz-score-badge.mid { background:rgba(245,158,11,.12); color:#fbbf24; }
.qz-score-badge.lo { background:rgba(239,68,68,.12); color:#f87171; }

.cs-overlay { position:fixed; inset:0; background:radial-gradient(ellipse at center, rgba(30,24,10,.55) 0%, rgba(0,0,0,.88) 100%); backdrop-filter:blur(14px) saturate(140%); -webkit-backdrop-filter:blur(14px) saturate(140%); display:none; align-items:center; justify-content:center; z-index:9999; padding:20px; animation:csFade .35s ease; }
@keyframes csFade { from{opacity:0;} to{opacity:1;} }
.cs-modal { position:relative; background:linear-gradient(160deg, rgba(40,32,14,.55) 0%, rgba(18,16,12,.65) 100%); border:1px solid rgba(212,175,55,.35); border-radius:24px; padding:46px 36px; max-width:400px; width:100%; text-align:center; backdrop-filter:blur(20px); -webkit-backdrop-filter:blur(20px); box-shadow:0 25px 70px rgba(0,0,0,.55), 0 0 0 1px rgba(255,215,120,.06) inset, 0 1px 0 rgba(255,235,180,.15) inset; animation:csPop .45s cubic-bezier(.2,.9,.25,1.1); overflow:hidden; }
.cs-modal::before { content:''; position:absolute; top:-40%; left:-20%; width:140%; height:140%; background:conic-gradient(from 0deg, transparent, rgba(212,175,55,.18), transparent 30%); animation:csSheen 6s linear infinite; pointer-events:none; }
.cs-modal::after { content:''; position:absolute; inset:0; border-radius:24px; padding:1px; background:linear-gradient(135deg, rgba(255,223,140,.6), rgba(212,175,55,0) 40%, rgba(212,175,55,0) 60%, rgba(255,223,140,.4)); -webkit-mask:linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0); -webkit-mask-composite:xor; mask-composite:exclude; pointer-events:none; }
@keyframes csSheen { to { transform:rotate(360deg); } }
@keyframes csPop { from{opacity:0; transform:scale(.9) translateY(16px);} to{opacity:1; transform:scale(1) translateY(0);} }
.cs-emoji { position:relative; font-size:50px; margin-bottom:16px; filter:drop-shadow(0 0 18px rgba(255,205,90,.55)); animation:csFloat 3s ease-in-out infinite; }
@keyframes csFloat { 0%,100%{transform:translateY(0);} 50%{transform:translateY(-6px);} }
.cs-title { position:relative; font-size:24px; font-weight:800; font-family:'Sora',sans-serif; margin-bottom:12px; letter-spacing:.3px; background:linear-gradient(135deg,#fff3cf,#d4af37 45%,#f6e27a 65%,#b8860b); -webkit-background-clip:text; background-clip:text; -webkit-text-fill-color:transparent; }
.cs-desc { position:relative; font-size:14px; color:rgba(240,225,190,.75); line-height:1.7; margin-bottom:28px; }
.cs-btn { position:relative; display:inline-flex; align-items:center; justify-content:center; gap:8px; width:100%; padding:14px 20px; border:1px solid rgba(255,223,140,.5); border-radius:14px; background:linear-gradient(135deg,#f6e27a,#d4af37 50%,#b8860b); color:#241a05; font-size:14px; font-weight:700; font-family:'Sora',sans-serif; letter-spacing:.2px; cursor:pointer; box-shadow:0 10px 30px rgba(212,175,55,.35), 0 1px 0 rgba(255,245,210,.6) inset; transition:transform .18s ease, box-shadow .18s ease; }
.cs-btn:hover { transform:translateY(-2px); box-shadow:0 14px 36px rgba(212,175,55,.45), 0 1px 0 rgba(255,245,210,.7) inset; }
.cs-btn:active { transform:translateY(0); }
</style>

<div class="cs-overlay" id="csOverlay">
  <div class="cs-modal">
    <div class="cs-emoji">✨</div>
    <div class="cs-title">Coming Soon</div>
    <p class="cs-desc">Quiz Practice is being polished behind the scenes. It'll be ready before you know it.</p>
    <button class="cs-btn" onclick="csGoBack()">← Go Back</button>
  </div>
</div>
<script>
function csGoBack() {
  if (document.referrer && document.referrer.indexOf(location.host) !== -1) {
    window.location.href = document.referrer;
  } else if (window.history.length > 1) {
    window.history.back();
  } else {
    window.location.href = '<?= SITE_URL ?>/dashboard';
  }
}
</script>

<div class="qz-page-header">
  <div>
    <div class="qz-page-title">🧠 Quiz Practice</div>
    <div class="qz-page-sub">Build your own MCQ bank from past papers and test yourself</div>
  </div>
</div>

<div class="qz-tab-bar">
  <button class="qz-tab-btn active" data-tab="practice" onclick="qzSwitchTab('practice')">▶️ Practice</button>
  <button class="qz-tab-btn" data-tab="bank" onclick="qzSwitchTab('bank')">📋 My Questions <span class="nf-tab-count" style="display:inline-flex;align-items:center;justify-content:center;min-width:18px;height:18px;padding:0 5px;border-radius:99px;background:rgba(99,102,241,.15);color:var(--accent);font-size:10px;font-weight:800;"><?= count($questions) ?></span></button>
  <button class="qz-tab-btn" data-tab="history" onclick="qzSwitchTab('history')">📊 History</button>
</div>

<!-- ═══════════ PRACTICE TAB ═══════════ -->
<div class="qz-tab-panel active" id="qzPanel-practice">

  <div id="qzSetup">
    <div class="card">
      <div class="card-header"><div class="card-title">⚡ Start a Practice Quiz</div></div>
      <div class="qz-setup-grid">
        <div class="form-group" style="margin-bottom:0">
          <label style="font-size:12px;color:var(--text-muted);margin-bottom:6px;display:block">Subject</label>
          <select class="form-control" id="qzSubjectSelect">
            <option value="0">All Subjects</option>
            <?php foreach ($subjects as $s): ?>
            <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['name']) ?> (<?= $qCountBySubject[$s['id']] ?? 0 ?> questions)</option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="form-group" style="margin-bottom:0">
          <label style="font-size:12px;color:var(--text-muted);margin-bottom:6px;display:block">Number of Questions</label>
          <select class="form-control" id="qzCountSelect">
            <option value="5">5 Questions</option>
            <option value="10" selected>10 Questions</option>
            <option value="20">20 Questions</option>
            <option value="30">30 Questions</option>
          </select>
        </div>
      </div>
      <button class="btn btn-primary btn-full" onclick="qzStartQuiz()">🚀 Start Quiz</button>
      <?php if (empty($questions)): ?>
      <p style="font-size:12px;color:var(--text-muted);margin-top:12px;text-align:center">You don't have any questions yet — add some in the "My Questions" tab first.</p>
      <?php endif; ?>
    </div>
  </div>

  <div id="qzActive" style="display:none">
    <div id="qzQuestionsWrap"></div>
    <button class="btn btn-primary btn-full" onclick="qzSubmitQuiz()">✅ Submit Quiz</button>
  </div>

  <div id="qzResults" style="display:none"></div>

</div>

<!-- ═══════════ MY QUESTIONS TAB ═══════════ -->
<div class="qz-tab-panel" id="qzPanel-bank">
  <div class="card">
    <div class="card-header">
      <div class="card-title">➕ Add New Question</div>
    </div>
    <div class="form-group">
      <select class="form-control" id="qNewSubject">
        <option value="0">No subject</option>
        <?php foreach ($subjects as $s): ?>
        <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="form-group"><textarea class="form-control" id="qNewQuestion" rows="2" placeholder="Question text"></textarea></div>
    <div class="qz-setup-grid">
      <input class="form-control" id="qNewA" placeholder="Option A">
      <input class="form-control" id="qNewB" placeholder="Option B">
      <input class="form-control" id="qNewC" placeholder="Option C">
      <input class="form-control" id="qNewD" placeholder="Option D">
    </div>
    <div class="qz-setup-grid" style="margin-top:14px">
      <div class="form-group" style="margin-bottom:0">
        <label style="font-size:12px;color:var(--text-muted);margin-bottom:6px;display:block">Correct Answer</label>
        <select class="form-control" id="qNewCorrect">
          <option value="a">A</option><option value="b">B</option><option value="c">C</option><option value="d">D</option>
        </select>
      </div>
      <input class="form-control" id="qNewYear" placeholder="Year (optional, e.g. 2023)" style="align-self:end">
    </div>
    <div class="form-group" style="margin-top:14px"><textarea class="form-control" id="qNewExplanation" rows="2" placeholder="Explanation (optional — shown after answering)"></textarea></div>
    <button class="btn btn-primary" onclick="qzAddQuestion()">Add to Bank</button>
  </div>

  <div class="card" style="margin-top:16px;padding:0">
    <?php if (empty($questions)): ?>
    <div class="empty-state"><div class="empty-icon">🧠</div><h3>No questions yet</h3><p>Add MCQs from your past papers above to build your practice bank.</p></div>
    <?php else: foreach ($questions as $q): ?>
    <div class="qz-bank-item">
      <div style="flex:1;min-width:0">
        <div class="qz-bank-q"><?= htmlspecialchars($q['question']) ?></div>
        <div class="qz-bank-opts">
          A. <?= htmlspecialchars($q['option_a']) ?> · B. <?= htmlspecialchars($q['option_b']) ?> · C. <?= htmlspecialchars($q['option_c']) ?> · D. <?= htmlspecialchars($q['option_d']) ?>
          <br>Correct: <span class="qz-bank-correct"><?= strtoupper($q['correct_option']) ?></span>
          <?php if ($q['subject_name']): ?> · <span class="badge badge-purple"><?= htmlspecialchars($q['subject_name']) ?></span><?php endif; ?>
          <?php if ($q['year']): ?> · <?= htmlspecialchars($q['year']) ?><?php endif; ?>
        </div>
      </div>
      <button class="note-action-btn del" onclick="qzDeleteQuestion(<?= $q['id'] ?>)">✕</button>
    </div>
    <?php endforeach; endif; ?>
  </div>
</div>

<!-- ═══════════ HISTORY TAB ═══════════ -->
<div class="qz-tab-panel" id="qzPanel-history">
  <div class="card" style="padding:0">
    <?php if (empty($attempts)): ?>
    <div class="empty-state"><div class="empty-icon">📊</div><h3>No quiz attempts yet</h3><p>Your practice quiz history will show up here.</p></div>
    <?php else: foreach ($attempts as $a):
      $pct = (float)$a['score_percent'];
      $cls = $pct >= 75 ? 'hi' : ($pct >= 50 ? 'mid' : 'lo');
    ?>
    <div class="qz-history-row">
      <div>
        <div style="font-weight:600;color:var(--text-primary)"><?= htmlspecialchars($a['subject_name'] ?? 'All Subjects') ?></div>
        <div style="font-size:11px;color:var(--text-muted)"><?= date('M j, Y — g:i A', strtotime($a['taken_at'])) ?> · <?= $a['correct_count'] ?>/<?= $a['total_questions'] ?> correct</div>
      </div>
      <span class="qz-score-badge <?= $cls ?>"><?= $pct ?>%</span>
    </div>
    <?php endforeach; endif; ?>
  </div>
</div>

<script>
function qzSwitchTab(tab) {
  document.querySelectorAll('.qz-tab-btn').forEach(b => b.classList.toggle('active', b.dataset.tab === tab));
  document.querySelectorAll('.qz-tab-panel').forEach(p => p.classList.toggle('active', p.id === 'qzPanel-'+tab));
}

async function qzPost(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 qzAddQuestion() {
  const payload = {
    action: 'add_question',
    subject_id: document.getElementById('qNewSubject').value,
    question: document.getElementById('qNewQuestion').value.trim(),
    option_a: document.getElementById('qNewA').value.trim(),
    option_b: document.getElementById('qNewB').value.trim(),
    option_c: document.getElementById('qNewC').value.trim(),
    option_d: document.getElementById('qNewD').value.trim(),
    correct_option: document.getElementById('qNewCorrect').value,
    explanation: document.getElementById('qNewExplanation').value.trim(),
    year: document.getElementById('qNewYear').value.trim(),
  };
  if (!payload.question || !payload.option_a || !payload.option_b || !payload.option_c || !payload.option_d) {
    alert('Please fill in the question and all 4 options.'); return;
  }
  const r = await qzPost(payload);
  if (r.success) location.reload();
  else alert(r.message);
}

async function qzDeleteQuestion(id) {
  if (!(await stConfirm('Delete this question?'))) return;
  const r = await qzPost({ action:'delete_question', id });
  if (r.success) location.reload();
}

let qzCurrentQuestions = [];
let qzSelectedAnswers = {};

async function qzStartQuiz() {
  const subject_id = document.getElementById('qzSubjectSelect').value;
  const count = document.getElementById('qzCountSelect').value;
  const r = await qzPost({ action:'start_quiz', subject_id, count });
  if (!r.success) { alert(r.message); return; }
  qzCurrentQuestions = r.questions;
  qzSelectedAnswers = {};
  renderQuizQuestions();
  document.getElementById('qzSetup').style.display = 'none';
  document.getElementById('qzActive').style.display = 'block';
  document.getElementById('qzResults').style.display = 'none';
}

function renderQuizQuestions() {
  const wrap = document.getElementById('qzQuestionsWrap');
  wrap.innerHTML = qzCurrentQuestions.map((q, i) => `
    <div class="qz-question-box">
      <div class="qz-qnum">Question ${i+1} of ${qzCurrentQuestions.length}</div>
      <div class="qz-qtext">${escQz(q.question)}</div>
      ${['a','b','c','d'].map(letter => `
        <div class="qz-option" data-qid="${q.id}" data-letter="${letter}" onclick="qzSelectOption(${q.id}, '${letter}', this)">
          <span class="qz-option-letter">${letter.toUpperCase()}</span>
          <span class="qz-option-text">${escQz(q['option_'+letter])}</span>
        </div>
      `).join('')}
    </div>
  `).join('');
}

function qzSelectOption(qid, letter, el) {
  qzSelectedAnswers[qid] = letter;
  document.querySelectorAll(`.qz-option[data-qid="${qid}"]`).forEach(o => o.classList.remove('selected'));
  el.classList.add('selected');
}

function escQz(str) {
  const d = document.createElement('div'); d.textContent = str; return d.innerHTML;
}

async function qzSubmitQuiz() {
  const unanswered = qzCurrentQuestions.filter(q => !qzSelectedAnswers[q.id]).length;
  if (unanswered > 0 && !(await stConfirm(unanswered + ' question(s) left unanswered. Submit anyway?', {icon:'📝', okStyle:'primary', okLabel:'Submit'}))) return;

  const r = await qzPost({ action:'submit_quiz', answers: JSON.stringify(qzSelectedAnswers) });
  if (!r.success) { alert(r.message); return; }

  document.getElementById('qzActive').style.display = 'none';
  const resultsEl = document.getElementById('qzResults');
  resultsEl.style.display = 'block';

  let html = `
    <div class="card">
      <div class="qz-score-hero">
        <div class="qz-score-num">${r.score_percent}%</div>
        <div class="qz-score-sub">${r.correct} out of ${r.total} correct</div>
        <button class="btn btn-primary" style="margin-top:18px" onclick="location.reload()">🔄 New Quiz</button>
      </div>
    </div>
  `;

  r.results.forEach((res, i) => {
    html += `<div class="qz-question-box">
      <div class="qz-qnum">Question ${i+1} — ${res.is_correct ? '✅ Correct' : '❌ Incorrect'}</div>
      <div class="qz-qtext">${escQz(res.question)}</div>
      ${['a','b','c','d'].map(letter => {
        let cls = '';
        if (letter === res.correct_option) cls = 'correct';
        else if (letter === res.selected) cls = 'wrong';
        return `<div class="qz-option ${cls}">
          <span class="qz-option-letter">${letter.toUpperCase()}</span>
          <span class="qz-option-text">${escQz(res.options[letter])}</span>
        </div>`;
      }).join('')}
      ${res.explanation ? `<div class="qz-explanation">💡 ${escQz(res.explanation)}</div>` : ''}
    </div>`;
  });

  resultsEl.innerHTML = html;
}
</script>

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