<?php
// /elms/admin/courses/quiz_builder.php
// Clean MCQ builder: create/update quiz, 4-answer question form, edit/delete question, CSV import/export, publish to lms_content.
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) session_start();

require_once __DIR__ . '/../../includes/auth.php';
require_role(['super_admin','admin','branch_admin']);
require_once __DIR__ . '/../../includes/db.php';
if (is_file(__DIR__ . '/../../includes/helpers.php')) require_once __DIR__ . '/../../includes/helpers.php';

$mysqli = $mysqli ?? ($conn ?? null);
if (!$mysqli instanceof mysqli) { http_response_code(500); exit('DB connection missing'); }
$mysqli->set_charset('utf8mb4');

if (!function_exists('esc')) {
    function esc($s): string { return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
}

function qb_table_exists(string $table): bool {
    global $mysqli;
    $st = $mysqli->prepare("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? LIMIT 1");
    $st->bind_param('s', $table);
    $st->execute();
    $ok = (bool)$st->get_result()->fetch_row();
    $st->close();
    return $ok;
}

function qb_col_exists(string $table, string $col): bool {
    global $mysqli;
    $st = $mysqli->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=? LIMIT 1");
    $st->bind_param('ss', $table, $col);
    $st->execute();
    $ok = (bool)$st->get_result()->fetch_row();
    $st->close();
    return $ok;
}

function qb_pick_col(string $table, array $cols, string $fallback = 'id'): string {
    foreach ($cols as $c) if (qb_col_exists($table, $c)) return $c;
    return $fallback;
}

function qb_norm($s): string {
    return strtolower(preg_replace('/[^a-z0-9]+/', '_', trim((string)$s)));
}

function qb_redirect(int $course_id, int $module_id, int $quiz_id = 0, string $extra = ''): void {
    $url = "quiz_builder.php?course_id={$course_id}&module_id={$module_id}";
    if ($quiz_id > 0) $url .= "&quiz_id={$quiz_id}";
    $url .= $extra;
    header("Location: {$url}");
    exit;
}

function qb_flash(string $key, ?string $value = null): ?string {
    if ($value === null) {
        $v = $_SESSION['qb_flash'][$key] ?? null;
        unset($_SESSION['qb_flash'][$key]);
        return $v;
    }
    $_SESSION['qb_flash'][$key] = $value;
    return null;
}

function qb_ensure_schema(): void {
    global $mysqli;

    $mysqli->query("CREATE TABLE IF NOT EXISTS `lms_quizzes` (
        `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
        `course_id` INT UNSIGNED NOT NULL,
        `module_id` INT UNSIGNED NOT NULL,
        `title` VARCHAR(255) NOT NULL,
        `description` TEXT NULL,
        `time_limit_sec` INT NULL,
        `max_attempts` INT NULL,
        `pass_score` INT NULL,
        `max_questions` INT NULL,
        `randomized` TINYINT(1) NOT NULL DEFAULT 0,
        `active` TINYINT(1) NOT NULL DEFAULT 1,
        `created_at` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        `updated_at` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`),
        KEY `idx_course_module` (`course_id`,`module_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    foreach ([
        'max_questions INT NULL AFTER pass_score',
        'randomized TINYINT(1) NOT NULL DEFAULT 0 AFTER max_questions',
        'active TINYINT(1) NOT NULL DEFAULT 1 AFTER randomized'
    ] as $def) {
        [$col] = explode(' ', $def, 2);
        if (!qb_col_exists('lms_quizzes', $col)) @$mysqli->query("ALTER TABLE lms_quizzes ADD COLUMN {$def}");
    }

    $mysqli->query("CREATE TABLE IF NOT EXISTS `lms_quiz_questions` (
        `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
        `quiz_id` INT UNSIGNED NOT NULL,
        `question_text` TEXT NOT NULL,
        `points` INT NOT NULL DEFAULT 1,
        `sort_order` INT NOT NULL DEFAULT 0,
        PRIMARY KEY (`id`),
        KEY `idx_quiz` (`quiz_id`,`sort_order`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $mysqli->query("CREATE TABLE IF NOT EXISTS `lms_quiz_options` (
        `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
        `question_id` INT UNSIGNED NOT NULL,
        `option_text` TEXT NOT NULL,
        `is_correct` TINYINT(1) NOT NULL DEFAULT 0,
        `sort_order` INT NOT NULL DEFAULT 0,
        PRIMARY KEY (`id`),
        KEY `idx_question` (`question_id`,`sort_order`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $mysqli->query("CREATE TABLE IF NOT EXISTS `lms_content` (
        `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
        `module_id` INT UNSIGNED NOT NULL,
        `title` VARCHAR(255) NOT NULL,
        `content_type` VARCHAR(50) NOT NULL DEFAULT 'link',
        `description` TEXT NULL,
        `available_from` DATETIME NULL,
        `available_to` DATETIME NULL,
        `file_path` VARCHAR(255) NULL,
        `url` VARCHAR(500) NULL,
        `quiz_id` INT NULL,
        `duration_seconds` INT NULL,
        `sort_order` INT NOT NULL DEFAULT 0,
        `active` TINYINT(1) NOT NULL DEFAULT 1,
        `require_paid` TINYINT(1) NOT NULL DEFAULT 0,
        `created_at` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        `updated_at` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`),
        KEY `idx_module_order` (`module_id`,`sort_order`),
        KEY `idx_quiz` (`quiz_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    if (!qb_col_exists('lms_content', 'quiz_id')) {
        @$mysqli->query("ALTER TABLE lms_content ADD COLUMN quiz_id INT NULL AFTER url, ADD KEY idx_quiz (quiz_id)");
    }
}

qb_ensure_schema();

$course_id = (int)($_GET['course_id'] ?? $_POST['course_id'] ?? 0);
$module_id = (int)($_GET['module_id'] ?? $_POST['module_id'] ?? 0);
$quiz_id   = (int)($_GET['quiz_id'] ?? $_POST['quiz_id'] ?? 0);
$content_id = (int)($_GET['content_id'] ?? 0);
$edit_qid  = (int)($_GET['edit_qid'] ?? 0);

if (!qb_col_exists('lms_content', 'session_id')) {
    @$mysqli->query("ALTER TABLE lms_content ADD COLUMN session_id INT UNSIGNED NULL AFTER module_id");
}

$SESSIONS = [];
if (qb_table_exists('lms_content_sessions')) {
    $st = $mysqli->prepare("
        SELECT id, title 
        FROM lms_content_sessions 
        WHERE course_id=? AND module_id=? 
        ORDER BY sort_order, id
    ");
    $st->bind_param('ii', $course_id, $module_id);
    $st->execute();
    $rs = $st->get_result();
    while ($r = $rs->fetch_assoc()) {
        $SESSIONS[] = $r;
    }
    $st->close();
}


if ($quiz_id <= 0 && $content_id > 0 && qb_table_exists('lms_content')) {
    if (qb_col_exists('lms_content', 'quiz_id')) {
        $st = $mysqli->prepare("
            SELECT quiz_id
            FROM lms_content
            WHERE id=? AND module_id=? AND content_type='quiz'
            LIMIT 1
        ");
        $st->bind_param('ii', $content_id, $module_id);
        $st->execute();
        $row = $st->get_result()->fetch_assoc();
        $st->close();

        if (!empty($row['quiz_id'])) {
            $quiz_id = (int)$row['quiz_id'];
        }
    }

    if ($quiz_id <= 0) {
        $quizUrl = '/elms/student/quiz.php?quiz_id=';

        $st = $mysqli->prepare("
            SELECT url
            FROM lms_content
            WHERE id=? AND module_id=? AND content_type='quiz'
            LIMIT 1
        ");
        $st->bind_param('ii', $content_id, $module_id);
        $st->execute();
        $row = $st->get_result()->fetch_assoc();
        $st->close();

        if (!empty($row['url']) && preg_match('/quiz_id=(\d+)/', $row['url'], $m)) {
            $quiz_id = (int)$m[1];
        }
    }
}

if ($course_id <= 0 || $module_id <= 0) { http_response_code(400); exit('Missing course_id/module_id'); }

/* detect correct module table */
$MOD_TBL = null;
foreach (['course_modules','lms_modules'] as $tbl) {
    if (!qb_table_exists($tbl) || !qb_col_exists($tbl, 'id') || !qb_col_exists($tbl, 'course_id')) continue;
    $st = $mysqli->prepare("SELECT id FROM `$tbl` WHERE id=? AND course_id=? LIMIT 1");
    $st->bind_param('ii', $module_id, $course_id);
    $st->execute();
    $found = $st->get_result()->fetch_assoc();
    $st->close();
    if ($found) { $MOD_TBL = $tbl; break; }
}
if (!$MOD_TBL) $MOD_TBL = qb_table_exists('course_modules') ? 'course_modules' : (qb_table_exists('lms_modules') ? 'lms_modules' : null);
if (!$MOD_TBL) { http_response_code(500); exit('No modules table found.'); }

$TITLE_COL = qb_pick_col($MOD_TBL, ['title','name','module_name'], 'id');
$ORDER_COL = qb_pick_col($MOD_TBL, ['sort_order','order_no','position'], 'id');

$st = $mysqli->prepare("SELECT id, `$TITLE_COL` AS title FROM `$MOD_TBL` WHERE id=? AND course_id=? LIMIT 1");
$st->bind_param('ii', $module_id, $course_id);
$st->execute();
$MODULE = $st->get_result()->fetch_assoc();
$st->close();

if (!$MODULE) {
    echo '<div style="padding:18px;font-family:system-ui"><h3>Module not found</h3>';
    echo '<p>module_id <b>'.(int)$module_id.'</b> does not exist for course_id <b>'.(int)$course_id.'</b>.</p>';
    $st = $mysqli->prepare("SELECT id, `$TITLE_COL` AS title FROM `$MOD_TBL` WHERE course_id=? ORDER BY `$ORDER_COL`, id");
    $st->bind_param('i', $course_id);
    $st->execute();
    $rs = $st->get_result();
    echo '<ul>';
    while ($m = $rs->fetch_assoc()) echo '<li><a href="quiz_builder.php?course_id='.$course_id.'&module_id='.(int)$m['id'].'">'.esc($m['title']).' (ID '.(int)$m['id'].')</a></li>';
    echo '</ul><a href="modules.php?course_id='.(int)$course_id.'">Back to Modules</a></div>';
    $st->close();
    exit;
}

/* course label */
$courseLabel = 'Course #'.$course_id;
if (qb_table_exists('courses')) {
    $cCol = qb_pick_col('courses', ['course_name','name','title'], 'id');
    $st = $mysqli->prepare("SELECT `$cCol` AS label FROM courses WHERE id=? LIMIT 1");
    $st->bind_param('i', $course_id);
    $st->execute();
    if ($r = $st->get_result()->fetch_assoc()) $courseLabel = (string)$r['label'];
    $st->close();
}

/* downloads */
if (($_GET['download'] ?? '') === 'csv_template') {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="quiz_template.csv"');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['question','points','option_a','option_b','option_c','option_d','correct']);
    fputcsv($out, ['What is 2 + 2?', '1', '3', '4', '5', '22', 'B']);
    fclose($out);
    exit;
}

if (($_GET['download'] ?? '') === 'quiz_csv') {
    if ($quiz_id <= 0) { http_response_code(400); exit('quiz_id missing'); }
    $st = $mysqli->prepare("SELECT id, question_text, points FROM lms_quiz_questions WHERE quiz_id=? ORDER BY sort_order,id");
    $st->bind_param('i', $quiz_id);
    $st->execute();
    $rs = $st->get_result();
    $questions = [];
    while ($q = $rs->fetch_assoc()) $questions[] = $q;
    $st->close();

    $optsByQ = [];
    if ($questions) {
        $ids = implode(',', array_map('intval', array_column($questions, 'id')));
        $rs = $mysqli->query("SELECT question_id, option_text, is_correct FROM lms_quiz_options WHERE question_id IN ($ids) ORDER BY question_id, sort_order,id");
        while ($o = $rs->fetch_assoc()) $optsByQ[(int)$o['question_id']][] = $o;
    }

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="quiz_'.$quiz_id.'.csv"');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['question','points','option_a','option_b','option_c','option_d','correct']);
    $letters = ['A','B','C','D'];
    foreach ($questions as $q) {
        $opts = $optsByQ[(int)$q['id']] ?? [];
        $row = [$q['question_text'], (int)$q['points']];
        for ($i=0; $i<4; $i++) $row[] = $opts[$i]['option_text'] ?? '';
        $correct = 'A';
        for ($i=0; $i<count($opts) && $i<4; $i++) if (!empty($opts[$i]['is_correct'])) { $correct = $letters[$i]; break; }
        $row[] = $correct;
        fputcsv($out, $row);
    }
    fclose($out);
    exit;
}

$action = $_POST['action'] ?? '';

if ($action === 'create_quiz') {
    $title = trim($_POST['title'] ?? '');
    $desc  = trim($_POST['description'] ?? '');
    $time  = ($_POST['time_limit_sec'] ?? '') === '' ? null : max(0, (int)$_POST['time_limit_sec']);
    $maxat = ($_POST['max_attempts'] ?? '') === '' ? null : max(1, (int)$_POST['max_attempts']);
    $pass  = ($_POST['pass_score'] ?? '') === '' ? null : max(0, (int)$_POST['pass_score']);
    $maxq  = ($_POST['max_questions'] ?? '') === '' ? null : max(1, (int)$_POST['max_questions']);
    $rand  = isset($_POST['randomized']) ? 1 : 0;
    if ($title === '') qb_flash('err', 'Quiz title required.');
    else {
        $st = $mysqli->prepare("INSERT INTO lms_quizzes(course_id,module_id,title,description,time_limit_sec,max_attempts,pass_score,max_questions,randomized,active) VALUES (?,?,?,?,?,?,?,?,?,1)");
        $st->bind_param('iissiiiii', $course_id, $module_id, $title, $desc, $time, $maxat, $pass, $maxq, $rand);
        if ($st->execute()) { $quiz_id = (int)$st->insert_id; qb_flash('ok', 'Quiz created.'); }
        else qb_flash('err', 'DB error creating quiz.');
        $st->close();
        qb_redirect($course_id, $module_id, $quiz_id);
    }
}

if ($action === 'update_quiz' && $quiz_id > 0) {
    $title = trim($_POST['title'] ?? '');
    $desc  = trim($_POST['description'] ?? '');
    $time  = ($_POST['time_limit_sec'] ?? '') === '' ? null : max(0, (int)$_POST['time_limit_sec']);
    $maxat = ($_POST['max_attempts'] ?? '') === '' ? null : max(1, (int)$_POST['max_attempts']);
    $pass  = ($_POST['pass_score'] ?? '') === '' ? null : max(0, (int)$_POST['pass_score']);
    $maxq  = ($_POST['max_questions'] ?? '') === '' ? null : max(1, (int)$_POST['max_questions']);
    $rand  = isset($_POST['randomized']) ? 1 : 0;
    if ($title === '') qb_flash('err', 'Quiz title required.');
    else {
        $st = $mysqli->prepare("UPDATE lms_quizzes SET title=?,description=?,time_limit_sec=?,max_attempts=?,pass_score=?,max_questions=?,randomized=?,updated_at=NOW() WHERE id=? AND course_id=? AND module_id=?");
        $st->bind_param('ssiiiiiiii', $title, $desc, $time, $maxat, $pass, $maxq, $rand, $quiz_id, $course_id, $module_id);
        $st->execute();
        $st->close();
        qb_flash('ok', 'Quiz settings saved.');
    }
    qb_redirect($course_id, $module_id, $quiz_id);
}

if ($action === 'add_question' && $quiz_id > 0) {
    $qt = trim($_POST['question_text'] ?? '');
    $pts = max(1, (int)($_POST['points'] ?? 1));
    $answers = $_POST['answers'] ?? [];
    $correct = (int)($_POST['correct_answer'] ?? 0);
    if (!is_array($answers)) $answers = [];
    $cleanAnswers = array_map(fn($x) => trim((string)$x), array_slice($answers, 0, 4));

    if ($qt === '') qb_flash('err', 'Question text required.');
    elseif (count(array_filter($cleanAnswers, fn($x) => $x !== '')) < 2) qb_flash('err', 'At least 2 answers required.');
    elseif ($correct < 1 || $correct > 4 || empty($cleanAnswers[$correct-1])) qb_flash('err', 'Select a valid correct answer.');
    else {
        $ord = 1;
        $st = $mysqli->prepare("SELECT COALESCE(MAX(sort_order),0)+1 FROM lms_quiz_questions WHERE quiz_id=?");
        $st->bind_param('i', $quiz_id); $st->execute(); $st->bind_result($ord); $st->fetch(); $st->close();

        $st = $mysqli->prepare("INSERT INTO lms_quiz_questions(quiz_id,question_text,points,sort_order) VALUES (?,?,?,?)");
        $st->bind_param('isii', $quiz_id, $qt, $pts, $ord);
        $st->execute();
        $questionId = (int)$st->insert_id;
        $st->close();

        $opOrd = 1;
        $oi = $mysqli->prepare("INSERT INTO lms_quiz_options(question_id,option_text,is_correct,sort_order) VALUES (?,?,?,?)");
        foreach ($cleanAnswers as $i => $txt) {
            if ($txt === '') continue;
            $ok = (($i + 1) === $correct) ? 1 : 0;
            $oi->bind_param('isii', $questionId, $txt, $ok, $opOrd);
            $oi->execute();
            $opOrd++;
        }
        $oi->close();
        qb_flash('ok', 'Question and answers added.');
    }
    qb_redirect($course_id, $module_id, $quiz_id);
}

if ($action === 'update_question' && $quiz_id > 0) {
    $qid = (int)($_POST['question_id'] ?? 0);
    $qt = trim($_POST['question_text'] ?? '');
    $pts = max(1, (int)($_POST['points'] ?? 1));
    $answers = $_POST['answers'] ?? [];
    $optionIds = $_POST['option_ids'] ?? [];
    $correct = (int)($_POST['correct_answer'] ?? 0);
    if (!is_array($answers)) $answers = [];
    if (!is_array($optionIds)) $optionIds = [];

    $chk = $mysqli->prepare("SELECT id FROM lms_quiz_questions WHERE id=? AND quiz_id=? LIMIT 1");
    $chk->bind_param('ii', $qid, $quiz_id); $chk->execute(); $valid = $chk->get_result()->fetch_assoc(); $chk->close();

    if (!$valid) qb_flash('err', 'Invalid question.');
    elseif ($qt === '') qb_flash('err', 'Question text required.');
    elseif (count(array_filter($answers, fn($x) => trim((string)$x) !== '')) < 2) qb_flash('err', 'At least 2 answers required.');
    elseif ($correct < 1 || $correct > 4 || trim((string)($answers[$correct-1] ?? '')) === '') qb_flash('err', 'Select a valid correct answer.');
    else {
        $st = $mysqli->prepare("UPDATE lms_quiz_questions SET question_text=?, points=? WHERE id=? AND quiz_id=?");
        $st->bind_param('siii', $qt, $pts, $qid, $quiz_id); $st->execute(); $st->close();

        $mysqli->query("DELETE FROM lms_quiz_options WHERE question_id=".(int)$qid);
        $oi = $mysqli->prepare("INSERT INTO lms_quiz_options(question_id,option_text,is_correct,sort_order) VALUES (?,?,?,?)");
        $opOrd = 1;
        foreach (array_slice($answers, 0, 4) as $i => $txt) {
            $txt = trim((string)$txt);
            if ($txt === '') continue;
            $ok = (($i + 1) === $correct) ? 1 : 0;
            $oi->bind_param('isii', $qid, $txt, $ok, $opOrd);
            $oi->execute();
            $opOrd++;
        }
        $oi->close();
        qb_flash('ok', 'Question updated.');
    }
    qb_redirect($course_id, $module_id, $quiz_id);
}

if ($action === 'delete_question' && $quiz_id > 0) {
    $qid = (int)($_POST['question_id'] ?? 0);
    if ($qid > 0) {
        $st = $mysqli->prepare("DELETE FROM lms_quiz_options WHERE question_id IN (SELECT id FROM lms_quiz_questions WHERE id=? AND quiz_id=?)");
        $st->bind_param('ii', $qid, $quiz_id); $st->execute(); $st->close();
        $st = $mysqli->prepare("DELETE FROM lms_quiz_questions WHERE id=? AND quiz_id=?");
        $st->bind_param('ii', $qid, $quiz_id); $st->execute(); $st->close();
        qb_flash('ok', 'Question deleted.');
    }
    qb_redirect($course_id, $module_id, $quiz_id);
}

if ($action === 'publish_to_content' && $quiz_id > 0) {
    if (!qb_col_exists('lms_content', 'session_id')) {
        @$mysqli->query("ALTER TABLE lms_content ADD COLUMN session_id INT UNSIGNED NULL AFTER module_id");
    }

    if (!qb_col_exists('lms_content', 'quiz_id')) {
        @$mysqli->query("ALTER TABLE lms_content ADD COLUMN quiz_id INT NULL AFTER url");
    }

    $session_id = (int)($_POST['session_id'] ?? 0);
    $sidDb = $session_id > 0 ? $session_id : null;

    $st = $mysqli->prepare("SELECT title FROM lms_quizzes WHERE id=? AND course_id=? AND module_id=? LIMIT 1");
    $st->bind_param('iii', $quiz_id, $course_id, $module_id);
    $st->execute();
    $quiz = $st->get_result()->fetch_assoc();
    $st->close();

    if (!$quiz) {
        qb_flash('err', 'Quiz not found.');
        qb_redirect($course_id, $module_id, $quiz_id);
    }

    $title = (string)$quiz['title'];
    $url   = "/elms/student/quiz.php?quiz_id=" . $quiz_id;
    $desc  = '';
    $type  = 'quiz';

    $st = $mysqli->prepare("SELECT id FROM lms_content WHERE module_id=? AND quiz_id=? LIMIT 1");
    $st->bind_param('ii', $module_id, $quiz_id);
    $st->execute();
    $existing = $st->get_result()->fetch_assoc();
    $st->close();

    if ($existing) {
        $id = (int)$existing['id'];

        $st = $mysqli->prepare("
            UPDATE lms_content
            SET session_id=?, title=?, content_type='quiz', description=?, url=?, active=1
            WHERE id=?
        ");
        $st->bind_param('isssi', $sidDb, $title, $desc, $url, $id);
        $st->execute();
        $st->close();

        qb_flash('ok', 'Quiz content updated.');
    } else {
        $ord = 1;
        $st = $mysqli->prepare("SELECT COALESCE(MAX(sort_order),0)+1 FROM lms_content WHERE module_id=?");
        $st->bind_param('i', $module_id);
        $st->execute();
        $st->bind_result($ord);
        $st->fetch();
        $st->close();

        $st = $mysqli->prepare("
            INSERT INTO lms_content
            (module_id, session_id, title, content_type, description, url, quiz_id, sort_order, active, require_paid)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, 0)
        ");
        $st->bind_param('iissssii', $module_id, $sidDb, $title, $type, $desc, $url, $quiz_id, $ord);
        $st->execute();
        $st->close();

        qb_flash('ok', 'Quiz published to module content.');
    }

    qb_redirect($course_id, $module_id, $quiz_id);
}

if ($action === 'upload_csv' && $quiz_id > 0) {
    $mode = $_POST['import_mode'] ?? 'append';
    if (!isset($_FILES['csv_file']) || !is_uploaded_file($_FILES['csv_file']['tmp_name'])) qb_flash('err', 'Please choose a CSV file.');
    else {
        $fh = fopen($_FILES['csv_file']['tmp_name'], 'r');
        $header = $fh ? fgetcsv($fh) : false;
        if (!$header) qb_flash('err', 'Empty CSV file.');
        else {
            $hn = array_map('qb_norm', $header);
            $qIdx = array_search('question', $hn, true);
            $ptsIdx = array_search('points', $hn, true);
            $correctIdx = array_search('correct', $hn, true);
            if ($qIdx === false) qb_flash('err', 'Missing question column.');
            else {
                $optCols = [];
                foreach ($hn as $i => $name) if (preg_match('/^option_?[a-z0-9]+$/', $name)) $optCols[] = $i;
                if (!$optCols) {
                    foreach ($hn as $i => $name) if (!in_array($i, [$qIdx,$ptsIdx,$correctIdx], true)) $optCols[] = $i;
                }
                if (count($optCols) < 2) qb_flash('err', 'Need at least 2 option columns.');
                else {
                    if ($mode === 'replace') {
                        $st = $mysqli->prepare("DELETE FROM lms_quiz_options WHERE question_id IN (SELECT id FROM lms_quiz_questions WHERE quiz_id=?)");
                        $st->bind_param('i', $quiz_id); $st->execute(); $st->close();
                        $st = $mysqli->prepare("DELETE FROM lms_quiz_questions WHERE quiz_id=?");
                        $st->bind_param('i', $quiz_id); $st->execute(); $st->close();
                    }
                    $added = 0; $skipped = 0; $letters = ['A'=>1,'B'=>2,'C'=>3,'D'=>4,'E'=>5,'F'=>6];
                    while (($row = fgetcsv($fh)) !== false) {
                        $question = trim((string)($row[$qIdx] ?? ''));
                        if ($question === '') { $skipped++; continue; }
                        $points = ($ptsIdx !== false && is_numeric($row[$ptsIdx] ?? null)) ? max(1, (int)$row[$ptsIdx]) : 1;
                        $opts = [];
                        foreach ($optCols as $c) { $v = trim((string)($row[$c] ?? '')); if ($v !== '') $opts[] = $v; }
                        if (count($opts) < 2) { $skipped++; continue; }
                        $correct = 1;
                        if ($correctIdx !== false) {
                            $cv = strtoupper(trim((string)($row[$correctIdx] ?? '')));
                            if (isset($letters[$cv])) $correct = min($letters[$cv], count($opts));
                            elseif (ctype_digit($cv) && (int)$cv >= 1 && (int)$cv <= count($opts)) $correct = (int)$cv;
                            else foreach ($opts as $k=>$ot) if (strcasecmp($ot, $cv) === 0) { $correct = $k+1; break; }
                        }
                        $ord = 1;
                        $st = $mysqli->prepare("SELECT COALESCE(MAX(sort_order),0)+1 FROM lms_quiz_questions WHERE quiz_id=?");
                        $st->bind_param('i', $quiz_id); $st->execute(); $st->bind_result($ord); $st->fetch(); $st->close();
                        $st = $mysqli->prepare("INSERT INTO lms_quiz_questions(quiz_id,question_text,points,sort_order) VALUES (?,?,?,?)");
                        $st->bind_param('isii', $quiz_id, $question, $points, $ord); $st->execute(); $qid = (int)$st->insert_id; $st->close();
                        $oi = $mysqli->prepare("INSERT INTO lms_quiz_options(question_id,option_text,is_correct,sort_order) VALUES (?,?,?,?)");
                        foreach ($opts as $i=>$txt) { $ok = (($i+1)===$correct)?1:0; $pos=$i+1; $oi->bind_param('isii',$qid,$txt,$ok,$pos); $oi->execute(); }
                        $oi->close();
                        $added++;
                    }
                    qb_flash('ok', "CSV import finished: {$added} added, {$skipped} skipped.");
                }
            }
        }
        if (is_resource($fh)) fclose($fh);
    }
    qb_redirect($course_id, $module_id, $quiz_id);
}

/* read */
$QUIZ = null; $QUEST = []; $OPTS = [];
if ($quiz_id > 0) {
    $st = $mysqli->prepare("SELECT * FROM lms_quizzes WHERE id=? AND course_id=? AND module_id=? LIMIT 1");
    $st->bind_param('iii', $quiz_id, $course_id, $module_id);
    $st->execute(); $QUIZ = $st->get_result()->fetch_assoc(); $st->close();
    if ($QUIZ) {
        $st = $mysqli->prepare("SELECT * FROM lms_quiz_questions WHERE quiz_id=? ORDER BY sort_order,id");
        $st->bind_param('i', $quiz_id); $st->execute(); $rs = $st->get_result();
        while ($q = $rs->fetch_assoc()) $QUEST[] = $q;
        $st->close();
        if ($QUEST) {
            $ids = implode(',', array_map('intval', array_column($QUEST, 'id')));
            $rs = $mysqli->query("SELECT * FROM lms_quiz_options WHERE question_id IN ($ids) ORDER BY question_id,sort_order,id");
            while ($o = $rs->fetch_assoc()) $OPTS[(int)$o['question_id']][] = $o;
        }
    }
}

$editQuestion = null;
if ($edit_qid > 0) foreach ($QUEST as $q) if ((int)$q['id'] === $edit_qid) { $editQuestion = $q; break; }

$PAGE_TITLE = 'Quiz Builder';
$ACTIVE_MENU = 'courses';
$__layoutOpened = false;
foreach (['../../includes/admin_layout_top.php','../../includes/layout_top.php','../../includes/admin_header.php','../../includes/header_admin.php'] as $f) {
    $p = __DIR__.'/'.$f;
    if (is_file($p)) { require_once $p; $__layoutOpened=true; break; }
}
if (!$__layoutOpened) echo '<div class="container-fluid p-3">';
?>
<style>
.qb-hero{background:linear-gradient(135deg,#111827,#2563eb);color:#fff;border-radius:18px;padding:20px;box-shadow:0 12px 35px rgba(37,99,235,.16)}
.qb-card{border:1px solid #e5e7eb;border-radius:16px;background:#fff;box-shadow:0 8px 24px rgba(15,23,42,.06);overflow:hidden}
.qb-card-head{padding:14px 16px;border-bottom:1px solid #e5e7eb;background:#f8fafc}
.answer-box .input-group-text{background:#f8fafc}.answer-box.correct .input-group{box-shadow:0 0 0 3px rgba(34,197,94,.15);border-radius:12px}.answer-box.correct input.form-control{border-color:#22c55e}
.question-item{border:1px solid #e5e7eb;border-radius:14px;padding:12px;margin-bottom:10px;background:#fff}.question-item:hover{background:#fbfdff}
</style>

<div class="qb-hero mb-4 d-flex justify-content-between align-items-center flex-wrap gap-3">
    <div>
        <h1 class="h4 mb-1">Quiz Builder</h1>
        <div class="small opacity-75"><?= esc($courseLabel) ?> · <?= esc($MODULE['title']) ?> · Module ID <?= (int)$module_id ?></div>
    </div>
    <div class="d-flex gap-2">
        <a class="btn btn-light btn-sm" href="content.php?course_id=<?= (int)$course_id ?>&module_id=<?= (int)$module_id ?>">Content</a>
        <a class="btn btn-outline-light btn-sm" href="modules.php?course_id=<?= (int)$course_id ?>">← Modules</a>
    </div>
</div>

<?php if ($m = qb_flash('ok')): ?><div class="alert alert-success"><?= esc($m) ?></div><?php endif; ?>
<?php if ($m = qb_flash('err')): ?><div class="alert alert-danger"><?= esc($m) ?></div><?php endif; ?>

<?php if (!$QUIZ && $quiz_id === 0): ?>
<div class="qb-card mb-4">
    <div class="qb-card-head"><strong>Create new quiz</strong></div>
    <div class="p-3">
        <form method="post" class="row g-3">
            <input type="hidden" name="action" value="create_quiz">
            <input type="hidden" name="course_id" value="<?= (int)$course_id ?>">
            <input type="hidden" name="module_id" value="<?= (int)$module_id ?>">
            <div class="col-md-6"><label class="form-label">Title</label><input class="form-control" name="title" required></div>
            <div class="col-md-6"><label class="form-label">Time limit seconds</label><input class="form-control" type="number" min="0" name="time_limit_sec" placeholder="600"></div>
            <div class="col-md-4"><label class="form-label">Max attempts</label><input class="form-control" type="number" min="1" name="max_attempts"></div>
            <div class="col-md-4"><label class="form-label">Pass score</label><input class="form-control" type="number" min="0" name="pass_score"></div>
            <div class="col-md-4"><label class="form-label">Max questions shown</label><input class="form-control" type="number" min="1" name="max_questions"></div>
            <div class="col-12"><label class="form-check"><input class="form-check-input" type="checkbox" name="randomized"> Randomize questions/options</label></div>
            <div class="col-12"><label class="form-label">Description</label><textarea class="form-control" name="description" rows="2"></textarea></div>
            <div class="col-12"><button class="btn btn-primary">Create Quiz</button></div>
        </form>
    </div>
</div>
<?php endif; ?>

<?php if ($QUIZ): ?>
<div class="qb-card mb-4">
    <div class="qb-card-head d-flex justify-content-between align-items-center flex-wrap gap-2">
        <div><strong><?= esc($QUIZ['title']) ?></strong> <span class="text-muted small">Quiz ID <?= (int)$quiz_id ?></span></div>
        <div class="d-flex gap-2 flex-wrap">
            <a class="btn btn-outline-secondary btn-sm" href="?course_id=<?= (int)$course_id ?>&module_id=<?= (int)$module_id ?>&quiz_id=<?= (int)$quiz_id ?>&download=csv_template">CSV Template</a>
            <a class="btn btn-outline-primary btn-sm" href="?course_id=<?= (int)$course_id ?>&module_id=<?= (int)$module_id ?>&quiz_id=<?= (int)$quiz_id ?>&download=quiz_csv">Export CSV</a>
            <button type="button"
        class="btn btn-outline-dark btn-sm"
        data-bs-toggle="modal"
        data-bs-target="#studentPreviewModal">
    Preview Student
</button>
            <form method="post" class="d-flex gap-2 align-items-center flex-wrap">
    <input type="hidden" name="action" value="publish_to_content">
    <input type="hidden" name="course_id" value="<?= (int)$course_id ?>">
    <input type="hidden" name="module_id" value="<?= (int)$module_id ?>">
    <input type="hidden" name="quiz_id" value="<?= (int)$quiz_id ?>">

    <select name="session_id" class="form-select form-select-sm" style="width:220px;">
        <option value="0">Unassigned</option>
        <?php foreach ($SESSIONS as $s): ?>
            <option value="<?= (int)$s['id'] ?>">
                <?= esc($s['title']) ?>
            </option>
        <?php endforeach; ?>
    </select>

    <button class="btn btn-success btn-sm">Publish to Content</button>
</form>
        </div>
    </div>
    <div class="p-3">
        <form method="post" class="row g-3">
            <input type="hidden" name="action" value="update_quiz">
            <input type="hidden" name="course_id" value="<?= (int)$course_id ?>">
            <input type="hidden" name="module_id" value="<?= (int)$module_id ?>">
            <input type="hidden" name="quiz_id" value="<?= (int)$quiz_id ?>">
            <div class="col-md-6"><label class="form-label">Title</label><input class="form-control" name="title" value="<?= esc($QUIZ['title'] ?? '') ?>" required></div>
            <div class="col-md-6"><label class="form-label">Time limit seconds</label><input class="form-control" type="number" min="0" name="time_limit_sec" value="<?= esc($QUIZ['time_limit_sec'] ?? '') ?>"></div>
            <div class="col-md-4"><label class="form-label">Max attempts</label><input class="form-control" type="number" min="1" name="max_attempts" value="<?= esc($QUIZ['max_attempts'] ?? '') ?>"></div>
            <div class="col-md-4"><label class="form-label">Pass score</label><input class="form-control" type="number" min="0" name="pass_score" value="<?= esc($QUIZ['pass_score'] ?? '') ?>"></div>
            <div class="col-md-4"><label class="form-label">Max questions shown</label><input class="form-control" type="number" min="1" name="max_questions" value="<?= esc($QUIZ['max_questions'] ?? '') ?>"></div>
            <div class="col-12"><label class="form-check"><input class="form-check-input" type="checkbox" name="randomized" <?= !empty($QUIZ['randomized'])?'checked':'' ?>> Randomize questions/options</label></div>
            <div class="col-12"><label class="form-label">Description</label><textarea class="form-control" name="description" rows="2"><?= esc($QUIZ['description'] ?? '') ?></textarea></div>
            <div class="col-12"><button class="btn btn-primary">Save Settings</button></div>
        </form>
    </div>
</div>

<div class="qb-card mb-4">
    <div class="qb-card-head"><strong>Bulk import questions CSV</strong></div>
    <div class="p-3">
        <form method="post" enctype="multipart/form-data" class="row g-2 align-items-end">
            <input type="hidden" name="action" value="upload_csv">
            <input type="hidden" name="course_id" value="<?= (int)$course_id ?>">
            <input type="hidden" name="module_id" value="<?= (int)$module_id ?>">
            <input type="hidden" name="quiz_id" value="<?= (int)$quiz_id ?>">
            <div class="col-md-6"><label class="form-label">CSV file</label><input class="form-control" type="file" name="csv_file" accept=".csv,text/csv" required></div>
            <div class="col-md-3"><label class="form-label">Import mode</label><select class="form-select" name="import_mode"><option value="append">Append</option><option value="replace">Replace existing</option></select></div>
            <div class="col-md-3 d-grid"><button class="btn btn-primary">Upload & Import</button></div>
        </form>
    </div>
</div>

<?php
$formAction = $editQuestion ? 'update_question' : 'add_question';
$formTitle = $editQuestion ? 'Edit Question' : 'Add MCQ Question';
$formOpts = $editQuestion ? ($OPTS[(int)$editQuestion['id']] ?? []) : [];
$correctPos = 1;
for ($i=0; $i<count($formOpts); $i++) if (!empty($formOpts[$i]['is_correct'])) { $correctPos = $i+1; break; }
?>
<div class="qb-card mb-4" id="question-form">
    <div class="qb-card-head"><strong><?= esc($formTitle) ?></strong></div>
    <div class="p-3">
        <form method="post">
            <input type="hidden" name="action" value="<?= esc($formAction) ?>">
            <input type="hidden" name="course_id" value="<?= (int)$course_id ?>">
            <input type="hidden" name="module_id" value="<?= (int)$module_id ?>">
            <input type="hidden" name="quiz_id" value="<?= (int)$quiz_id ?>">
            <?php if ($editQuestion): ?><input type="hidden" name="question_id" value="<?= (int)$editQuestion['id'] ?>"><?php endif; ?>
            <div class="mb-3"><label class="form-label">Question</label><textarea class="form-control" name="question_text" rows="2" required><?= esc($editQuestion['question_text'] ?? '') ?></textarea></div>
            <div class="row g-3 mb-3">
                <?php for ($i=0; $i<4; $i++): ?>
                <div class="col-md-6 answer-box <?= ($correctPos === $i+1) ? 'correct' : '' ?>">
                    <label class="form-label">Answer <?= $i+1 ?></label>
                    <div class="input-group">
                        <span class="input-group-text"><input type="radio" name="correct_answer" value="<?= $i+1 ?>" <?= ($correctPos === $i+1) ? 'checked' : '' ?> required></span>
                        <input class="form-control" name="answers[]" placeholder="Answer <?= $i+1 ?>" value="<?= esc($formOpts[$i]['option_text'] ?? '') ?>" <?= $i<2 ? 'required' : '' ?>>
                    </div>
                </div>
                <?php endfor; ?>
            </div>
            <div class="row g-2 align-items-end">
                <div class="col-md-2"><label class="form-label">Points</label><input class="form-control" name="points" type="number" min="1" value="<?= esc($editQuestion['points'] ?? 1) ?>"></div>
                <div class="col-md-10 text-end">
                    <?php if ($editQuestion): ?><a class="btn btn-outline-secondary" href="quiz_builder.php?course_id=<?= (int)$course_id ?>&module_id=<?= (int)$module_id ?>&quiz_id=<?= (int)$quiz_id ?>">Cancel</a><?php endif; ?>
                    <button class="btn btn-primary"><?= $editQuestion ? 'Update Question' : 'Add Question' ?></button>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="qb-card mb-4">
    <div class="qb-card-head d-flex justify-content-between"><strong>Questions</strong><span class="badge bg-primary rounded-pill"><?= count($QUEST) ?></span></div>
    <div class="p-3">
        <?php if (!$QUEST): ?>
            <div class="text-muted">No questions yet.</div>
        <?php else: foreach ($QUEST as $q): $qid=(int)$q['id']; ?>
            <div class="question-item">
                <div class="d-flex justify-content-between gap-2 flex-wrap">
                    <div><strong>Q<?= (int)$q['sort_order'] ?>.</strong> <?= esc($q['question_text']) ?> <span class="text-muted small">(<?= (int)$q['points'] ?> pt)</span></div>
                    <div class="d-flex gap-2">
                        <a class="btn btn-sm btn-outline-primary" href="quiz_builder.php?course_id=<?= (int)$course_id ?>&module_id=<?= (int)$module_id ?>&quiz_id=<?= (int)$quiz_id ?>&edit_qid=<?= $qid ?>#question-form">Edit</a>
                        <form method="post" onsubmit="return confirm('Delete this question?');">
                            <input type="hidden" name="action" value="delete_question">
                            <input type="hidden" name="course_id" value="<?= (int)$course_id ?>">
                            <input type="hidden" name="module_id" value="<?= (int)$module_id ?>">
                            <input type="hidden" name="quiz_id" value="<?= (int)$quiz_id ?>">
                            <input type="hidden" name="question_id" value="<?= $qid ?>">
                            <button class="btn btn-sm btn-outline-danger">Delete</button>
                        </form>
                    </div>
                </div>
                <?php if (!empty($OPTS[$qid])): ?>
                    <ol class="mt-2 mb-0">
                        <?php foreach ($OPTS[$qid] as $op): ?>
                            <li><?= esc($op['option_text']) ?> <?= !empty($op['is_correct']) ? '<span class="badge bg-success">correct</span>' : '' ?></li>
                        <?php endforeach; ?>
                    </ol>
                <?php endif; ?>
            </div>
        <?php endforeach; endif; ?>
    </div>
</div>
<div class="modal fade" id="studentPreviewModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-fullscreen">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Student Quiz Preview</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body p-0">
                <iframe
                    src="/elms/student/quiz.php?quiz_id=<?= (int)$quiz_id ?>&preview=1"
                    style="width:100%;height:calc(100vh - 64px);border:0;"
                    loading="lazy">
                </iframe>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<script>
document.querySelectorAll('input[name="correct_answer"]').forEach(function(r){
  r.addEventListener('change', function(){
    document.querySelectorAll('.answer-box').forEach(function(b){ b.classList.remove('correct'); });
    var box = r.closest('.answer-box'); if (box) box.classList.add('correct');
  });
});
</script>
<?php
$__layoutClosed = false;
foreach (['../../includes/admin_layout_bottom.php','../../includes/layout_bottom.php','../../includes/admin_footer.php','../../includes/footer_admin.php'] as $f) {
    $p = __DIR__.'/'.$f;
    if (is_file($p)) { require_once $p; $__layoutClosed=true; break; }
}
if (!$__layoutClosed) echo '</div>';
