<?php
declare(strict_types=1);
session_start();
require_once '../config.php';
requireModule('exams');
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/lib/content_chunker.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);
$settings     = examsGetSettings($conn);
$defaultYear  = (string) ($settings['academic_year'] ?? getAcademicYear());
$classOptions = examsGetClasses($conn);

// Quota info for the header badge
$monthYear   = date('Y-m');
$schoolCode  = defined('SCHOOL_CODE') ? SCHOOL_CODE : 'DEMO';
$jobQuota    = getPlanJobQuota();

// Ensure quota table exists before querying it (ajax endpoints create it on first use,
// but the page may load before any ajax call has run)
$conn->query("CREATE TABLE IF NOT EXISTS ai_generation_quota (
    id          INT AUTO_INCREMENT PRIMARY KEY,
    school_code VARCHAR(50)  NOT NULL,
    month_year  CHAR(7)      NOT NULL,
    jobs_used   INT          NOT NULL DEFAULT 0,
    word_count  INT          NOT NULL DEFAULT 0,
    updated_at  TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uq_school_month (school_code, month_year)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

$qRow = $conn->query(
    "SELECT jobs_used FROM ai_generation_quota
     WHERE school_code = '" . $conn->real_escape_string($schoolCode) . "'
       AND month_year  = '" . $conn->real_escape_string($monthYear) . "'"
) ?: null;
$qData    = $qRow ? $qRow->fetch_assoc() : null;
$jobsUsed = (int) ($qData['jobs_used'] ?? 0);
$quotaClass = $jobsUsed >= $jobQuota ? 'bg-danger' : ($jobsUsed >= $jobQuota - 2 ? 'bg-warning text-dark' : 'bg-secondary');

// 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 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>
        .drop-zone{border:2px dashed #9cb3d1;border-radius:1rem;padding:2rem;text-align:center;background:#f8fbff;cursor:pointer}
        .drop-zone.dragover{border-color:#0d6efd;background:#eef5ff}
        .material-list .badge{font-size:.75rem}
        .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)}
        .status-dot{width:10px;height:10px;border-radius:50%;display:inline-block;background:#ccc;transition:background .3s ease}
        .status-dot.online{background:#28a745;box-shadow:0 0 6px #28a74580}
        .status-dot.offline{background:#dc3545}
        .status-dot.checking{background:#ffc107;animation:pulse 1s infinite}
        @keyframes pulse{0%,100%{opacity:1}50%{opacity:.3}}
    </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 Generator</h4>
                <div class="text-muted small">Upload study materials, extract content, and generate exam questions into the existing bank.</div>
            </div>
            <div>
                <span class="badge <?= $quotaClass ?>" title="AI generation quota this month">
                    <i class="fas fa-bolt me-1"></i><?= $jobsUsed ?>/<?= $jobQuota ?> generations used
                </span>
            </div>
        </header>
        <main class="container-fluid py-4">
            <?= examsRenderTabs('ai') ?>
            <div class="card mb-3 border-0 shadow-sm" id="ai-status-bar">
                <div class="card-body py-2">
                    <div class="d-flex align-items-center justify-content-between flex-wrap gap-2">
                        <div class="d-flex align-items-center gap-3 flex-wrap">
                            <small class="text-muted fw-semibold">AI Engines:</small>
                            <span class="d-flex align-items-center gap-1"><span class="status-dot" id="dot-claude"></span><small id="lbl-claude">Claude</small><small class="text-muted" id="lat-claude"></small></span>
                            <span class="d-flex align-items-center gap-1"><span class="status-dot" id="dot-groq"></span><small id="lbl-groq">Groq</small><small class="text-muted" id="lat-groq"></small></span>
                            <span class="d-flex align-items-center gap-1"><span class="status-dot" id="dot-gemini"></span><small id="lbl-gemini">Gemini</small><small class="text-muted" id="lat-gemini"></small></span>
                        </div>
                        <div class="d-flex align-items-center gap-2">
                            <span class="badge" id="overall-badge">Checking...</span>
                            <button class="btn btn-sm btn-outline-secondary" onclick="checkAIStatus()" id="btn-refresh-status" type="button">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="row g-4">
                <div class="col-lg-7">
                    <div class="card shadow-sm border-0 mb-4">
                        <div class="card-header"><h5 class="mb-0">Step 1 — Upload Study Material</h5></div>
                        <div class="card-body">
                            <div id="dropZone" class="drop-zone" style="position:relative;">
                                <i class="fas fa-cloud-upload-alt fa-2x mb-3 text-primary"></i>
                                <div class="fw-semibold">Drag and drop study material files here</div>
                                <div class="text-muted small mb-3">PDF, Word (.docx), TXT, or images — or click to browse.</div>
                                <input type="file" id="materialFile" accept=".pdf,.docx,.doc,.txt,.jpg,.jpeg,.png,.webp" multiple
                                    style="position:absolute;left:0;top:0;width:100%;height:100%;opacity:0;cursor:pointer;z-index:2;">
                                <button type="button" class="btn btn-outline-primary" id="browseBtn" style="position:relative;z-index:3;">Browse Files</button>
                            </div>
                            <div class="row g-3 mt-3">
                                <div class="col-md-6"><label class="form-label">Subject</label><select id="upload_subject_id" class="form-select"><?php foreach ($subjects as $subject): ?><option value="<?= (int) $subject['id'] ?>"><?= htmlspecialchars((string) $subject['subject_name']) ?></option><?php endforeach; ?></select></div>
                                <div class="col-md-6"><label class="form-label">Class</label><select id="upload_class_name" class="form-select"><?php foreach ($classOptions as $class): ?><option value="<?= htmlspecialchars($class) ?>"><?= htmlspecialchars($class) ?></option><?php endforeach; ?></select></div>
                            </div>
                            <div class="progress mt-3 d-none" id="uploadProgressWrap"><div id="uploadProgress" class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width:0%">0%</div></div>
                            <div class="material-list mt-3" id="materialList"></div>
                        </div>
                    </div>

                    <div class="card shadow-sm border-0">
                        <div class="card-header"><h5 class="mb-0">Step 2 — Configure Exam</h5></div>
                        <div class="card-body">
                            <form id="generateForm" class="row g-3">
                                <div class="col-12">
                                    <label class="form-label d-block mb-1">Generation Source</label>
                                    <div class="btn-group" role="group" aria-label="Generation source">
                                        <input type="radio" class="btn-check" name="genSource" id="srcMaterial" value="material" checked>
                                        <label class="btn btn-outline-primary btn-sm" for="srcMaterial"><i class="fas fa-file-alt me-1"></i>From uploaded material</label>
                                        <input type="radio" class="btn-check" name="genSource" id="srcTopics" value="topics">
                                        <label class="btn btn-outline-primary btn-sm" for="srcTopics"><i class="fas fa-list-ul me-1"></i>From topics (no upload)</label>
                                    </div>
                                </div>
                                <div class="col-12" id="topicsWrap" style="display:none;">
                                    <label class="form-label">Topics to cover</label>
                                    <textarea class="form-control" name="topics" id="topicsInput" rows="3" placeholder="e.g. Fractions, Decimals, Percentages, Ratio and Proportion"></textarea>
                                    <div class="form-text">Comma- or line-separated. Optionally weight a topic with a colon, e.g. <code>Fractions:40, Decimals:30</code>, to bias more questions toward it. Generated from the standard curriculum — no upload needed.</div>
                                </div>
                                <div class="col-md-6"><label class="form-label">Subject</label><select name="subject_id" class="form-select"><?php foreach ($subjects as $subject): ?><option value="<?= (int) $subject['id'] ?>"><?= htmlspecialchars((string) $subject['subject_name']) ?></option><?php endforeach; ?></select></div>
                                <div class="col-md-6"><label class="form-label">Class Level</label><select name="class_name" class="form-select"><?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 name="term" class="form-select"><?php foreach (examsTerms() as $term): ?><option value="<?= htmlspecialchars($term) ?>"><?= htmlspecialchars($term) ?></option><?php endforeach; ?></select></div>
                                <div class="col-md-4"><label class="form-label">Academic Year</label><input type="text" name="academic_year" class="form-control" value="<?= htmlspecialchars($defaultYear) ?>"></div>
                                <div class="col-md-4"><label class="form-label">Difficulty</label><select name="difficulty" class="form-select"><option value="easy">Easy</option><option value="medium" selected>Medium</option><option value="hard">Hard</option></select></div>
                                <div class="col-12"><h6 class="mb-0">Question Breakdown</h6></div>
                                <div class="col-md-3"><label class="form-label">MCQ Count</label><input type="number" min="0" name="mcq_count" class="form-control q-count" value="20"></div>
                                <div class="col-md-3"><label class="form-label">Fill Blank Count</label><input type="number" min="0" name="fill_blank_count" class="form-control q-count" value="5"></div>
                                <div class="col-md-3"><label class="form-label">True/False Count</label><input type="number" min="0" name="true_false_count" class="form-control q-count" value="0"></div>
                                <div class="col-md-3"><label class="form-label">Matching Count</label><input type="number" min="0" name="matching_count" class="form-control q-count" value="0"></div>
                                <div class="col-md-3"><label class="form-label">Comprehension Count</label><input type="number" min="0" name="comprehension_count" class="form-control q-count" value="0"></div>
                                <div class="col-md-3"><label class="form-label">Theory Count</label><input type="number" min="0" name="theory_count" class="form-control q-count" value="5"></div>
                                <div class="col-md-3"><label class="form-label">Diagram Questions</label><input type="number" min="0" name="diagram_count" class="form-control" value="2"><div class="form-text">AI will include diagrams where the subject warrants it.</div></div>
                                <div class="col-12"><div class="alert alert-light border mb-0">Total Questions: <strong id="totalQuestions">30</strong></div></div>
                                <div class="col-12"><button type="submit" id="generateBtn" class="btn btn-primary" disabled><i class="fas fa-magic me-1"></i>Generate Questions</button></div>
                            </form>
                        </div>
                    </div>
                </div>

                <div class="col-lg-5">
                    <div class="card shadow-sm border-0 mb-4">
                        <div class="card-header"><h5 class="mb-0">Generation History</h5></div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-sm align-middle">
                                    <thead><tr><th>Date</th><th>Subject</th><th>Class</th><th>Questions</th><th>Engine</th><th>Status</th><th>Actions</th></tr></thead>
                                    <tbody id="jobHistoryBody"></tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    <div class="card shadow-sm border-0" id="quickExportCard" style="display:none;">
                        <div class="card-header"><h5 class="mb-0">Quick Export</h5></div>
                        <div class="card-body d-grid gap-2">
                            <div id="engine-info" class="mb-3" style="display:none;">
                                <small class="text-muted">Generated by: </small>
                                <span id="engine-badge"></span>
                            </div>
                            <a class="btn btn-outline-primary" id="downloadCsvBtn" target="_blank">Download CSV</a>
                            <a class="btn btn-outline-secondary" id="downloadExamPdfBtn" target="_blank">Download Exam PDF</a>
                            <a class="btn btn-outline-secondary" id="downloadKeyPdfBtn" target="_blank">Download Answer Key PDF</a>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<div class="progress-overlay" id="progressOverlay">
    <div class="progress-card">
        <h5 class="mb-3"><i class="fas fa-robot me-2 text-primary"></i>Generating Questions</h5>
        <div class="progress mb-3" style="height:8px;">
            <div id="generationProgress" class="progress-bar progress-bar-striped progress-bar-animated bg-primary" style="width:0%;transition:width .4s ease;"></div>
        </div>
        <div class="mb-3" id="stepList" style="font-size:.875rem;">
            <div class="d-flex align-items-center gap-2 mb-2" id="step-clean">
                <span class="step-icon text-muted"><i class="fas fa-circle fa-xs"></i></span>
                <span class="text-muted">Cleaning extracted content…</span>
            </div>
            <div class="d-flex align-items-center gap-2 mb-2" id="step-chunk">
                <span class="step-icon text-muted"><i class="fas fa-circle fa-xs"></i></span>
                <span class="text-muted">Splitting into topic chunks…</span>
            </div>
            <div class="d-flex align-items-center gap-2 mb-2" id="step-generate">
                <span class="step-icon text-muted"><i class="fas fa-circle fa-xs"></i></span>
                <span class="text-muted" id="step-generate-label">Generating questions (chunk 0/0)…</span>
            </div>
            <div class="d-flex align-items-center gap-2 mb-2" id="step-refine">
                <span class="step-icon text-muted"><i class="fas fa-circle fa-xs"></i></span>
                <span class="text-muted">Moderating with senior AI examiner…</span>
            </div>
            <div class="d-flex align-items-center gap-2" id="step-save">
                <span class="step-icon text-muted"><i class="fas fa-circle fa-xs"></i></span>
                <span class="text-muted">Saving to question bank…</span>
            </div>
        </div>
        <div class="text-muted small" id="generationStatus">Preparing generation pipeline…</div>
    </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>
let uploadedMaterials = [];
let lastJobId = 0;
let loadMaterialsSeq = 0; // prevents stale fetch from overwriting newer result

// ── Step-display helpers ──────────────────────────────────────────────────
function stepActive(id, label) {
  const el = document.getElementById(id);
  if (!el) return;
  el.querySelector('.step-icon').innerHTML = '<i class="fas fa-spinner fa-spin text-primary fa-xs"></i>';
  const span = id === 'step-generate' ? document.getElementById('step-generate-label') : el.querySelector('span:last-child');
  if (span && label) span.textContent = label;
  el.querySelector('span:last-child').classList.replace('text-muted','text-dark');
}
function stepDone(id) {
  const el = document.getElementById(id);
  if (!el) return;
  el.querySelector('.step-icon').innerHTML = '<i class="fas fa-check-circle text-success fa-xs"></i>';
  el.querySelector('span:last-child').classList.replace('text-dark','text-success');
  el.querySelector('span:last-child').classList.replace('text-muted','text-success');
}
function stepReset() {
  ['step-clean','step-chunk','step-generate','step-refine','step-save'].forEach(id => {
    const el = document.getElementById(id);
    if (!el) return;
    el.querySelector('.step-icon').innerHTML = '<i class="fas fa-circle fa-xs"></i>';
    ['text-success','text-dark'].forEach(c => el.querySelectorAll('span').forEach(s => { s.classList.remove(c); s.classList.add('text-muted'); }));
  });
  const lbl = document.getElementById('step-generate-label');
  if (lbl) lbl.textContent = 'Generating questions (chunk 0/0)…';
}
function esc(v){return String(v ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[c]));}
function updateTotal(){let total=0;document.querySelectorAll('.q-count').forEach(el=>total+=parseInt(el.value||'0',10));document.getElementById('totalQuestions').textContent=total;}
function renderMaterials(){
  const wrap=document.getElementById('materialList');
  if(!uploadedMaterials.length){
    wrap.innerHTML='<div class="text-muted small">No study materials uploaded yet.</div>';
    document.getElementById('generateBtn').disabled = isTopicMode() ? false : true;
    return;
  }
  const hasDone=uploadedMaterials.some(m=>m.extraction_status==='done');
  wrap.innerHTML=uploadedMaterials.map(m=>{
    const wc   = parseInt(m.cleaned_word_count || m.word_count || 0, 10);
    const chunks = parseInt(m.chunk_count || 0, 10);
    const pages  = parseInt(m.page_count || 0, 10);
    let statusHtml = '';
    if (m.extraction_status === 'done') {
      statusHtml = `<span class="text-success"><i class="fas fa-check-circle me-1"></i>${esc(wc)} words`
                 + (chunks > 0 ? ` · ${esc(chunks)} topic chunk${chunks>1?'s':''}` : '')
                 + (pages > 0  ? ` · ${esc(pages)} pages` : '')
                 + `</span>`;
    } else if (m.extraction_status === 'failed') {
      statusHtml = '<span class="text-danger"><i class="fas fa-exclamation-circle me-1"></i>Extraction failed — check AI API key in Settings</span>';
    } else {
      statusHtml = '<span class="text-warning"><i class="fas fa-spinner fa-spin me-1"></i>Processing...</span>';
    }
    return `<div class="border rounded p-3 mb-2"><div class="d-flex justify-content-between align-items-start gap-2"><div><div class="fw-semibold">${esc(m.original_filename||m.filename||'')}</div><div class="small text-muted"><span class="badge bg-secondary me-1">${esc(m.subject_name||'')}</span><span class="badge bg-light text-dark">${esc(m.class_name||'')}</span></div><div class="small mt-2">${statusHtml}</div></div><button class="btn btn-sm btn-outline-danger" onclick="deleteMaterial(${m.id||m.material_id})"><i class="fas fa-trash"></i></button></div></div>`;
  }).join('');
  void wrap.offsetHeight;
  // Enable Generate only when at least one material has usable extracted content
  document.getElementById('generateBtn').disabled = isTopicMode() ? false : !hasDone;
}
async function loadMaterials(){
  const seq = ++loadMaterialsSeq;
  try {
    const res=await fetch('ajax/get_materials.php',{method:'POST'});
    const data=await res.json();
    if(seq !== loadMaterialsSeq) return; // discard stale response
    uploadedMaterials=Array.isArray(data)?data:[];
    renderMaterials();
  } catch(err) {
    if(seq !== loadMaterialsSeq) return;
    document.getElementById('materialList').innerHTML='<div class="text-danger small">Failed to load materials: '+esc(err.message||'Unknown error')+'</div>';
  }
}
const engineBadges={claude:'<span class="badge bg-primary">Claude</span>',groq:'<span class="badge bg-warning text-dark">Groq</span>',gemini:'<span class="badge bg-success">Gemini</span>'};
async function loadJobs(){try{const res=await fetch('ajax/get_generation_jobs.php',{method:'POST'});const jobs=await res.json();document.getElementById('jobHistoryBody').innerHTML=(Array.isArray(jobs)?jobs:[]).map(job=>`<tr><td>${esc(job.created_at)}</td><td>${esc(job.subject_name || '')}</td><td>${esc(job.class_name)}</td><td>${esc((parseInt(job.mcq_count||0,10)+parseInt(job.theory_count||0,10)+parseInt(job.fill_blank_count||0,10)).toString())}</td><td>${engineBadges[job.engine_used]||'<span class="text-muted">—</span>'}</td><td><span class="badge ${job.status==='done'?'bg-success':job.status==='failed'?'bg-danger':'bg-warning text-dark'}">${esc(job.status)}</span></td><td><a href="index.php?job_id=${job.id}" class="btn btn-sm btn-outline-primary">View</a></td></tr>`).join('') || '<tr><td colspan="7" class="text-muted">No generation jobs yet.</td></tr>';}catch(err){document.getElementById('jobHistoryBody').innerHTML='<tr><td colspan="7" class="text-danger small">Failed to load history.</td></tr>';}}
async function deleteMaterial(id){if(!confirm('Delete this study material?'))return;const res=await fetch('ajax/delete_material.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams({id})});const data=await res.json();if(data.success){await loadMaterials();}}

function setDropZoneUploading(files) {
  const icon = dropZone.querySelector('.fa-cloud-upload-alt');
  const label = dropZone.querySelector('.fw-semibold');
  const sub = dropZone.querySelector('.text-muted.small');
  if (icon) { icon.classList.remove('fa-cloud-upload-alt'); icon.classList.add('fa-spinner','fa-spin'); }
  if (label) label.textContent = files.length === 1 ? `Uploading: ${files[0].name}` : `Uploading ${files.length} file(s)…`;
  if (sub) sub.textContent = 'Please wait…';
}
function resetDropZone() {
  const icon = dropZone.querySelector('.fa-spinner');
  const label = dropZone.querySelector('.fw-semibold');
  const sub = dropZone.querySelector('.text-muted.small');
  if (icon) { icon.classList.remove('fa-spinner','fa-spin'); icon.classList.add('fa-cloud-upload-alt'); }
  if (label) label.textContent = 'Drag and drop study material files here';
  if (sub) sub.textContent = 'PDF, Word (.docx), TXT, or images — or click to browse.';
}

async function uploadFiles(files){
  if(!files||!files.length)return;
  const subjectId=document.getElementById('upload_subject_id').value;
  const className=document.getElementById('upload_class_name').value;
  const progressWrap=document.getElementById('uploadProgressWrap');
  const progressBar=document.getElementById('uploadProgress');
  setDropZoneUploading(Array.from(files));
  progressWrap.classList.remove('d-none');
  for(const file of files){
    const formData=new FormData();
    formData.append('file',file);
    formData.append('subject_id',subjectId);
    formData.append('class_name',className);
    progressBar.style.width='20%';progressBar.textContent='20%';
    try{
      const res=await fetch('ajax/upload_material.php',{method:'POST',body:formData});
      progressBar.style.width='100%';progressBar.textContent='100%';
      const text=await res.text();
      let data;
      try{data=JSON.parse(text);}catch(e){alert('Server error uploading '+file.name+': '+text.substring(0,200));continue;}
      if(!data.success){alert(data.message||data.error||'Upload failed for '+file.name);continue;}
      // Show extraction warning as a non-blocking notice in the material list area
      if(data.warning){
        const note=document.getElementById('materialList');
        const div=document.createElement('div');
        div.className='alert alert-warning alert-dismissible py-2 mt-2';
        div.innerHTML='<i class="fas fa-exclamation-triangle me-1"></i>'+esc(data.warning)+'<button type="button" class="btn-close btn-sm" data-bs-dismiss="alert"></button>';
        note.prepend(div);
      }
    }catch(err){alert('Network error: '+err.message);}
  }
  setTimeout(()=>{progressWrap.classList.add('d-none');progressBar.style.width='0%';progressBar.textContent='0%';},600);
  document.getElementById('materialFile').value='';
  resetDropZone();
  await loadMaterials();
}
const dropZone=document.getElementById('dropZone');
document.getElementById('materialFile').addEventListener('change',e=>{if(e.target.files.length)uploadFiles(e.target.files);});
// browseBtn click: prevent the transparent file-input overlay from double-firing, then trigger it
document.getElementById('browseBtn').addEventListener('click',e=>{e.preventDefault();e.stopPropagation();document.getElementById('materialFile').click();});
dropZone.addEventListener('dragover',e=>{e.preventDefault();dropZone.classList.add('dragover');});
dropZone.addEventListener('dragleave',e=>{if(!dropZone.contains(e.relatedTarget))dropZone.classList.remove('dragover');});
dropZone.addEventListener('drop',e=>{e.preventDefault();dropZone.classList.remove('dragover');uploadFiles(e.dataTransfer.files);});
document.querySelectorAll('.q-count').forEach(el=>el.addEventListener('input',updateTotal));
document.getElementById('generateForm').addEventListener('submit',async function(e){
  e.preventDefault();
  const topicMode = isTopicMode();
  let readyMaterials = [];
  if (topicMode) {
    if(!document.getElementById('topicsInput').value.trim()){alert('Enter at least one topic to cover.');return;}
  } else {
    if(!uploadedMaterials.length){alert('Upload at least one material first');return;}
    readyMaterials=uploadedMaterials.filter(m=>m.extraction_status==='done');
    if(!readyMaterials.length){alert('No materials have finished processing yet. Please wait for extraction to complete.');return;}
  }

  const overlay  = document.getElementById('progressOverlay');
  const progress = document.getElementById('generationProgress');
  const status   = document.getElementById('generationStatus');
  overlay.style.display='flex';
  stepReset();

  // Step 1 — clean
  stepActive('step-clean','Cleaning extracted content…');
  progress.style.width='10%';

  // Simulate clean + chunk steps during the actual server call
  let stepTimer = setTimeout(()=>{
    stepDone('step-clean');
    stepActive('step-chunk','Splitting into topic chunks…');
    progress.style.width='20%';
    stepTimer = setTimeout(()=>{
      stepDone('step-chunk');
      // We'll find out how many chunks there are from the response,
      // but start the generate step now
      stepActive('step-generate','Generating questions…');
      progress.style.width='35%';
      // Slowly tick progress during AI calls
      stepTimer = setInterval(()=>{
        const cur = parseFloat(progress.style.width)||35;
        if(cur < 80){ progress.style.width=(cur+1)+'%'; }
      },1500);
    },800);
  },600);

  try{
    const formData=new FormData(this);
    let endpoint;
    if (topicMode) {
      endpoint = 'ajax/generate_from_topics.php';
    } else {
      formData.append('material_ids',JSON.stringify(readyMaterials.map(m=>m.id||m.material_id)));
      endpoint = 'ajax/generate_questions.php';
    }
    status.textContent='Sending to AI exam officer…';
    const res  = await fetch(endpoint,{method:'POST',body:new URLSearchParams(formData)});
    const data = await res.json();

    clearInterval(stepTimer);
    clearTimeout(stepTimer);

    if(!data.success){
      overlay.style.display='none';
      alert(data.message||'Generation failed');
      return;
    }

    // Update generate label with actual chunk count
    const chunkCount = data.chunk_count || 1;
    document.getElementById('step-generate-label').textContent =
      `Generating questions (${chunkCount} chunk${chunkCount>1?'s':''} processed)…`;
    stepDone('step-generate');

    // Refine step
    if(data.refined){
      stepActive('step-refine','Moderating with senior AI examiner…');
      progress.style.width='90%';
      await new Promise(r=>setTimeout(r,400));
      stepDone('step-refine');
    } else {
      // dim step — not available on this plan
      const el=document.getElementById('step-refine');
      if(el) el.querySelector('span:last-child').textContent='Moderation pass (Growth/Premium plans)';
    }

    // Save step
    stepActive('step-save','Saving to question bank…');
    progress.style.width='96%';
    await new Promise(r=>setTimeout(r,300));
    stepDone('step-save');
    progress.style.width='100%';

    await new Promise(r=>setTimeout(r,400));
    overlay.style.display='none';

    lastJobId = data.job_id;
    document.getElementById('quickExportCard').style.display='block';

    const engineLabels={
      claude:'<span class="badge bg-primary"><i class="fas fa-robot me-1"></i>Claude AI</span>',
      groq  :'<span class="badge bg-warning text-dark"><i class="fas fa-bolt me-1"></i>Groq AI</span>',
      gemini:'<span class="badge bg-success"><i class="fas fa-gem me-1"></i>Gemini AI</span>',
    };
    if(data.engine){
      document.getElementById('engine-badge').innerHTML=(engineLabels[data.engine]||esc(data.engine))
        + (data.refined && data.refiner_engine
            ? ' <span class="text-muted small ms-1">+ '+esc(data.refiner_engine)+' moderator</span>'
            : '');
      document.getElementById('engine-info').style.display='block';
    }

    document.getElementById('downloadCsvBtn').href    = 'ajax/export_csv.php?job_id='+lastJobId;
    document.getElementById('downloadExamPdfBtn').href= 'ajax/export_pdf.php?job_id='+lastJobId+'&type=exam';
    document.getElementById('downloadKeyPdfBtn').href = 'ajax/export_pdf.php?job_id='+lastJobId+'&type=key';

    // Quota badge update
    if(data.quota_used !== undefined && data.quota_limit !== undefined){
      const badge = document.querySelector('header .badge[title="AI generation quota this month"]');
      if(badge){
        badge.textContent = `⚡ ${data.quota_used}/${data.quota_limit} generations used`;
        badge.className   = 'badge ' + (data.quota_used >= data.quota_limit ? 'bg-danger' : data.quota_used >= data.quota_limit-2 ? 'bg-warning text-dark' : 'bg-secondary');
      }
    }

    let msg = data.summary || 'Generation completed';
    if(data.partial_errors && data.partial_errors.length){
      msg += '\n\nSome chunks had errors:\n' + data.partial_errors.join('\n');
    }
    alert(msg);
    loadJobs();

  } catch(err){
    clearInterval(stepTimer);
    clearTimeout(stepTimer);
    overlay.style.display='none';
    alert('Generation failed: '+(err.message||'Network error'));
  }
});
function checkAIStatus(){const engines=['claude','groq','gemini'];engines.forEach(e=>{document.getElementById('dot-'+e).className='status-dot checking';document.getElementById('lat-'+e).textContent='';});document.getElementById('overall-badge').textContent='Checking...';document.getElementById('overall-badge').className='badge bg-secondary';document.getElementById('btn-refresh-status').disabled=true;fetch('ajax/check_ai_status.php').then(r=>r.json()).then(data=>{engines.forEach(e=>{const dot=document.getElementById('dot-'+e);const lat=document.getElementById('lat-'+e);const info=data[e];if(info.status==='online'){dot.className='status-dot online';lat.textContent=info.latency;}else{dot.className='status-dot offline';lat.textContent='✕';lat.title=info.error||'';}});const badge=document.getElementById('overall-badge');if(data.overall==='all_online'){badge.textContent='✓ All Engines Online';badge.className='badge bg-success';}else if(data.overall==='degraded'){badge.textContent='⚠ Degraded — Fallback Active';badge.className='badge bg-warning text-dark';}else{badge.textContent='✕ All Engines Offline';badge.className='badge bg-danger';}}).catch(()=>{document.getElementById('overall-badge').textContent='Status Check Failed';document.getElementById('overall-badge').className='badge bg-secondary';}).finally(()=>{document.getElementById('btn-refresh-status').disabled=false;});}
function isTopicMode(){ return ((document.querySelector('input[name="genSource"]:checked')||{}).value) === 'topics'; }
function applyGenSource(){
  const topic = isTopicMode();
  document.getElementById('topicsWrap').style.display = topic ? 'block' : 'none';
  document.getElementById('generateBtn').disabled = topic ? false : !uploadedMaterials.some(m=>m.extraction_status==='done');
}
document.querySelectorAll('input[name="genSource"]').forEach(r=>r.addEventListener('change',applyGenSource));
updateTotal();loadMaterials();loadJobs();checkAIStatus();applyGenSource();
</script>
</body>
</html>
