<?php
declare(strict_types=1);

session_start();

if (!isset($_SESSION['student_id'])) {
    header('Location: student-login.php');
    exit;
}

require_once __DIR__ . '/../config/database.php';
$pdo = getDbConnection();

$bookSlug = trim((string)($_GET['book'] ?? ''));
$levelSlug = trim((string)($_GET['level'] ?? ''));
$levelId = max(0, (int)($_GET['level_id'] ?? 0));
$unitId = max(0, (int)($_GET['unit_id'] ?? ($_GET['id'] ?? 0)));
$lessonId = max(0, (int)($_GET['lesson_id'] ?? 0));
$activityId = max(0, (int)($_GET['activity_id'] ?? ($_GET['activity'] ?? 0)));

if (
    $bookSlug === ''
    || $levelId <= 0
    || $unitId <= 0
    || $lessonId <= 0
    || $activityId <= 0
) {
    header('Location: student-learning.php');
    exit;
}

function sqColumns(PDO $pdo, string $table): array
{
    $stmt = $pdo->prepare(
        "SELECT COUNT(*)
         FROM information_schema.TABLES
         WHERE TABLE_SCHEMA = DATABASE()
           AND TABLE_NAME = ?"
    );
    $stmt->execute([$table]);

    if ((int)$stmt->fetchColumn() === 0) {
        return [];
    }

    $rows = $pdo->query("SHOW COLUMNS FROM `{$table}`")->fetchAll(PDO::FETCH_ASSOC);
    return array_column($rows, null, 'Field');
}

function sqAssetUrl(string $path): string
{
    $path = trim($path);

    if ($path === '') {
        return '';
    }

    if (
        str_starts_with($path, 'http://')
        || str_starts_with($path, 'https://')
        || str_starts_with($path, 'data:')
        || str_starts_with($path, '/')
    ) {
        return $path;
    }

    return '/EnglishSpeak/' . ltrim($path, './');
}

$activityColumns = sqColumns($pdo, 'activities');
$relationColumns = sqColumns($pdo, 'flashcard_set_words');
$wordColumns = sqColumns($pdo, 'words');

if (
    $activityColumns === []
    || $relationColumns === []
    || $wordColumns === []
    || !isset($activityColumns['flashcard_set_id'])
) {
    http_response_code(500);
    exit('Thiếu bảng dữ liệu Quiz.');
}

$activityTitleColumn = isset($activityColumns['title'])
    ? 'title'
    : (isset($activityColumns['name']) ? 'name' : null);

$setFk = isset($relationColumns['set_id'])
    ? 'set_id'
    : (isset($relationColumns['flashcard_set_id']) ? 'flashcard_set_id' : null);

$wordFk = isset($relationColumns['word_id']) ? 'word_id' : null;

$orderColumn = isset($relationColumns['order_no'])
    ? 'order_no'
    : (isset($relationColumns['sort_order']) ? 'sort_order' : 'id');

$wordTextColumn = isset($wordColumns['word'])
    ? 'word'
    : (isset($wordColumns['term']) ? 'term' : null);

$imageColumn = isset($wordColumns['image_path'])
    ? 'image_path'
    : (isset($wordColumns['image']) ? 'image' : null);

$audioColumn = isset($wordColumns['audio_us_path'])
    ? 'audio_us_path'
    : (isset($wordColumns['audio_path'])
        ? 'audio_path'
        : (isset($wordColumns['audio']) ? 'audio' : null));

if (
    $activityTitleColumn === null
    || $setFk === null
    || $wordFk === null
    || $wordTextColumn === null
) {
    http_response_code(500);
    exit('Cấu trúc dữ liệu Quiz chưa đầy đủ.');
}

$activityStatusWhere = isset($activityColumns['status'])
    ? "AND a.status = 'active'"
    : '';

$passingScoreSelect = isset($activityColumns['passing_score'])
    ? 'a.passing_score AS passing_score,'
    : '70 AS passing_score,';

$contextStmt = $pdo->prepare(
    "SELECT
        a.id AS activity_id,
        a.flashcard_set_id,
        a.xp_reward AS xp_reward,
        {$passingScoreSelect}
        a.`{$activityTitleColumn}` AS activity_title,

        le.id AS lesson_id,
        le.lesson_number,
        le.title AS lesson_title,

        u.id AS unit_id,
        u.unit_number,
        u.title AS unit_title,

        l.id AS level_id,
        l.name AS level_name,
        l.slug AS level_slug,

        b.id AS book_id,
        b.name AS book_name,
        b.slug AS book_slug
     FROM activities a
     INNER JOIN lessons le
        ON le.id = a.lesson_id
     INNER JOIN units u
        ON u.id = le.unit_id
     INNER JOIN levels l
        ON l.id = u.level_id
     INNER JOIN books b
        ON b.id = l.book_id
     WHERE a.id = ?
       AND le.id = ?
       AND u.id = ?
       AND l.id = ?
       AND b.slug = ?
       {$activityStatusWhere}
     LIMIT 1"
);
$contextStmt->execute([
    $activityId,
    $lessonId,
    $unitId,
    $levelId,
    $bookSlug,
]);
$activity = $contextStmt->fetch(PDO::FETCH_ASSOC);

if (!$activity) {
    http_response_code(404);
    exit('Không tìm thấy Quiz trong cấp độ đã chọn.');
}

$passingScore = max(0, min(100, (int)($activity['passing_score'] ?? 70)));
$isPreview = (int)($_GET['preview'] ?? 0) === 1;

/*
 * Activity Settings.
 * Prefer settings already loaded by Student Runtime, then fall back to DB
 * so direct links and Preview still work correctly.
 */
$activitySettings = $_SESSION['activity_settings_data'] ?? [];

if ($activitySettings === [] && sqColumns($pdo, 'activity_settings') !== []) {
    $settingsStmt = $pdo->prepare(
        'SELECT settings_json FROM activity_settings WHERE activity_id = ? LIMIT 1'
    );
    $settingsStmt->execute([$activityId]);
    $settingsJson = $settingsStmt->fetchColumn();

    if (is_string($settingsJson) && $settingsJson !== '') {
        $decodedSettings = json_decode($settingsJson, true);

        if (is_array($decodedSettings)) {
            $activitySettings = $decodedSettings;
        }
    }
}

$resourceType = strtolower(trim((string)($activitySettings['resource_type'] ?? '')));
$resourceId = max(0, (int)($activitySettings['resource_id'] ?? 0));

$flashcardSetId = (int)$activity['flashcard_set_id'];

if ($resourceType === 'flashcard_set' && $resourceId > 0) {
    $flashcardSetId = $resourceId;
}

$questionCount = max(
    1,
    min(
        100,
        (int)(
            $activitySettings['question_count']
            ?? $activitySettings['word_count']
            ?? $activitySettings['cards_per_session']
            ?? 10
        )
    )
);

$quizSettings = [
    'shuffle_questions' => filter_var(
        $activitySettings['shuffle'] ?? true,
        FILTER_VALIDATE_BOOL
    ),
    'shuffle_options' => filter_var(
        $activitySettings['shuffle_options'] ?? true,
        FILTER_VALIDATE_BOOL
    ),
    'allow_retry' => filter_var(
        $activitySettings['allow_retry'] ?? true,
        FILTER_VALIDATE_BOOL
    ),
];

$passingScore = max(
    0,
    min(100, (int)($activitySettings['passing_score'] ?? $passingScore))
);

/*
 * Student Progress endpoint for Quiz.
 * - preview=1: never saves.
 * - best_score never decreases.
 * - attempt_count increases once per finished attempt.
 * - XP is intentionally untouched in this step.
 */
if (
    ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST'
    && (string)($_POST['action'] ?? '') === 'save_activity_progress'
) {
    header('Content-Type: application/json; charset=utf-8');

    if ($isPreview) {
        echo json_encode([
            'ok' => true,
            'saved' => false,
            'reason' => 'preview',
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $studentId = max(0, (int)($_SESSION['student_id'] ?? 0));
    $score = max(0, min(100, (int)($_POST['score'] ?? 0)));

    if ($studentId <= 0) {
        http_response_code(401);
        echo json_encode(['ok' => false, 'message' => 'Chưa đăng nhập học sinh.'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $progressColumns = sqColumns($pdo, 'student_content_progress');
    $requiredProgressColumns = [
        'student_id',
        'content_type',
        'content_id',
        'status',
        'best_score',
        'attempt_count',
        'xp_earned',
        'first_started_at',
        'completed_at',
        'last_attempt_at',
    ];

    foreach ($requiredProgressColumns as $requiredColumn) {
        if (!isset($progressColumns[$requiredColumn])) {
            http_response_code(500);
            echo json_encode([
                'ok' => false,
                'message' => 'Bảng student_content_progress thiếu cột: ' . $requiredColumn,
            ], JSON_UNESCAPED_UNICODE);
            exit;
        }
    }

    $passed = $score >= $passingScore;

    try {
        $pdo->beginTransaction();

        $existingStmt = $pdo->prepare(
            "SELECT id, status, best_score, attempt_count
             FROM student_content_progress
             WHERE student_id = ?
               AND content_type = 'activity'
               AND content_id = ?
             LIMIT 1
             FOR UPDATE"
        );
        $existingStmt->execute([$studentId, $activityId]);
        $existing = $existingStmt->fetch(PDO::FETCH_ASSOC);

        if ($existing) {
            $updateStmt = $pdo->prepare(
                "UPDATE student_content_progress
                 SET
                    status = CASE
                        WHEN status = 'completed' OR ? = 1 THEN 'completed'
                        ELSE 'in_progress'
                    END,
                    best_score = GREATEST(COALESCE(best_score, 0), ?),
                    attempt_count = COALESCE(attempt_count, 0) + 1,
                    completed_at = CASE
                        WHEN ? = 1 THEN COALESCE(completed_at, NOW())
                        ELSE completed_at
                    END,
                    last_attempt_at = NOW()
                 WHERE id = ?"
            );
            $updateStmt->execute([
                $passed ? 1 : 0,
                $score,
                $passed ? 1 : 0,
                (int)$existing['id'],
            ]);
        } else {
            $insertStmt = $pdo->prepare(
                "INSERT INTO student_content_progress (
                    student_id,
                    content_type,
                    content_id,
                    status,
                    best_score,
                    attempt_count,
                    xp_earned,
                    first_started_at,
                    completed_at,
                    last_attempt_at
                 ) VALUES (
                    ?,
                    'activity',
                    ?,
                    ?,
                    ?,
                    1,
                    0,
                    NOW(),
                    CASE WHEN ? = 1 THEN NOW() ELSE NULL END,
                    NOW()
                 )"
            );
            $insertStmt->execute([
                $studentId,
                $activityId,
                $passed ? 'completed' : 'in_progress',
                $score,
                $passed ? 1 : 0,
            ]);
        }

        $resultStmt = $pdo->prepare(
            "SELECT status, best_score, attempt_count, completed_at, last_attempt_at
             FROM student_content_progress
             WHERE student_id = ?
               AND content_type = 'activity'
               AND content_id = ?
             LIMIT 1"
        );
        $resultStmt->execute([$studentId, $activityId]);
        $progress = $resultStmt->fetch(PDO::FETCH_ASSOC) ?: [];

        $pdo->commit();

        echo json_encode([
            'ok' => true,
            'saved' => true,
            'passed' => $passed,
            'passing_score' => $passingScore,
            'progress' => $progress,
        ], JSON_UNESCAPED_UNICODE);
        exit;
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }

        http_response_code(500);
        echo json_encode([
            'ok' => false,
            'message' => 'Không thể lưu tiến trình Quiz.',
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }
}

$xpReward = max(0, (int)($activity['xp_reward'] ?? 0));
if ($xpReward <= 0) {
    $xpReward = 20;
}

$imageSelect = $imageColumn !== null
    ? "w.`{$imageColumn}` AS image_path"
    : "'' AS image_path";

$audioSelect = $audioColumn !== null
    ? "w.`{$audioColumn}` AS audio_path"
    : "'' AS audio_path";

$wordStatusWhere = isset($wordColumns['status'])
    ? "AND w.status = 'active'"
    : '';

$wordStmt = $pdo->prepare(
    "SELECT
        w.id,
        w.`{$wordTextColumn}` AS word_text,
        {$imageSelect},
        {$audioSelect},
        fsw.`{$orderColumn}` AS display_order
     FROM flashcard_set_words fsw
     INNER JOIN words w
        ON w.id = fsw.`{$wordFk}`
     WHERE fsw.`{$setFk}` = ?
       {$wordStatusWhere}
     ORDER BY fsw.`{$orderColumn}` ASC, fsw.id ASC"
);
$wordStmt->execute([$flashcardSetId]);
$rows = $wordStmt->fetchAll(PDO::FETCH_ASSOC);

$cards = array_map(
    static function (array $row): array {
        return [
            'word' => (string)($row['word_text'] ?? ''),
            'image' => sqAssetUrl((string)($row['image_path'] ?? '')),
            'audio' => sqAssetUrl((string)($row['audio_path'] ?? '')),
        ];
    },
    $rows
);

if ($quizSettings['shuffle_questions']) {
    shuffle($cards);
}

if (
    $questionCount < 100
    && count($cards) > $questionCount
) {
    $cards = array_slice($cards, 0, $questionCount);
}

$rawUnitNumber = trim((string)$activity['unit_number']);
$rawLessonNumber = trim((string)$activity['lesson_number']);

$displayUnitNumber = preg_match('/(\d+)/', $rawUnitNumber, $unitMatch)
    ? (int)$unitMatch[1]
    : $rawUnitNumber;

$displayLessonNumber = preg_match('/(\d+)/', $rawLessonNumber, $lessonMatch)
    ? (int)$lessonMatch[1]
    : $rawLessonNumber;

$backUrl = 'student-activities.php?' . http_build_query([
    'book' => (string)$activity['book_slug'],
    'level' => (string)$activity['level_slug'],
    'level_id' => (int)$activity['level_id'],
    'unit_id' => (int)$activity['unit_id'],
    'lesson_id' => (int)$activity['lesson_id'],
    'lesson' => $displayLessonNumber,
]);

$runtimeFinishUrl = 'student-runtime/index.php?' . http_build_query([
    'runtime_action' => 'next',
    'current_activity_id' => (int)$activity['activity_id'],
    'lesson_id' => (int)$activity['lesson_id'],
    'preview' => (int)($_GET['preview'] ?? 0) === 1 ? 1 : 0,
]);

$_SESSION['last_learning_url'] = (string)($_SERVER['REQUEST_URI'] ?? '');
?>
<!doctype html>
<html lang="vi">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>Quiz | EnglishSpeak</title>
<style>
:root{
  --blue:#198fe3;--blue-dark:#0868c7;--soft:#eaf5ff;--page:#f4f8fc;
  --text:#15314b;--muted:#718399;--line:#dfe8f0;--green:#26a65b;
  --red:#e55353;--width:520px;--shadow:0 7px 22px rgba(31,71,108,.10)
}
*{box-sizing:border-box}
html,body{margin:0;min-height:100%;background:var(--page);color:var(--text);font-family:"Segoe UI",Tahoma,Arial,sans-serif}
body{display:flex;justify-content:center}
button,a{font:inherit;-webkit-tap-highlight-color:transparent}
.app{width:min(100%,var(--width));min-height:100dvh;padding:0 12px 24px;background:#fff;box-shadow:0 0 28px rgba(30,79,115,.08)}
.topbar{position:sticky;top:0;z-index:40;display:grid;grid-template-columns:46px minmax(0,1fr) 46px;align-items:center;gap:9px;min-height:76px;margin:0 -12px 14px;padding:12px;background:linear-gradient(135deg,#3488ef,#17b8e4);color:#fff;box-shadow:0 5px 15px rgba(31,135,210,.22)}
.round{display:grid;width:44px;height:44px;place-items:center;border:0;border-radius:50%;background:rgba(255,255,255,.15);color:#fff;text-decoration:none;font-size:24px;font-weight:850;cursor:pointer}
.heading{text-align:center;min-width:0}.heading strong{display:block;font-size:22px;line-height:1.15}.heading small{display:block;margin-top:4px;color:rgba(255,255,255,.92);font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.lesson{display:grid;grid-template-columns:52px minmax(0,1fr);align-items:center;gap:11px;min-height:72px;margin-bottom:12px;padding:12px 14px;border-radius:20px;background:linear-gradient(135deg,#edf6ff,#e6f1ff)}
.lesson__icon{width:48px;height:48px;display:grid;place-items:center;border-radius:14px;background:#fff;font-size:29px}.lesson strong{font-size:18px}
.progress-row{display:flex;justify-content:space-between;gap:10px;color:#38536c;font-size:13px;font-weight:800}
.track{height:9px;margin:8px 0 14px;overflow:hidden;border-radius:999px;background:#dceaf5}
.fill{width:0;height:100%;border-radius:inherit;background:linear-gradient(90deg,#1c7ce4,#18a9e7);transition:width .2s}
.quiz-card{padding:16px;border:1px solid var(--line);border-radius:22px;background:#fff;box-shadow:var(--shadow)}
.quiz-image{width:100%;height:min(36dvh,280px);display:grid;place-items:center;padding:16px;border-radius:18px;background:#fbfdff}
.quiz-image img{max-width:260px;max-height:260px;width:92%;height:92%;object-fit:contain}
.quiz-question{margin:16px 0 14px;color:#123e62;font-size:20px;font-weight:850;text-align:center}
.options{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.option{min-height:56px;padding:10px;border:1px solid #cbddeb;border-radius:15px;background:#fff;color:var(--text);font-weight:800;cursor:pointer}
.option.selected{border:2px solid var(--blue);background:var(--soft);color:var(--blue-dark)}
.option.correct{border:2px solid #70cf91;background:#effcf3;color:#19783a}
.option.wrong{border:2px solid #ef9a9a;background:#fff1f1;color:#a23636}
.feedback{display:none;margin-top:12px;padding:12px 14px;border-radius:14px;font-size:14px;font-weight:750}
.feedback.show{display:block}
.feedback.good{border:1px solid #bce5c8;background:#eefbf2;color:#19783a}
.feedback.bad{border:1px solid #efc1c1;background:#fff1f1;color:#9a3434}
.next{width:100%;min-height:52px;margin-top:12px;border:0;border-radius:15px;background:var(--blue);color:#fff;font-weight:850;cursor:pointer}
.next:disabled{opacity:.45}
.finish{display:none;min-height:calc(100dvh - 110px);padding:38px 18px;align-items:center;justify-content:center;flex-direction:column;text-align:center}
.finish.show{display:flex}.finish__icon{font-size:66px}.finish h2{margin:14px 0 8px;color:#123e62;font-size:35px}.finish p{margin:0;color:var(--muted);font-size:16px}
.summary{width:100%;margin-top:22px;padding:5px 17px;border:1px solid var(--line);border-radius:18px;box-shadow:var(--shadow)}
.summary-row{display:flex;justify-content:space-between;align-items:center;min-height:58px;border-bottom:1px solid #e5ecf2}.summary-row:last-child{border:0}.summary-row strong{color:var(--blue-dark);font-size:19px}
.finish-message{width:100%;margin-top:16px;padding:15px;border:1px solid #bde7c8;border-radius:16px;background:#eefbf1;color:#16823b;font-weight:750}
.finish-actions{display:grid;gap:10px;width:100%;margin-top:18px}.finish-actions button,.finish-actions a{min-height:54px;display:grid;place-items:center;border:1px solid var(--blue);border-radius:15px;background:#fff;color:var(--blue-dark);text-decoration:none;font-weight:850}.finish-actions .primary{background:var(--blue);color:#fff}
.empty{padding:50px 20px;text-align:center}
@media(max-width:390px){.app{padding-left:10px;padding-right:10px}.topbar{margin-left:-10px;margin-right:-10px;padding-left:10px;padding-right:10px}.quiz-card{padding:12px}.quiz-image{height:min(33dvh,250px)}.quiz-image img{max-width:230px;max-height:230px}.quiz-question{font-size:18px}.option{min-height:52px;font-size:14px}}

/* EnglishSpeak XP popup */
.xp-popup {
    position: fixed;
    z-index: 10000;
    inset: 0;
    display: none;
    align-items: center;
    justify-content: center;
    padding: 20px;
    background: rgba(18, 49, 74, .38);
    backdrop-filter: blur(5px);
}
.xp-popup.show { display: flex; }
.xp-popup__card {
    width: min(100%, 350px);
    padding: 24px 20px 20px;
    border-radius: 24px;
    background: #fff;
    box-shadow: 0 18px 50px rgba(18, 49, 74, .24);
    text-align: center;
    animation: xpPopupIn .25s ease-out;
}
.xp-popup__icon {
    width: 76px;
    height: 76px;
    display: grid;
    place-items: center;
    margin: 0 auto 10px;
    border-radius: 50%;
    background: linear-gradient(135deg, #fff6bf, #ffe06e);
    font-size: 42px;
}
.xp-popup__title {
    margin: 0;
    color: #15314b;
    font-size: 27px;
    line-height: 1.2;
}
.xp-popup__text {
    margin: 7px 0 0;
    color: #718399;
    font-size: 14px;
}
.xp-popup__score {
    margin: 17px 0;
    color: #f39c12;
    font-size: 36px;
    font-weight: 900;
    line-height: 1;
}
.xp-popup__button {
    width: 100%;
    min-height: 52px;
    border: 0;
    border-radius: 15px;
    background: linear-gradient(135deg, #237fe1, #159ddd);
    color: #fff;
    font-weight: 850;
    cursor: pointer;
}
@keyframes xpPopupIn {
    from { opacity: 0; transform: translateY(14px) scale(.96); }
    to { opacity: 1; transform: translateY(0) scale(1); }
}

</style>
</head>
<body>
<main class="app">
<header class="topbar">
  <a class="round" href="<?= htmlspecialchars($backUrl, ENT_QUOTES, 'UTF-8') ?>" aria-label="Quay lại">←</a>
  <div class="heading">
    <strong>Unit <?= $displayUnitNumber ?></strong>
    <small><?= htmlspecialchars((string)($activity['unit_title'] ?? ''), ENT_QUOTES, 'UTF-8') ?></small>
  </div>
  <span class="round" aria-hidden="true" style="visibility:hidden"></span>
</header>

<?php if ($cards === []): ?>
<section class="empty"><h2>Chưa có từ vựng</h2><p>Hoạt động này chưa có dữ liệu.</p></section>
<?php else: ?>
<section id="quizScreen">
  <div class="lesson"><div class="lesson__icon">❓</div><strong>Quiz</strong></div>
  <div class="progress-row"><span id="progressLabel">1 / <?= count($cards) ?></span><span id="scoreLabel">0 điểm</span></div>
  <div class="track"><div class="fill" id="progressFill"></div></div>

  <section class="quiz-card">
    <div class="quiz-image">
      <img id="quizImage" alt="">
    </div>

    <div class="quiz-question">Chọn từ đúng</div>
    <div class="options" id="options"></div>
    <div class="feedback" id="feedback" aria-live="polite"></div>
    <button class="next" id="nextButton" type="button" disabled>Tiếp →</button>
  </section>
</section>

<section class="finish" id="finishScreen">
  <div class="finish__icon">🎉</div>
  <h2>🎉 Quiz Completed!</h2>
  <p>Bạn đã hoàn thành bài Quiz.</p>
  <div class="summary">
    <div class="summary-row"><span>Đúng</span><strong id="finalCorrect">0 / <?= count($cards) ?></strong></div>
    <div class="summary-row"><span>Điểm</span><strong id="finalScore">0%</strong></div>
  </div>
  <div class="finish-message" id="finishMessage">✅ Em đã hoàn thành Quiz.</div>
  <div class="finish-actions">
    <a class="primary" id="continueButton" href="<?= htmlspecialchars($runtimeFinishUrl, ENT_QUOTES, 'UTF-8') ?>" style="display:none">➡ Next</a>
    <button id="playAgainButton" type="button">↻ Again</button>
    <a href="<?= htmlspecialchars($backUrl, ENT_QUOTES, 'UTF-8') ?>">← Back</a>
  </div>
</section>
<?php endif; ?>
</main>


<div class="xp-popup" id="xpPopup" role="dialog" aria-modal="true" aria-labelledby="xpPopupTitle">
    <div class="xp-popup__card">
        <div class="xp-popup__icon" aria-hidden="true">⭐</div>
        <h2 class="xp-popup__title" id="xpPopupTitle">Hoàn thành!</h2>
        <p class="xp-popup__text" id="xpPopupText">Em nhận được</p>
        <div class="xp-popup__score" id="xpPopupScore"></div>
        <button class="xp-popup__button" id="xpPopupButton" type="button">View Result</button>
    </div>
</div>

<?php if ($cards !== []): ?>
<script>

function showXpPopup(result) {
  if (!result || result.preview === true) return;

  const popup = document.getElementById('xpPopup');
  const title = document.getElementById('xpPopupTitle');
  const text = document.getElementById('xpPopupText');
  const score = document.getElementById('xpPopupScore');

  if (!popup || !title || !text || !score) return;

  const xpAdded = Number(result.xp_added || 0);
  const passed = result.passed === true;

  if (xpAdded > 0) {
    title.textContent = result.xp_event_type === 'completion'
      ? 'Hoàn thành!'
      : 'Luyện tập tốt!';
    text.hidden = false;
    text.textContent = 'Em nhận được';
    score.textContent = `+${xpAdded} XP`;
  } else if (passed) {
    /*
     * Đã hết Practice XP:
     * chỉ khen và hiển thị điểm phần trăm.
     */
    const finalPercent = Number(
      document.getElementById('finalScore')?.textContent.replace('/100', '') || 0
    );

    title.textContent = 'Great!';
    text.textContent = '';
    text.hidden = true;
    score.textContent = `${Math.max(0, Math.min(100, Math.round(finalPercent)))}%`;
  } else {
    const finalPercent = Number(
      document.getElementById('finalScore')?.textContent.replace('/100', '') || 0
    );
    const safePercent = Math.max(0, Math.min(100, Math.round(finalPercent)));

    title.textContent = 'Good effort!';
    text.hidden = false;
    text.textContent = 'Em chưa đạt mức yêu cầu. Hãy thử lại nhé.';
    score.textContent = `${safePercent}%`;
  }

  popup.classList.add('show');
}
function hideXpPopup(){
  const popup=document.getElementById('xpPopup');
  if(popup) popup.classList.remove('show');
}
document.getElementById('xpPopupButton')?.addEventListener('click',hideXpPopup);


const cards = <?= json_encode($cards, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;
const quizSettings = <?= json_encode(
    $quizSettings,
    JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
) ?>;
let index=0,correctCount=0,answered=false,soundOn=true;
const quizScreen=document.getElementById('quizScreen');
const finishScreen=document.getElementById('finishScreen');
const image=document.getElementById('quizImage');
const options=document.getElementById('options');
const feedback=document.getElementById('feedback');
const nextButton=document.getElementById('nextButton');

async function saveActivityProgress(score){
  try{
    const response=await fetch(
      '/EnglishSpeak/api/save-activity-progress.php',
      {
        method:'POST',
        headers:{'Content-Type':'application/json;charset=UTF-8'},
        credentials:'same-origin',
        body:JSON.stringify({
          activity_id:<?= (int)$activityId ?>,
          score:score,
          completed:score>=<?= (int)$passingScore ?>,
          passing_score:<?= (int)$passingScore ?>,
          preview:<?= $isPreview ? 'true' : 'false' ?>
        })
      }
    );

    const result=await response.json();

    if(!response.ok||!result.ok){
      console.warn('Không thể lưu tiến trình Quiz.',result);
    }

    return result;
  }catch(error){
    console.warn('Lỗi mạng khi lưu tiến trình Quiz.',error);
    return {ok:false,xp_added:0};
  }
}

function shuffle(arr){
  for(let i=arr.length-1;i>0;i--){
    const j=Math.floor(Math.random()*(i+1));
    [arr[i],arr[j]]=[arr[j],arr[i]];
  }
  return arr;
}
function speak(card){
  if(!soundOn)return;
  if(card.audio){
    const a=new Audio(card.audio);
    a.play().catch(()=>tts(card.word));
  }else tts(card.word);
}
function tts(text){
  if(!('speechSynthesis' in window))return;
  speechSynthesis.cancel();
  const u=new SpeechSynthesisUtterance(text);
  u.lang='en-US';
  u.rate=.72;
  speechSynthesis.speak(u);
}
function getChoices(current){
  const others=cards.filter(c=>c.word!==current.word);
  const distractors=quizSettings.shuffle_options
    ? shuffle([...others]).slice(0,3)
    : others.slice(0,3);

  const choices=[current,...distractors];

  return quizSettings.shuffle_options
    ? shuffle(choices)
    : choices;
}
function render(){
  answered=false;
  nextButton.disabled=true;
  feedback.className='feedback';
  feedback.textContent='';

  const card=cards[index];
  image.src=card.image||'';
  image.alt=card.word;
  document.getElementById('progressLabel').textContent=`${index+1} / ${cards.length}`;
  document.getElementById('progressFill').style.width=`${((index+1)/cards.length)*100}%`;
  document.getElementById('scoreLabel').textContent=`${correctCount} điểm`;

  options.innerHTML='';
  getChoices(card).forEach(choice=>{
    const btn=document.createElement('button');
    btn.className='option';
    btn.type='button';
    btn.textContent=choice.word;
    btn.onclick=()=>choose(btn,choice,card);
    options.appendChild(btn);
  });
}
function choose(btn,choice,correctCard){
  if(answered)return;
  answered=true;
  const all=[...document.querySelectorAll('.option')];

  all.forEach(b=>{
    if(b.textContent===correctCard.word)b.classList.add('correct');
  });

  if(choice.word===correctCard.word){
    correctCount++;
    btn.classList.add('correct');
    feedback.className='feedback show good';
    feedback.textContent='✅ Chính xác!';
    speak(correctCard);
  }else{
    btn.classList.add('wrong');
    feedback.className='feedback show bad';
    feedback.textContent=`Đáp án đúng: ${correctCard.word}`;
    speak(correctCard);
  }

  document.getElementById('scoreLabel').textContent=`${correctCount} điểm`;
  nextButton.disabled=false;
}
async function next(){
  if(index<cards.length-1){
    index++;
    render();
  }else{
    const percent=Math.round((correctCount/cards.length)*100);
    document.getElementById('finalCorrect').textContent=`${correctCount} / ${cards.length}`;
    document.getElementById('finalScore').textContent=`${percent}/100`;
    document.getElementById('finishMessage').textContent=
      percent>=<?= (int)$passingScore ?>
        ? '✅ Em đã hoàn thành Quiz.'
        : 'Em chưa đạt mức yêu cầu. Hãy thử lại nhé.';
    const progressResult=await saveActivityProgress(percent);
    quizScreen.style.display='none';
    finishScreen.classList.add('show');
    const continueButton=document.getElementById('continueButton');
    if(continueButton){
      continueButton.style.display=percent>=<?= (int)$passingScore ?> ? 'grid' : 'none';
    }
    showXpPopup(progressResult);
  }
}
nextButton.onclick=next;
document.getElementById('playAgainButton')?.addEventListener('click',()=>{
  index=0;
  correctCount=0;
  answered=false;
  finishScreen.classList.remove('show');
  hideXpPopup();
  quizScreen.style.display='block';
  render();
});
render();
</script>
<?php endif; ?>
</body>
</html>
