<?php
declare(strict_types=1);
session_start();
require_once '../config.php';
requireModule('exams');
require_once __DIR__ . '/helpers.php';
if (!isset($_SESSION['user_id'])) { header('Location: ../login.php'); exit; }

$conn = getDBConnection();
if (!$conn instanceof mysqli) { http_response_code(500); exit('Database connection failed.'); }
$subjects     = examsGetSubjects($conn);
$classOptions = 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)) {
    $classOptions = array_values(array_filter($classOptions, 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)));
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exams - AI Paper Generator</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="../css/style.css">
    <style>
        .progress-overlay{position:fixed;inset:0;background:rgba(13,27,42,.72);display:none;align-items:center;justify-content:center;z-index:3000}
        .progress-card{background:#fff;border-radius:1rem;padding:2rem;max-width:520px;width:calc(100% - 2rem);box-shadow:0 1rem 3rem rgba(0,0,0,.2)}
        .format-status-box{border:1px dashed #9cb3d1;border-radius:.75rem;padding:1rem;background:#f8fbff;}
        .question-editor{border:1px solid #e2e8f0;border-radius:12px;padding:1rem;margin-bottom:1rem;background:#fff;}
    </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 id="content" class="content">
        <header class="top-navbar d-flex justify-content-between align-items-center flex-wrap gap-2">
            <div>
                <h4 class="mb-1">Exams - AI Paper Generator</h4>
                <div class="text-muted small">Generate a full structured exam paper (sections, marks, model answers, rubrics) that goes through review, approval, and publishing.</div>
            </div>
            <span class="badge bg-secondary" id="generatorBadge">Generator: idle</span>
        </header>
        <main class="container-fluid py-4">
            <?= examsRenderTabs('paper-generator') ?>
            <div id="generatorStatus"></div>

            <div class="row g-4">
                <div class="col-lg-5">
                    <div class="card shadow-sm border-0 mb-4">
                        <div class="card-header"><h5 class="mb-0">Step 1 — Class &amp; Subject</h5></div>
                        <div class="card-body">
                            <div class="row g-3">
                                <div class="col-md-4"><label class="form-label">Subject</label><select id="subjectSelect" class="form-select"><option value="">Select Subject</option><?php foreach ($subjects as $subject): ?><option value="<?= (int) $subject['id'] ?>"><?= htmlspecialchars((string) $subject['subject_name']) ?></option><?php endforeach; ?></select></div>
                                <div class="col-md-4"><label class="form-label">Class</label><select id="classSelect" class="form-select"><option value="">Select Class</option><?php foreach ($classOptions 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 id="termSelect" class="form-select"><?php foreach (examsTerms() as $term): ?><option value="<?= htmlspecialchars($term) ?>"><?= htmlspecialchars($term) ?></option><?php endforeach; ?></select></div>
                            </div>
                        </div>
                    </div>

                    <div class="card shadow-sm border-0 mb-4">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">Exam Format / Standard</h5>
                            <span class="text-muted small">Upload once per subject &amp; class</span>
                        </div>
                        <div class="card-body">
                            <div class="format-status-box mb-3" id="formatProfileStatus">
                                <div class="text-muted small">Select a subject and class to see or set this school's exam format.</div>
                            </div>
                            <button type="button" class="btn btn-sm btn-outline-primary mb-3" id="useSchoolFormatBtn" disabled>
                                <i class="fas fa-magic me-1"></i>Use School Format
                            </button>

                            <div class="accordion" id="formatUploadAccordion">
                                <div class="accordion-item">
                                    <h2 class="accordion-header">
                                        <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#formatUploadBody">
                                            Upload / Replace Sample Paper
                                        </button>
                                    </h2>
                                    <div id="formatUploadBody" class="accordion-collapse collapse">
                                        <div class="accordion-body">
                                            <div class="mb-2">
                                                <label class="form-label small">Sample file (PDF, Word, image)</label>
                                                <input type="file" class="form-control form-control-sm" id="formatProfileFile" accept=".pdf,.docx,.doc,.txt,.jpg,.jpeg,.png,.webp">
                                            </div>
                                            <div class="mb-2 text-center text-muted small">— or —</div>
                                            <div class="mb-2">
                                                <label class="form-label small">Paste sample exam text</label>
                                                <textarea class="form-control form-control-sm" id="formatProfileText" rows="4" placeholder="Paste a past exam paper's text here..."></textarea>
                                            </div>
                                            <button type="button" class="btn btn-sm btn-primary" id="uploadFormatProfileBtn">
                                                <i class="fas fa-upload me-1"></i>Analyze &amp; Save
                                            </button>
                                            <button type="button" class="btn btn-sm btn-outline-danger" id="clearFormatProfileBtn">
                                                <i class="fas fa-trash me-1"></i>Clear
                                            </button>
                                            <div class="form-text">The AI studies this sample's structure and style only — it will not copy its questions.</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card shadow-sm border-0">
                        <div class="card-header"><h5 class="mb-0">Step 2 — Study Materials</h5></div>
                        <div class="card-body">
                            <div class="small text-muted mb-2">Content the AI draws questions from. <a href="upload_materials.php" target="_blank">Upload materials</a> for this class/subject if the list below is empty.</div>
                            <div id="materialsList"><div class="alert alert-info py-2 small mb-0">Select a class and subject to view materials.</div></div>
                        </div>
                    </div>
                </div>

                <div class="col-lg-7">
                    <div class="card shadow-sm border-0 mb-4">
                        <div class="card-header"><h5 class="mb-0">Step 3 — Configure &amp; Generate</h5></div>
                        <div class="card-body">
                            <div class="row g-3">
                                <div class="col-md-8"><label class="form-label">Exam Title</label><input type="text" id="examTitle" class="form-control" placeholder="e.g. Mathematics Mid-Term Examination"></div>
                                <div class="col-md-4">
                                    <label class="form-label d-block">Exam Type</label>
                                    <div class="btn-group" role="group">
                                        <input type="radio" class="btn-check" name="examType" id="examTypeMid" value="mid_term" checked>
                                        <label class="btn btn-outline-primary btn-sm" for="examTypeMid">Mid-Term</label>
                                        <input type="radio" class="btn-check" name="examType" id="examTypeEnd" value="end_term">
                                        <label class="btn btn-outline-primary btn-sm" for="examTypeEnd">End of Term</label>
                                    </div>
                                </div>
                                <div class="col-md-6"><label class="form-label">Duration (minutes)</label><input type="number" id="duration" class="form-control" value="60" min="1"></div>
                                <div class="col-md-6"><label class="form-label">Total Marks</label><input type="number" id="totalMarks" class="form-control" value="100" min="1"></div>

                                <div class="col-12"><hr class="my-1"><h6 class="mb-0">Question Sections</h6></div>
                                <div class="col-md-4">
                                    <div class="form-check mb-2"><input class="form-check-input" type="checkbox" id="formatObjective" checked><label class="form-check-label fw-semibold" for="formatObjective">Objective</label></div>
                                    <input type="number" id="objCount" class="form-control form-control-sm mb-1" value="20" min="0" placeholder="Question count">
                                    <input type="number" id="objMarks" class="form-control form-control-sm" value="2" min="1" placeholder="Marks each">
                                </div>
                                <div class="col-md-4">
                                    <div class="form-check mb-2"><input class="form-check-input" type="checkbox" id="formatSubjective" checked><label class="form-check-label fw-semibold" for="formatSubjective">Theory</label></div>
                                    <input type="number" id="subjCount" class="form-control form-control-sm mb-1" value="5" min="0" placeholder="Question count">
                                    <input type="number" id="subjMarks" class="form-control form-control-sm" value="8" min="1" placeholder="Marks each">
                                </div>
                                <div class="col-md-4">
                                    <div class="form-check mb-2"><input class="form-check-input" type="checkbox" id="formatComprehension"><label class="form-check-label fw-semibold" for="formatComprehension">Comprehension</label></div>
                                    <div class="text-muted small">One passage with derived questions.</div>
                                </div>

                                <div class="col-12"><label class="form-label">Teacher Instructions for the AI (optional)</label><textarea id="aiNotes" class="form-control" rows="2" placeholder="e.g. Emphasize word problems over pure computation."></textarea></div>
                                <div class="col-12"><label class="form-label">Topics to Emphasize (optional)</label><textarea id="topics" class="form-control" rows="2" placeholder="e.g. Fractions, Decimals, Ratio"></textarea></div>
                                <div class="col-12"><label class="form-label">Sample Question Patterns to Imitate (optional)</label><textarea id="sampleQuestions" class="form-control" rows="2" placeholder="Paste 1-2 example questions in the style you want, if you have them."></textarea></div>

                                <div class="col-12"><button type="button" class="btn btn-primary" id="generateBtn" onclick="generateExam()"><i class="fas fa-magic me-1"></i>Generate Exam Paper</button></div>
                            </div>
                        </div>
                    </div>

                    <div class="card shadow-sm border-0" id="questionBankCard">
                        <div class="card-header"><h5 class="mb-0">Question Bank (insert into the editor after generating)</h5></div>
                        <div class="card-body" id="questionBankPanel">
                            <div class="alert alert-info py-2 small mb-0">Select a class and subject to load the question bank.</div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row g-4 mt-1" id="previewSection" style="display:none;">
                <div class="col-lg-5">
                    <div class="card shadow-sm border-0 mb-4">
                        <div class="card-header"><h5 class="mb-0">Edit Draft</h5></div>
                        <div class="card-body">
                            <div class="row g-2 mb-3">
                                <div class="col-12"><label class="form-label small">Title</label><input type="text" id="editorExamTitle" class="form-control form-control-sm"></div>
                                <div class="col-md-6"><label class="form-label small">Duration (mins)</label><input type="number" id="editorDuration" class="form-control form-control-sm"></div>
                                <div class="col-md-6"><label class="form-label small">Total Marks</label><input type="number" id="editorTotalMarks" class="form-control form-control-sm"></div>
                                <div class="col-12"><label class="form-label small">Instructions</label><textarea id="editorInstructions" class="form-control form-control-sm" rows="2"></textarea></div>
                            </div>
                            <div id="editorSections"></div>
                            <div class="d-flex flex-wrap gap-2 mt-2">
                                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="renderPreviewFromEditor()"><i class="fas fa-sync-alt me-1"></i>Refresh Preview</button>
                                <button type="button" class="btn btn-sm btn-primary" onclick="saveExamEdits()"><i class="fas fa-save me-1"></i>Save Changes</button>
                                <button type="button" class="btn btn-sm btn-outline-success" onclick="saveCurrentExamToBank()"><i class="fas fa-database me-1"></i>Save Questions to Bank</button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-lg-7">
                    <div id="workflowPanel" class="mb-4"></div>
                    <div class="card shadow-sm border-0">
                        <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
                            <h5 class="mb-0">Preview</h5>
                            <div class="d-flex gap-2 flex-wrap">
                                <div class="btn-group btn-group-sm">
                                    <button type="button" class="btn btn-outline-secondary" onclick="setPreviewVersion('student')">Student Copy</button>
                                    <button type="button" class="btn btn-outline-secondary" onclick="setPreviewVersion('teacher')">Teacher Guide</button>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-primary" id="downloadPdfBtn" disabled onclick="downloadPDF()"><i class="fas fa-file-pdf me-1"></i>Download PDF</button>
                                <button type="button" class="btn btn-sm btn-outline-dark" id="teacherPdfBtn" disabled onclick="setPreviewVersion('teacher');downloadPDF();"><i class="fas fa-key me-1"></i>Answer Key PDF</button>
                                <button type="button" class="btn btn-sm btn-outline-secondary" id="printExamBtn" disabled onclick="printExam()"><i class="fas fa-print me-1"></i>Print</button>
                            </div>
                        </div>
                        <div class="card-body">
                            <div id="examPreview" class="text-muted">Generate an exam to see the preview here.</div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<div class="progress-overlay" id="loadingOverlay">
    <div class="progress-card text-center">
        <div class="spinner-border text-primary mb-3" role="status"></div>
        <h5 class="mb-2" id="generationOverlayTitle">Submitting exam generation request...</h5>
        <p class="text-muted mb-0" id="generationOverlayMessage">The request will be queued and processed in the background.</p>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="js/exam_generator_editor.js"></script>
<script>
// ── Exam Format Profile panel — upload/status/auto-prefill ─────────────────
let currentFormatSpec = null;

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

function formatProfileParams() {
    return { subject_id: $('#subjectSelect').val(), class_name: $('#classSelect').val() };
}

function renderFormatProfileStatus(data) {
    const box = document.getElementById('formatProfileStatus');
    const useBtn = document.getElementById('useSchoolFormatBtn');
    if (!data || !data.exists) {
        box.innerHTML = '<div class="text-muted small"><i class="fas fa-info-circle me-1"></i>No exam format on file yet for this subject/class. Upload a sample below to teach the AI your school\'s standard.</div>';
        useBtn.disabled = true;
        currentFormatSpec = null;
        return;
    }
    if (data.status === 'ready' && data.format_spec) {
        currentFormatSpec = data.format_spec;
        box.innerHTML = '<div class="small"><span class="badge bg-success mb-2"><i class="fas fa-check-circle me-1"></i>Format learned</span><br>' + escapeHtmlLocal(data.summary_text || '') + '</div>';
        useBtn.disabled = false;
    } else if (data.status === 'failed') {
        currentFormatSpec = null;
        box.innerHTML = '<div class="small text-danger"><i class="fas fa-exclamation-triangle me-1"></i>' + escapeHtmlLocal(data.status_note || 'Analysis failed.') + '</div>';
        useBtn.disabled = true;
    } else {
        currentFormatSpec = null;
        box.innerHTML = '<div class="small text-warning"><i class="fas fa-hourglass-half me-1"></i>' + escapeHtmlLocal(data.status_note || 'Processing...') + '</div>';
        useBtn.disabled = true;
    }
}

function loadFormatProfile() {
    const params = formatProfileParams();
    if (!params.subject_id || !params.class_name) {
        document.getElementById('formatProfileStatus').innerHTML = '<div class="text-muted small">Select a subject and class to see or set this school\'s exam format.</div>';
        document.getElementById('useSchoolFormatBtn').disabled = true;
        currentFormatSpec = null;
        return;
    }
    $.get('ajax/get_format_profile.php', params, renderFormatProfileStatus, 'json')
        .fail(() => { document.getElementById('formatProfileStatus').innerHTML = '<div class="text-danger small">Could not load format profile.</div>'; });
}

document.getElementById('uploadFormatProfileBtn').addEventListener('click', function () {
    const params = formatProfileParams();
    if (!params.subject_id || !params.class_name) { alert('Select a subject and class first.'); return; }
    const fileInput = document.getElementById('formatProfileFile');
    const sampleText = document.getElementById('formatProfileText').value.trim();
    if (!fileInput.files.length && !sampleText) { alert('Choose a file or paste sample text.'); return; }

    const formData = new FormData();
    formData.append('subject_id', params.subject_id);
    formData.append('class_name', params.class_name);
    if (fileInput.files.length) formData.append('file', fileInput.files[0]);
    if (sampleText) formData.append('sample_text', sampleText);

    const btn = this;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Analyzing...';
    document.getElementById('formatProfileStatus').innerHTML = '<div class="text-muted small"><i class="fas fa-spinner fa-spin me-1"></i>Extracting and analyzing your sample. This can take up to a minute...</div>';

    fetch('ajax/upload_format_profile.php', { method: 'POST', body: formData })
        .then(r => r.json())
        .then(data => {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-upload me-1"></i>Analyze &amp; Save';
            if (!data.success) { alert(data.message || 'Upload failed.'); loadFormatProfile(); return; }
            fileInput.value = '';
            document.getElementById('formatProfileText').value = '';
            renderFormatProfileStatus({ exists: true, status: data.status, status_note: data.status_note, format_spec: data.format_spec, summary_text: data.summary_text });
            if (data.warning) { showStatus('warning', data.warning); }
        })
        .catch(() => {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-upload me-1"></i>Analyze &amp; Save';
            alert('Network error uploading the sample.');
        });
});

document.getElementById('clearFormatProfileBtn').addEventListener('click', function () {
    const params = formatProfileParams();
    if (!params.subject_id || !params.class_name) { alert('Select a subject and class first.'); return; }
    if (!confirm('Clear the exam format for this subject/class? Generation will use standard rules until a new sample is uploaded.')) return;
    $.post('ajax/delete_format_profile.php', params, function (data) {
        if (!data.success) { alert(data.message || 'Could not clear format profile.'); return; }
        loadFormatProfile();
    }, 'json').fail(() => alert('Network error clearing the format profile.'));
});

document.getElementById('useSchoolFormatBtn').addEventListener('click', function () {
    if (!currentFormatSpec || !Array.isArray(currentFormatSpec.sections)) return;
    const objective = currentFormatSpec.sections.find(s => s.type === 'objective');
    const subjective = currentFormatSpec.sections.find(s => s.type === 'subjective');

    if (objective) {
        document.getElementById('formatObjective').checked = true;
        if (objective.question_count > 0) document.getElementById('objCount').value = objective.question_count;
        if (objective.marks_per_question > 0) document.getElementById('objMarks').value = objective.marks_per_question;
    }
    if (subjective) {
        document.getElementById('formatSubjective').checked = true;
        if (subjective.question_count > 0) document.getElementById('subjCount').value = subjective.question_count;
        if (subjective.marks_per_question > 0) document.getElementById('subjMarks').value = subjective.marks_per_question;
    }
    document.getElementById('formatComprehension').checked = !!currentFormatSpec.has_comprehension;
    if (currentFormatSpec.duration_minutes > 0) document.getElementById('duration').value = currentFormatSpec.duration_minutes;
    if (currentFormatSpec.total_marks > 0) document.getElementById('totalMarks').value = currentFormatSpec.total_marks;

    showStatus('success', 'Form updated to match this school\'s exam format. Review and adjust before generating.');
});

$('#classSelect, #subjectSelect').on('change', loadFormatProfile);
</script>
</body>
</html>
