<?php
session_start();
require_once '../config.php';
requireModule('exams');
require_once 'helpers.php';

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

$conn = getDBConnection();
$subjects = examsGetSubjects($conn);
$classes  = examsGetClasses($conn);

// Tutor role: restrict to assigned classes/subjects
$_is_tutor       = ($_SESSION['role'] ?? '') === 'tutor';
$_teacher_classes  = $_SESSION['teacher_classes']  ?? [];
$_teacher_subjects = $_SESSION['teacher_subjects'] ?? [];
if ($_is_tutor && !empty($_teacher_classes)) {
    $classes = array_values(array_filter($classes, fn($c) => in_array($c, $_teacher_classes, true)));
}
if ($_is_tutor && !empty($_teacher_subjects)) {
    $subjects = array_values(array_filter($subjects, fn($s) => in_array($s['subject_name'], $_teacher_subjects, true)));
}
$currentYearInt = (int) date('Y');
$years = [];
for ($y = $currentYearInt - 1; $y <= $currentYearInt + 2; $y++) {
    $years[] = $y . '-' . ($y + 1);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exams - Paper Builder</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.8/css/dataTables.bootstrap5.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">
    <link rel="stylesheet" href="../css/style.css">
    <style>
        body { background: #f5f7fb; }
        .builder-shell { min-width: 0; }
        .paper-card { border: 0; border-radius: 16px; box-shadow: 0 10px 30px rgba(15, 23, 42, 0.08); }
        .paper-list { max-height: 76vh; overflow-y: auto; }
        .paper-item { border: 1px solid #e2e8f0; border-radius: 14px; padding: 1rem; margin-bottom: 1rem; background: #fff; }
        .paper-item.active { border-color: #0d6efd; box-shadow: 0 0 0 3px rgba(13, 110, 253, 0.12); }
        .question-list-item { display: flex; align-items: flex-start; gap: .75rem; padding: .85rem 1rem; border: 1px solid #e2e8f0; border-radius: 12px; background: #fff; margin-bottom: .75rem; cursor: move; }
        .question-list-item .handle { color: #64748b; font-size: 1.1rem; }
        .question-list-item .body { flex: 1; min-width: 0; }
        .question-list-item .meta { font-size: .82rem; color: #64748b; }
        .sticky-panel { position: sticky; top: 1rem; }
        .count-chip { background: #eff6ff; color: #1d4ed8; padding: .3rem .7rem; border-radius: 999px; font-weight: 600; font-size: .85rem; }
        .bank-table td, .bank-table th { vertical-align: middle; }
        .pdf-spinner { display: none; }
        .overlay-loading { position: fixed; inset: 0; background: rgba(15, 23, 42, 0.35); display: none; align-items: center; justify-content: center; z-index: 1080; }
        .overlay-loading .card { min-width: 280px; max-width: 420px; }
        @media (max-width: 991.98px) {
            .sticky-panel { position: static; }
            .paper-list { max-height: none; }
        }
    </style>
</head>
<body>
<div class="wrapper">
    <nav id="sidebar" class="sidebar"><?php if (!defined('EDUTRACK_MODULES')) require_once __DIR__ . '/../module_definitions.php'; echo buildSidebar('exams_generator/' . basename($_SERVER['PHP_SELF'])); ?></nav>
    <div class="main-content builder-shell">
        <div class="container-fluid py-4">
            <div class="d-flex flex-wrap justify-content-between align-items-center gap-3 mb-4">
                <div>
                    <h1 class="h3 mb-1">Exams - Paper Builder</h1>
                    <p class="text-muted mb-0">Create, curate, auto-generate, and export exam papers.</p>
                </div>
                <button type="button" class="btn btn-primary" id="createPaperBtn">
                    <i class="bi bi-plus-circle me-1"></i>Create New Paper
                </button>
            </div>

            <?= examsRenderTabs('papers') ?>

            <div class="row g-4">
                <div class="col-lg-4">
                    <div class="paper-card card sticky-panel">
                        <div class="card-body">
                            <h5 class="card-title mb-3">Papers</h5>
                            <div class="row g-2 mb-3">
                                <div class="col-12">
                                    <select class="form-select" id="paperFilterClass">
                                        <option value="">All Classes</option>
                                        <?php foreach ($classes as $class): ?>
                                            <option value="<?= htmlspecialchars($class) ?>"><?= htmlspecialchars($class) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-12">
                                    <select class="form-select" id="paperFilterTerm">
                                        <option value="">All Terms</option>
                                        <option value="First Term">First Term</option>
                                        <option value="Second Term">Second Term</option>
                                        <option value="Third Term">Third Term</option>
                                    </select>
                                </div>
                                <div class="col-12">
                                    <select class="form-select" id="paperFilterYear">
                                        <option value="">All Years</option>
                                        <?php foreach ($years as $year): ?>
                                            <option value="<?= htmlspecialchars($year) ?>"><?= htmlspecialchars($year) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-12">
                                    <select class="form-select" id="paperFilterStatus">
                                        <option value="">All Statuses</option>
                                        <option value="draft">Draft</option>
                                        <option value="published">Published</option>
                                        <option value="archived">Archived</option>
                                    </select>
                                </div>
                            </div>
                            <button type="button" class="btn btn-outline-primary w-100 mb-3" id="applyPaperFilters">
                                <i class="bi bi-funnel me-1"></i>Refresh List
                            </button>
                            <div class="paper-list" id="paperList"></div>
                        </div>
                    </div>
                </div>

                <div class="col-lg-8">
                    <div class="paper-card card">
                        <div class="card-body">
                            <div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-2">
                                <div>
                                    <h5 class="card-title mb-1">Paper Editor</h5>
                                    <p class="text-muted mb-0" id="editorSubtitle">Select a paper from the list or create a new one below.</p>
                                </div>
                                <div class="d-flex flex-wrap align-items-center gap-2">
                                    <span class="count-chip">Questions: <span id="selectedQuestionCount">0</span></span>
                                    <span class="count-chip">Marks: <span id="selectedMarkCount">0</span></span>
                                    <button type="button" class="btn btn-outline-secondary btn-sm" id="previewPaperBtn" disabled><i class="bi bi-eye me-1"></i>Preview</button>
                                    <button type="button" class="btn btn-outline-success btn-sm" id="printPaperBtn" disabled><i class="bi bi-printer me-1"></i>Print</button>
                                    <button type="button" class="btn btn-outline-primary btn-sm" id="exportPdfBtn" disabled><i class="bi bi-file-earmark-pdf me-1"></i>Export PDF</button>
                                    <button type="button" class="btn btn-outline-dark btn-sm" id="exportKeyBtn" disabled><i class="bi bi-journal-check me-1"></i>Export Answer Key</button>
                                    <div class="spinner-border spinner-border-sm text-primary pdf-spinner" id="pdfSpinner" role="status"></div>
                                </div>
                            </div>
                            <div class="alert alert-info py-2 small mb-3" id="noPaperAlert">
                                <i class="bi bi-info-circle me-1"></i>
                                Fill in the form below and click <strong>Save Paper Details</strong> to create a new paper, or click <strong>Edit</strong> on a paper from the list.
                            </div>

                            <form id="paperForm" class="row g-3 mb-4">
                                <input type="hidden" name="id" id="paperId" value="0">
                                <div class="col-12">
                                    <label class="form-label">Start from a Template <span class="text-muted small">(optional — pre-fills duration, marks, instructions and the auto-generate mix)</span></label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="bi bi-grid-3x3-gap"></i></span>
                                        <select class="form-select" id="paperTemplate">
                                            <option value="">No template — start blank</option>
                                        </select>
                                    </div>
                                    <div class="form-text" id="paperTemplateHint"></div>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Title</label>
                                    <input type="text" class="form-control" name="title" id="paperTitle" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Subject</label>
                                    <select class="form-select" name="subject_id" id="paperSubject" required>
                                        <option value="">Select Subject</option>
                                        <?php foreach ($subjects as $subject): ?>
                                            <option value="<?= (int) $subject['id'] ?>"><?= htmlspecialchars($subject['subject_name']) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Class</label>
                                    <select class="form-select" name="class_name" id="paperClass" required>
                                        <option value="">Select Class</option>
                                        <?php foreach ($classes as $class): ?>
                                            <option value="<?= htmlspecialchars($class) ?>"><?= htmlspecialchars($class) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Term</label>
                                    <select class="form-select" name="term" id="paperTerm" required>
                                        <?php foreach (['First Term','Second Term','Third Term'] as $t): ?>
                                        <option value="<?= htmlspecialchars($t) ?>" <?= $t === getCurrentTerm() ? 'selected' : '' ?>><?= htmlspecialchars($t) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Academic Year</label>
                                    <input type="text" class="form-control" name="academic_year" id="paperYear" value="<?= htmlspecialchars(getAcademicYear()) ?>" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Duration (minutes)</label>
                                    <input type="number" class="form-control" name="duration_minutes" id="paperDuration" value="60" min="1" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Total Marks</label>
                                    <input type="number" class="form-control" name="total_marks" id="paperTotalMarks" value="100" min="1" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Status</label>
                                    <select class="form-select" name="status" id="paperStatus">
                                        <option value="draft">Draft</option>
                                        <option value="published">Published</option>
                                        <option value="archived">Archived</option>
                                    </select>
                                </div>
                                <div class="col-12">
                                    <label class="form-label">Instructions</label>
                                    <textarea class="form-control" name="instructions" id="paperInstructions" rows="3"></textarea>
                                </div>
                                <div class="col-12">
                                    <div class="d-flex align-items-center justify-content-between" style="cursor:pointer;" onclick="toggleSectionBlueprint()">
                                        <label class="form-label mb-0">Section Blueprint <span class="text-muted small">(optional — per-section instruction &amp; "answer any N")</span></label>
                                        <i class="bi bi-chevron-down" id="bpChevron"></i>
                                    </div>
                                    <div id="sectionBlueprintWrap" style="display:none;margin-top:.5rem;">
                                        <table class="table table-sm align-middle mb-1">
                                            <thead><tr><th>Section</th><th>Instruction (optional)</th><th style="width:150px;">Answer any N<br><span class="text-muted small">0 = all</span></th></tr></thead>
                                            <tbody id="blueprintRows"></tbody>
                                        </table>
                                        <div class="form-text mb-0">Blank instruction defaults to "Answer ALL questions in this section." Only sections that have questions appear on the paper.</div>
                                    </div>
                                    <input type="hidden" name="section_config" id="sectionConfigField">
                                </div>
                                <div class="col-12">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="bi bi-save me-1"></i>Save Paper Details
                                    </button>
                                </div>
                            </form>

                            <ul class="nav nav-pills mb-3" id="paperTabs" role="tablist">
                                <li class="nav-item" role="presentation"><button class="nav-link active" data-bs-toggle="pill" data-bs-target="#selectedQuestionsPane" type="button">Selected Questions</button></li>
                                <li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="pill" data-bs-target="#questionBankPane" type="button">Add from Bank</button></li>
                                <li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="pill" data-bs-target="#autoGeneratePane" type="button">Auto-Generate</button></li>
                            </ul>

                            <div class="tab-content">
                                <div class="tab-pane fade show active" id="selectedQuestionsPane"><div id="selectedQuestionsList"></div></div>
                                <div class="tab-pane fade" id="questionBankPane">
                                    <div class="row g-2 mb-3">
                                        <div class="col-md-3">
                                            <select class="form-select" id="bankSubject">
                                                <option value="">All Subjects</option>
                                                <?php foreach ($subjects as $subject): ?>
                                                    <option value="<?= (int) $subject['id'] ?>"><?= htmlspecialchars($subject['subject_name']) ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <select class="form-select" id="bankClass">
                                                <option value="">All Classes</option>
                                                <?php foreach ($classes as $class): ?>
                                                    <option value="<?= htmlspecialchars($class) ?>"><?= htmlspecialchars($class) ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <select class="form-select" id="bankDifficulty">
                                                <option value="">All Difficulty</option>
                                                <option value="easy">Easy</option>
                                                <option value="medium">Medium</option>
                                                <option value="hard">Hard</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <select class="form-select" id="bankType">
                                                <option value="">All Types</option>
                                                <option value="mcq">MCQ</option>
                                                <option value="fill_blank">Fill Blank</option>
                                                <option value="theory">Theory</option>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="input-group">
                                                <input type="text" class="form-control" id="bankSearch" placeholder="Search question bank">
                                                <button class="btn btn-outline-primary" type="button" id="loadBankBtn">Load</button>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="table-responsive">
                                        <table class="table table-hover bank-table align-middle" id="questionBankTable">
                                            <thead>
                                            <tr>
                                                <th style="width: 40px;"><input type="checkbox" id="selectAllBank"></th>
                                                <th>Question</th>
                                                <th>Type</th>
                                                <th>Difficulty</th>
                                                <th>Marks</th>
                                                <th>Source</th>
                                            </tr>
                                            </thead>
                                            <tbody></tbody>
                                        </table>
                                    </div>
                                    <div class="alert alert-warning py-2 small mt-3 mb-0" id="bankNoPaperNotice" style="display:none;">
                                        <i class="bi bi-exclamation-triangle me-1"></i>No paper selected. Save the paper details first, then add questions.
                                    </div>
                                    <button type="button" class="btn btn-primary mt-3" id="addSelectedQuestionsBtn" disabled>
                                        <i class="bi bi-plus-square me-1"></i>Add Selected to Paper
                                    </button>
                                </div>
                                <div class="tab-pane fade" id="autoGeneratePane">
                                    <div class="row g-3 mb-3">
                                        <div class="col-md-4">
                                            <label class="form-label">Subject</label>
                                            <select class="form-select" id="autoSubject">
                                                <option value="">Select Subject</option>
                                                <?php foreach ($subjects as $subject): ?>
                                                    <option value="<?= (int) $subject['id'] ?>"><?= htmlspecialchars($subject['subject_name']) ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">Class</label>
                                            <select class="form-select" id="autoClass">
                                                <option value="">Select Class</option>
                                                <?php foreach ($classes as $class): ?>
                                                    <option value="<?= htmlspecialchars($class) ?>"><?= htmlspecialchars($class) ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">MCQ Count</label>
                                            <input type="number" class="form-control" id="autoMcqCount" value="10" min="0">
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">Theory Count</label>
                                            <input type="number" class="form-control" id="autoTheoryCount" value="3" min="0">
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">Fill Blank Count</label>
                                            <input type="number" class="form-control" id="autoFillCount" value="2" min="0">
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">Easy %</label>
                                            <input type="number" class="form-control" id="autoEasyPct" value="40" min="0" max="100">
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">Medium %</label>
                                            <input type="number" class="form-control" id="autoMediumPct" value="40" min="0" max="100">
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">Hard %</label>
                                            <input type="number" class="form-control" id="autoHardPct" value="20" min="0" max="100">
                                        </div>
                                    </div>
                                    <div class="d-flex gap-2 mb-3">
                                        <button type="button" class="btn btn-outline-primary" id="previewAutoGenerateBtn">
                                            <i class="bi bi-stars me-1"></i>Generate Preview
                                        </button>
                                        <button type="button" class="btn btn-primary" id="confirmAutoGenerateBtn" disabled>
                                            <i class="bi bi-check2-circle me-1"></i>Confirm and Add to Paper
                                        </button>
                                    </div>
                                    <div id="autoGeneratePreview" class="small text-muted">Generate a preview to review AI-prioritized question selection.</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="overlay-loading" id="pdfOverlay">
    <div class="card shadow-lg">
        <div class="card-body text-center p-4">
            <div class="spinner-border text-primary mb-3" role="status"></div>
            <h5 class="mb-2">Preparing PDF</h5>
            <p class="text-muted mb-0">Generating the export file. This tab will open automatically.</p>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.datatables.net/1.13.8/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.8/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.2/Sortable.min.js"></script>
<script>
const paperState = { selectedPaperId: 0, selectedQuestions: [], autoGeneratedQuestions: [] };
let bankDataTable = null;
let sortableInstance = null;

function escapeHtml(value) {
    return String(value ?? '').replace(/[&<>"']/g, function (char) {
        return {'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;'}[char];
    });
}

function sourceBadge(source) {
    if (source === 'AI') return '<span class="badge bg-primary-subtle text-primary">AI</span>';
    if (source === 'Imported') return '<span class="badge bg-success-subtle text-success">Imported</span>';
    return '<span class="badge bg-secondary-subtle text-secondary">Manual</span>';
}

function statusBadge(status) {
    const map = {draft: 'secondary', published: 'success', archived: 'dark'};
    const cls = map[status] || 'secondary';
    return '<span class="badge bg-' + cls + '-subtle text-' + cls + '">' + escapeHtml(status) + '</span>';
}

async function fetchJson(url, options = {}) {
    const response = await fetch(url, options);
    const data = await response.json();
    if (!response.ok) throw new Error(data.message || 'Request failed');
    return data;
}

function resetPaperForm() {
    document.getElementById('paperForm').reset();
    document.getElementById('paperId').value = '0';
    document.getElementById('paperYear').value = <?= json_encode(getAcademicYear()) ?>;
    document.getElementById('paperTerm').value = <?= json_encode(getCurrentTerm()) ?>;
    document.getElementById('paperDuration').value = '60';
    document.getElementById('paperTotalMarks').value = '100';
    document.getElementById('paperStatus').value = 'draft';
    renderBlueprintRows();
    applySectionBlueprint({});
    paperState.selectedPaperId = 0;
    paperState.selectedQuestions = [];
    updatePaperActionButtons();
    renderSelectedQuestions([]);
}

function updatePaperActionButtons() {
    const hasPaper = paperState.selectedPaperId > 0;
    document.getElementById('previewPaperBtn').disabled = !hasPaper;
    document.getElementById('printPaperBtn').disabled = !hasPaper;
    document.getElementById('exportPdfBtn').disabled = !hasPaper;
    document.getElementById('exportKeyBtn').disabled = !hasPaper;
    document.getElementById('noPaperAlert').style.display = hasPaper ? 'none' : '';
    document.getElementById('editorSubtitle').textContent = hasPaper
        ? 'Editing paper #' + paperState.selectedPaperId + '. Add questions using the tabs below.'
        : 'Select a paper from the list or create a new one below.';
}

async function loadPapers() {
    const list = document.getElementById('paperList');
    const formData = new URLSearchParams({
        class_name: document.getElementById('paperFilterClass').value,
        term: document.getElementById('paperFilterTerm').value,
        academic_year: document.getElementById('paperFilterYear').value,
        status: document.getElementById('paperFilterStatus').value
    });
    let data;
    try {
        data = await fetchJson('ajax/get_papers.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: formData.toString()
        });
    } catch (err) {
        list.innerHTML = '<div class="text-danger small">Failed to load papers: ' + escapeHtml(err.message || 'Unknown error') + '</div>';
        return;
    }
    if (!Array.isArray(data) || data.length === 0) {
        list.innerHTML = '<div class="text-muted small">No papers found for the selected filters.</div>';
        return;
    }
    list.innerHTML = data.map((paper) => {
        const activeClass = Number(paper.id) === paperState.selectedPaperId ? ' active' : '';
        return `<div class="paper-item${activeClass}" data-paper-id="${paper.id}">
            <div class="d-flex justify-content-between align-items-start gap-2 mb-2">
                <div><h6 class="mb-1">${escapeHtml(paper.title)}</h6><div class="small text-muted">${escapeHtml(paper.class_name)} • ${escapeHtml(paper.subject_name || 'No Subject')}</div></div>
                ${statusBadge(paper.status)}
            </div>
            <div class="small text-muted mb-3">Duration: ${Number(paper.duration_minutes)} mins • Total Marks: ${Number(paper.total_marks)} • Questions: ${Number(paper.question_count || 0)}</div>
            <div class="d-flex flex-wrap gap-2">
                <button type="button" class="btn btn-sm btn-outline-primary" onclick="selectPaper(${paper.id})">Edit</button>
                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="previewPaper(${paper.id})">Preview</button>
                <button type="button" class="btn btn-sm btn-outline-success" onclick="printPaper(${paper.id})">Print</button>
                <button type="button" class="btn btn-sm btn-outline-dark" onclick="exportPaperPdf(${paper.id}, 'exam')">Export PDF</button>
                <button type="button" class="btn btn-sm btn-outline-warning" onclick="exportPaperPdf(${paper.id}, 'key')">Answer Key</button>
                <button type="button" class="btn btn-sm btn-outline-danger" onclick="deletePaper(${paper.id})">Delete</button>
            </div>
        </div>`;
    }).join('');
}

async function selectPaper(paperId) {
    try {
        const listData = await fetchJson('ajax/get_papers.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: new URLSearchParams({id: String(paperId)}).toString()
        }).catch(() => null);
        if (Array.isArray(listData)) {
            const paper = listData.find((item) => Number(item.id) === Number(paperId));
            if (paper) {
                document.getElementById('paperId').value = paper.id;
                document.getElementById('paperTitle').value = paper.title || '';
                document.getElementById('paperSubject').value = paper.subject_id || '';
                document.getElementById('paperClass').value = paper.class_name || '';
                document.getElementById('paperTerm').value = paper.term || <?= json_encode(getCurrentTerm()) ?>;
                document.getElementById('paperYear').value = paper.academic_year || '';
                document.getElementById('paperDuration').value = paper.duration_minutes || 60;
                document.getElementById('paperTotalMarks').value = paper.total_marks || 100;
                document.getElementById('paperInstructions').value = paper.instructions || '';
                applySectionBlueprint(paper.section_config);
                document.getElementById('paperStatus').value = paper.status || 'draft';
            }
        }
        paperState.selectedPaperId = Number(paperId);
        updatePaperActionButtons();
        updateAddSelectedButton();
        await loadPapers();
        await loadSelectedQuestions();
    } catch (err) {
        alert('Error loading paper: ' + (err.message || 'Unknown error'));
    }
}

async function loadSelectedQuestions() {
    if (!paperState.selectedPaperId) {
        renderSelectedQuestions([]);
        return;
    }
    try {
        const data = await fetchJson('ajax/get_paper_questions.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: new URLSearchParams({paper_id: String(paperState.selectedPaperId)}).toString()
        });
        paperState.selectedQuestions = Array.isArray(data.questions) ? data.questions : (Array.isArray(data) ? data : []);
        renderSelectedQuestions(paperState.selectedQuestions);
    } catch (err) {
        document.getElementById('selectedQuestionsList').innerHTML =
            '<div class="text-danger small">Failed to load questions: ' + escapeHtml(err.message || 'Unknown error') + '</div>';
    }
}

function renderSelectedQuestions(questions) {
    const list = document.getElementById('selectedQuestionsList');
    const totalMarks = questions.reduce((sum, item) => sum + Number(item.marks || 0), 0);
    document.getElementById('selectedQuestionCount').textContent = String(questions.length);
    document.getElementById('selectedMarkCount').textContent = String(totalMarks);
    if (!questions.length) {
        list.innerHTML = '<div class="text-muted small">No questions selected yet.</div>';
        return;
    }
    list.innerHTML = questions.map((item) => `<div class="question-list-item" data-question-id="${item.question_id || item.id}">
        <div class="handle"><i class="bi bi-grip-vertical"></i></div>
        <div class="body">
            <div class="fw-semibold mb-1">${escapeHtml(item.question)}</div>
            <div class="meta d-flex align-items-center flex-wrap gap-2">
                <span>${escapeHtml(item.question_type)} • ${escapeHtml(item.difficulty || 'medium')} • ${sourceBadge(item.source || 'Manual')}</span>
                <label class="d-flex align-items-center gap-1 mb-0" style="font-size:.8rem;">
                    <span class="text-muted">Marks:</span>
                    <input type="number" class="form-control form-control-sm marks-input"
                           value="${Number(item.marks)}" min="1" max="100" step="1"
                           style="width:4.5rem;"
                           data-question-id="${item.question_id || item.id}"
                           onchange="updateQuestionMarks(this)"
                           onblur="updateQuestionMarks(this)">
                </label>
            </div>
        </div>
        <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeQuestion(${item.question_id || item.id})"><i class="bi bi-trash"></i></button>
    </div>`).join('');
    if (sortableInstance) { sortableInstance.destroy(); sortableInstance = null; }
    sortableInstance = Sortable.create(list, {animation: 150, handle: '.handle', onEnd: saveQuestionOrder});
}

async function saveQuestionOrder() {
    if (!paperState.selectedPaperId) return;
    const order = Array.from(document.querySelectorAll('#selectedQuestionsList [data-question-id]')).map((node) => Number(node.dataset.questionId));
    try {
        await fetchJson('ajax/reorder_paper_questions.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: new URLSearchParams({paper_id: String(paperState.selectedPaperId), order: JSON.stringify(order)}).toString()
        });
        await loadSelectedQuestions();
    } catch (err) {
        console.error('Reorder failed:', err.message);
    }
}

async function updateQuestionMarks(input) {
    if (!paperState.selectedPaperId) return;
    const qId  = Number(input.dataset.questionId);
    const marks = Math.max(1, parseInt(input.value, 10) || 1);
    input.value = String(marks);
    try {
        const data = await fetchJson('ajax/update_question_marks.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: new URLSearchParams({
                paper_id:    String(paperState.selectedPaperId),
                question_id: String(qId),
                marks:       String(marks)
            }).toString()
        });
        if (data.success) {
            // Sync in-memory state so total recalculates correctly
            const q = paperState.selectedQuestions.find((item) => Number(item.question_id || item.id) === qId);
            if (q) { q.marks = marks; }
            const total = paperState.selectedQuestions.reduce((sum, item) => sum + Number(item.marks || 0), 0);
            document.getElementById('selectedMarkCount').textContent = String(total);
        }
    } catch (err) {
        console.error('Marks update failed:', err.message);
    }
}

async function loadQuestionBank() {
    const tbody = document.querySelector('#questionBankTable tbody');
    tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted py-4">Loading questions...</td></tr>';
    const params = new URLSearchParams({
        subject_id: document.getElementById('bankSubject').value,
        class_name: document.getElementById('bankClass').value,
        difficulty: document.getElementById('bankDifficulty').value,
        question_type: document.getElementById('bankType').value,
        search: document.getElementById('bankSearch').value
    });
    let data;
    try {
        data = await fetchJson('ajax/get_questions.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: params.toString()
        });
    } catch (err) {
        tbody.innerHTML = '<tr><td colspan="6" class="text-center text-danger py-4">Failed to load questions: ' + escapeHtml(err.message || 'Unknown error') + '</td></tr>';
        return;
    }
    const selectedIds = new Set(paperState.selectedQuestions.map((item) => Number(item.question_id || item.id)));
    const rows = (Array.isArray(data) ? data : []).filter((item) => !selectedIds.has(Number(item.id)));
    tbody.innerHTML = rows.length ? rows.map((item) => `<tr>
        <td><input type="checkbox" class="bank-question-checkbox" value="${item.id}"></td>
        <td><div class="fw-semibold">${escapeHtml(item.question)}</div><div class="small text-muted">${escapeHtml(item.subject_name || '')} • ${escapeHtml(item.class_name || '')}</div></td>
        <td>${escapeHtml(item.question_type)}</td>
        <td>${escapeHtml(item.difficulty)}</td>
        <td>${Number(item.marks)}</td>
        <td>${sourceBadge(item.source || 'Manual')}</td>
    </tr>`).join('') : '<tr><td colspan="6" class="text-center text-muted py-4">No available questions match these filters.</td></tr>';
    if (bankDataTable) { bankDataTable.destroy(); bankDataTable = null; }
    if (document.getElementById('questionBankPane').classList.contains('active')) {
        bankDataTable = $('#questionBankTable').DataTable({paging: true, searching: false, info: false, ordering: false, pageLength: 8, lengthChange: false});
    }
    updateAddSelectedButton();
}

function updateAddSelectedButton() {
    const checked = document.querySelectorAll('.bank-question-checkbox:checked').length;
    const hasPaper = paperState.selectedPaperId > 0;
    document.getElementById('addSelectedQuestionsBtn').disabled = checked === 0 || !hasPaper;
    document.getElementById('bankNoPaperNotice').style.display = (!hasPaper && checked > 0) ? '' : 'none';
}

async function addSelectedQuestions() {
    if (!paperState.selectedPaperId) {
        alert('Save the paper details first.');
        return;
    }
    const selected = Array.from(document.querySelectorAll('.bank-question-checkbox:checked')).map((node) => Number(node.value));
    try {
        for (const questionId of selected) {
            await fetchJson('ajax/add_question_to_paper.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: new URLSearchParams({paper_id: String(paperState.selectedPaperId), question_id: String(questionId), marks: '1'}).toString()
            });
        }
        await loadSelectedQuestions();
        await loadQuestionBank();
    } catch (err) {
        alert('Error adding questions: ' + (err.message || 'Unknown error'));
    }
}

async function removeQuestion(questionId) {
    if (!paperState.selectedPaperId) return;
    try {
        await fetchJson('ajax/remove_question_from_paper.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: new URLSearchParams({paper_id: String(paperState.selectedPaperId), question_id: String(questionId)}).toString()
        });
        await loadSelectedQuestions();
        await loadQuestionBank();
    } catch (err) {
        alert('Error removing question: ' + (err.message || 'Unknown error'));
    }
}

async function previewAutoGenerate() {
    const easy = Number(document.getElementById('autoEasyPct').value || 0);
    const medium = Number(document.getElementById('autoMediumPct').value || 0);
    const hard = Number(document.getElementById('autoHardPct').value || 0);
    if (easy + medium + hard !== 100) {
        alert('Difficulty percentages must sum to 100.');
        return;
    }
    const preview = document.getElementById('autoGeneratePreview');
    preview.innerHTML = '<span class="text-muted"><i class="bi bi-hourglass-split me-1"></i>Loading questions…</span>';
    try {
        const data = await fetchJson('ajax/auto_generate_paper.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: new URLSearchParams({
                subject_id: document.getElementById('autoSubject').value,
                class_name: document.getElementById('autoClass').value,
                mcq_count: document.getElementById('autoMcqCount').value,
                theory_count: document.getElementById('autoTheoryCount').value,
                fill_blank_count: document.getElementById('autoFillCount').value,
                easy_pct: String(easy),
                medium_pct: String(medium),
                hard_pct: String(hard)
            }).toString()
        });
        paperState.autoGeneratedQuestions = Array.isArray(data.questions) ? data.questions : [];
        document.getElementById('confirmAutoGenerateBtn').disabled = !paperState.autoGeneratedQuestions.length || !paperState.selectedPaperId;
        if (!paperState.autoGeneratedQuestions.length) {
            preview.innerHTML = '<span class="text-danger">No matching questions found for the selected mix.</span>';
            return;
        }
        preview.innerHTML = paperState.autoGeneratedQuestions.map((item, index) => `<div class="question-list-item" data-question-id="${item.id}">
            <div class="handle text-muted">${index + 1}</div>
            <div class="body">
                <div class="fw-semibold mb-1">${escapeHtml(item.question)}</div>
                <div class="meta">${escapeHtml(item.question_type)} • ${escapeHtml(item.difficulty)} • ${Number(item.marks)} mark(s) • ${sourceBadge(item.source || (Number(item.ai_generated) === 1 ? 'AI' : 'Manual'))}</div>
            </div>
        </div>`).join('');
    } catch (err) {
        preview.innerHTML = '<span class="text-danger">Error: ' + escapeHtml(err.message || 'Failed to load preview') + '</span>';
    }
}

async function confirmAutoGenerate() {
    if (!paperState.selectedPaperId || !paperState.autoGeneratedQuestions.length) return;
    try {
        for (const question of paperState.autoGeneratedQuestions) {
            await fetchJson('ajax/add_question_to_paper.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: new URLSearchParams({paper_id: String(paperState.selectedPaperId), question_id: String(question.id), marks: String(question.marks || 1)}).toString()
            });
        }
        paperState.autoGeneratedQuestions = [];
        document.getElementById('autoGeneratePreview').innerHTML = '<span class="text-success">Auto-generated selection added to the paper.</span>';
        document.getElementById('confirmAutoGenerateBtn').disabled = true;
        await loadSelectedQuestions();
        await loadQuestionBank();
    } catch (err) {
        alert('Error adding auto-generated questions: ' + (err.message || 'Unknown error'));
    }
}

async function savePaper(event) {
    event.preventDefault();
    try {
        document.getElementById('sectionConfigField').value = serializeSectionBlueprint();
        const data = await fetchJson('ajax/save_paper.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: new URLSearchParams(new FormData(event.currentTarget)).toString()
        });
        if (data.paper_id) {
            paperState.selectedPaperId = Number(data.paper_id);
            document.getElementById('paperId').value = String(data.paper_id);
            updatePaperActionButtons();
            updateAddSelectedButton();
            await loadPapers();
            await loadSelectedQuestions();
        }
        alert(data.message || 'Paper saved successfully.');
    } catch (err) {
        alert('Error saving paper: ' + (err.message || 'Unknown error'));
    }
}

async function deletePaper(paperId) {
    if (!confirm('Delete this paper?')) return;
    try {
        await fetchJson('ajax/delete_paper.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: new URLSearchParams({id: String(paperId)}).toString()
        });
        if (paperState.selectedPaperId === Number(paperId)) resetPaperForm();
        await loadPapers();
    } catch (err) {
        alert('Error deleting paper: ' + (err.message || 'Unknown error'));
    }
}

function openPdfOverlay() {
    document.getElementById('pdfOverlay').style.display = 'flex';
    document.getElementById('pdfSpinner').style.display = 'inline-block';
}

function closePdfOverlay() {
    document.getElementById('pdfOverlay').style.display = 'none';
    document.getElementById('pdfSpinner').style.display = 'none';
}

function exportPaperPdf(paperId, type) {
    openPdfOverlay();
    window.open('ajax/export_pdf.php?paper_id=' + encodeURIComponent(paperId) + '&type=' + encodeURIComponent(type), '_blank', 'noopener');
    setTimeout(closePdfOverlay, 2500);
}

function previewPaper(paperId) {
    window.open('print_paper.php?paper_id=' + encodeURIComponent(paperId), '_blank', 'noopener');
}

function printPaper(paperId) {
    window.open('print_paper.php?paper_id=' + encodeURIComponent(paperId), '_blank', 'noopener');
}

// ── Paper templates (Phase 5) ──────────────────────────────────────────────
// ── Section blueprint (Phase 5b) ───────────────────────────────────────────
const BLUEPRINT_TYPES = [['mcq','Multiple Choice'],['true_false','True or False'],['matching','Matching'],['fill_blank','Fill in the Blank'],['comprehension','Comprehension'],['theory','Short Answer / Theory']];
function renderBlueprintRows() {
    const tb = document.getElementById('blueprintRows');
    if (!tb || tb.children.length) return; // render once
    tb.innerHTML = BLUEPRINT_TYPES.map(function (pair) {
        const t = pair[0], label = pair[1];
        return '<tr><td>' + label + '</td>'
            + '<td><input type="text" class="form-control form-control-sm" id="bp_instr_' + t + '" placeholder="Answer ALL questions in this section."></td>'
            + '<td><input type="number" min="0" class="form-control form-control-sm" id="bp_choose_' + t + '" value="0"></td></tr>';
    }).join('');
}
function serializeSectionBlueprint() {
    const cfg = {};
    BLUEPRINT_TYPES.forEach(function (pair) {
        const t = pair[0];
        const instrEl = document.getElementById('bp_instr_' + t);
        const chooseEl = document.getElementById('bp_choose_' + t);
        const instr = instrEl ? instrEl.value.trim() : '';
        const choose = chooseEl ? (parseInt(chooseEl.value, 10) || 0) : 0;
        const o = {};
        if (instr) o.instruction = instr;
        if (choose > 0) o.choose = choose;
        if (Object.keys(o).length) cfg[t] = o;
    });
    return JSON.stringify(cfg);
}
function applySectionBlueprint(raw) {
    let cfg = {};
    if (raw && typeof raw === 'string') { try { cfg = JSON.parse(raw) || {}; } catch (e) { cfg = {}; } }
    else if (raw && typeof raw === 'object') { cfg = raw; }
    BLUEPRINT_TYPES.forEach(function (pair) {
        const t = pair[0], c = cfg[t] || {};
        const i = document.getElementById('bp_instr_' + t); if (i) i.value = c.instruction || '';
        const n = document.getElementById('bp_choose_' + t); if (n) n.value = c.choose || 0;
    });
}
function toggleSectionBlueprint() {
    const w = document.getElementById('sectionBlueprintWrap');
    if (!w) return;
    const open = w.style.display !== 'none';
    w.style.display = open ? 'none' : 'block';
    const ch = document.getElementById('bpChevron'); if (ch) ch.className = open ? 'bi bi-chevron-down' : 'bi bi-chevron-up';
}

let paperTemplates = [];

async function loadTemplates() {
    try {
        const data = await fetchJson('ajax/get_templates.php');
        paperTemplates = (data && data.templates) || [];
        const select = document.getElementById('paperTemplate');
        select.innerHTML = '<option value="">No template — start blank</option>'
            + paperTemplates.map((t, i) => '<option value="' + i + '">' + escapeHtml(t.name) + '</option>').join('');
    } catch (error) {
        console.error('Failed to load templates', error);
    }
}

function applyTemplate() {
    const idx = document.getElementById('paperTemplate').value;
    const hint = document.getElementById('paperTemplateHint');
    if (idx === '') { hint.textContent = ''; return; }
    const tpl = paperTemplates[parseInt(idx, 10)];
    if (!tpl) return;
    const s = tpl.structure || {};

    if (s.duration_minutes) document.getElementById('paperDuration').value = s.duration_minutes;
    if (s.total_marks)      document.getElementById('paperTotalMarks').value = s.total_marks;
    if (typeof s.instructions === 'string') document.getElementById('paperInstructions').value = s.instructions;

    // Pre-fill the Auto-Generate mix when present.
    const a = s.auto || {};
    const setVal = (id, val) => { const el = document.getElementById(id); if (el && val !== undefined) el.value = val; };
    setVal('autoMcqCount',   a.mcq_count);
    setVal('autoTheoryCount', a.theory_count);
    setVal('autoFillCount',  a.fill_count);
    setVal('autoEasyPct',    a.easy_pct);
    setVal('autoMediumPct',  a.medium_pct);
    setVal('autoHardPct',    a.hard_pct);

    hint.textContent = (tpl.description || '') + ' Applied — adjust any field before saving.';
}

document.getElementById('paperTemplate').addEventListener('change', applyTemplate);

document.getElementById('paperForm').addEventListener('submit', savePaper);
document.getElementById('createPaperBtn').addEventListener('click', async () => {
    resetPaperForm();
    await loadPapers();
    await loadQuestionBank();
});
document.getElementById('applyPaperFilters').addEventListener('click', loadPapers);
document.getElementById('loadBankBtn').addEventListener('click', loadQuestionBank);
document.getElementById('addSelectedQuestionsBtn').addEventListener('click', addSelectedQuestions);
document.getElementById('previewAutoGenerateBtn').addEventListener('click', previewAutoGenerate);
document.getElementById('confirmAutoGenerateBtn').addEventListener('click', confirmAutoGenerate);
document.getElementById('previewPaperBtn').addEventListener('click', () => previewPaper(paperState.selectedPaperId));
document.getElementById('printPaperBtn').addEventListener('click', () => printPaper(paperState.selectedPaperId));
document.getElementById('exportPdfBtn').addEventListener('click', () => exportPaperPdf(paperState.selectedPaperId, 'exam'));
document.getElementById('exportKeyBtn').addEventListener('click', () => exportPaperPdf(paperState.selectedPaperId, 'key'));
document.getElementById('selectAllBank').addEventListener('change', (event) => {
    document.querySelectorAll('.bank-question-checkbox').forEach((checkbox) => { checkbox.checked = event.target.checked; });
    updateAddSelectedButton();
});
document.addEventListener('change', (event) => {
    if (event.target.classList.contains('bank-question-checkbox')) updateAddSelectedButton();
});

document.querySelector('[data-bs-target="#questionBankPane"]').addEventListener('shown.bs.tab', function () {
    if (!bankDataTable) {
        bankDataTable = $('#questionBankTable').DataTable({paging: true, searching: false, info: false, ordering: false, pageLength: 8, lengthChange: false});
    } else {
        bankDataTable.columns.adjust().draw(false);
    }
});

resetPaperForm();
loadTemplates();
loadPapers().then(loadQuestionBank).catch((error) => {
    console.error(error);
    alert(error.message || 'Failed to load paper builder data.');
});
</script>
</body>
</html>
