<?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);
$classes  = examsGetClasses($conn);
$settings = examsGetSettings($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)));
}
$academicYear = $settings['academic_year'] ?? getAcademicYear();
$jobId = (int) ($_GET['job_id'] ?? 0);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exams - Question Bank</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="https://cdn.datatables.net/1.13.8/css/dataTables.bootstrap5.min.css">
    <link rel="stylesheet" href="../css/style.css">
</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 - Question Bank</h4><div class="text-muted small">Create, import, filter, and maintain exam questions.</div></div>
        </header>
        <main class="container-fluid py-4">
            <?= examsRenderTabs('questions') ?>
            <div class="card shadow-sm border-0 mb-4">
                <div class="card-body">
                    <div class="row g-2 align-items-end">
                        <div class="col-md-2"><label class="form-label">Subject</label><select id="filter_subject" class="form-select"><option value="">All</option><?php foreach ($subjects as $s): ?><option value="<?= (int) $s['id'] ?>"><?= htmlspecialchars((string) $s['subject_name']) ?></option><?php endforeach; ?></select></div>
                        <div class="col-md-2"><label class="form-label">Class</label><select id="filter_class" class="form-select"><option value="">All</option><?php foreach ($classes as $class): ?><option value="<?= htmlspecialchars($class) ?>"><?= htmlspecialchars($class) ?></option><?php endforeach; ?></select></div>
                        <div class="col-md-2"><label class="form-label">Difficulty</label><select id="filter_difficulty" class="form-select"><option value="">All</option><option value="easy">Easy</option><option value="medium">Medium</option><option value="hard">Hard</option></select></div>
                        <div class="col-md-2"><label class="form-label">Type</label><select id="filter_type" class="form-select"><option value="">All</option><option value="mcq">MCQ</option><option value="theory">Theory</option><option value="fill_blank">Fill Blank</option></select></div>
                        <div class="col-md-2"><label class="form-label">Source</label><select id="filter_source" class="form-select"><option value="">All</option><option value="ai">AI Generated</option><option value="manual">Manual</option><option value="imported">Imported</option></select></div>
                        <div class="col-md-2"><label class="form-label">Search</label><input type="text" id="filter_search" class="form-control" placeholder="Question text"></div>
                    </div>
                    <div class="d-flex justify-content-between align-items-center gap-2 mt-3 flex-wrap">
                        <button class="btn btn-primary" id="filterBtn"><i class="fas fa-filter me-1"></i>Filter</button>
                        <div class="d-flex gap-2 flex-wrap">
                            <button class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#importModal"><i class="fas fa-file-import me-1"></i>Import from CSV</button>
                            <a href="ai_generator.php" class="btn btn-outline-primary"><i class="fas fa-magic me-1"></i>AI Generator</a>
                            <button class="btn btn-primary" id="addQuestionBtn" data-bs-toggle="modal" data-bs-target="#questionModal"><i class="fas fa-plus me-1"></i>Add Question</button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card shadow-sm border-0">
                <div class="card-body">
                    <div class="table-responsive">
                        <table id="questionTable" class="table table-striped align-middle">
                            <thead><tr><th>#</th><th>Subject</th><th>Class</th><th>Type</th><th>Difficulty</th><th>Source</th><th>Question</th><th>Marks</th><th>Actions</th></tr></thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<div class="modal fade" id="questionModal" tabindex="-1"><div class="modal-dialog modal-lg"><div class="modal-content"><form id="questionForm">
    <div class="modal-header"><h5 class="modal-title">Question Details</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <div class="modal-body">
        <div class="alert alert-info py-2"><i class="fas fa-lightbulb me-2"></i>Need to generate questions from your textbook? <a href="ai_generator.php">Try the AI Generator</a>.</div>
        <input type="hidden" name="id" id="question_id" value="0">
        <div class="row g-3">
            <div class="col-md-6"><label class="form-label">Subject</label><select name="subject_id" id="subject_id" class="form-select" required><option value="">Select</option><?php foreach ($subjects as $s): ?><option value="<?= (int) $s['id'] ?>"><?= htmlspecialchars((string) $s['subject_name']) ?></option><?php endforeach; ?></select></div>
            <div class="col-md-6"><label class="form-label">Class</label><select name="class_name" id="class_name" class="form-select" required><option value="">Select</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 name="term" id="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" id="academic_year" class="form-control" value="<?= htmlspecialchars((string) $academicYear) ?>"></div>
            <div class="col-md-4"><label class="form-label">Question Type</label><select name="question_type" id="question_type" class="form-select"><option value="mcq">MCQ</option><option value="theory">Theory</option><option value="fill_blank">Fill Blank</option></select></div>
            <div class="col-12"><label class="form-label">Question Text</label><textarea name="question" id="question" rows="4" class="form-control" required></textarea></div>
            <div id="mcqFields" class="row g-3">
                <div class="col-md-6"><label class="form-label">Option A</label><input type="text" name="option_a" id="option_a" class="form-control"></div>
                <div class="col-md-6"><label class="form-label">Option B</label><input type="text" name="option_b" id="option_b" class="form-control"></div>
                <div class="col-md-6"><label class="form-label">Option C</label><input type="text" name="option_c" id="option_c" class="form-control"></div>
                <div class="col-md-6"><label class="form-label">Option D</label><input type="text" name="option_d" id="option_d" class="form-control"></div>
                <div class="col-12"><label class="form-label d-block">Correct Answer</label><?php foreach (['A','B','C','D'] as $ans): ?><div class="form-check form-check-inline"><input class="form-check-input" type="radio" name="correct_answer" value="<?= $ans ?>"><label class="form-check-label"><?= $ans ?></label></div><?php endforeach; ?></div>
            </div>
            <div class="col-md-6"><label class="form-label">Marks</label><input type="number" name="marks" id="marks" class="form-control" value="1" min="1"></div>
            <div class="col-md-6"><label class="form-label">Difficulty</label><select name="difficulty" id="difficulty" class="form-select"><option value="easy">Easy</option><option value="medium" selected>Medium</option><option value="hard">Hard</option></select></div>
        </div>
    </div>
    <div class="modal-footer"><button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-primary">Save Question</button></div>
</form></div></div></div>

<div class="modal fade" id="importModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content"><form id="importForm" enctype="multipart/form-data">
    <div class="modal-header"><h5 class="modal-title">Import Questions from CSV</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <div class="modal-body">
        <div class="d-flex justify-content-between align-items-center mb-3"><a href="question_import_template.csv" class="btn btn-sm btn-outline-primary" download>Download CSV Template</a></div>
        <input type="file" name="csv_file" id="csv_file" accept=".csv" class="form-control" required>
        <div class="mt-3"><h6>Preview</h6><pre id="csvPreview" class="bg-light p-3 small mb-0">No file selected.</pre></div>
        <div class="mt-3 small text-muted" id="importResult"></div>
    </div>
    <div class="modal-footer"><button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-primary">Import CSV</button></div>
</form></div></div></div>

<div class="modal fade" id="diagramModal" tabindex="-1"><div class="modal-dialog modal-lg"><div class="modal-content"><div class="modal-header"><h5 class="modal-title">Question Diagram</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body" id="diagramModalBody"></div></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 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>
let table;
let questionModal;
let diagramModal;
function esc(v){return String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[c]));}
function showMcqFields(){document.getElementById('mcqFields').style.display=document.getElementById('question_type').value==='mcq'?'flex':'none';}
function sourceBadge(source){if(source==='AI'){return '<span class="badge bg-primary">AI</span>';}if(source==='Imported'){return '<span class="badge bg-success">Imported</span>';}return '<span class="badge bg-secondary">Manual</span>';}
function resetQuestionForm(){document.getElementById('questionForm').reset();document.getElementById('question_id').value='0';document.getElementById('academic_year').value='<?= htmlspecialchars((string) $academicYear) ?>';showMcqFields();}
function fillQuestion(q){resetQuestionForm();for(const k in q){const el=document.getElementById(k);if(el)el.value=q[k]??'';}if(q.correct_answer){const radio=document.querySelector(`input[name="correct_answer"][value="${q.correct_answer}"]`);if(radio)radio.checked=true;}showMcqFields();}
async function loadQuestions(){
  const fd=new URLSearchParams({subject_id:$('#filter_subject').val(),class_name:$('#filter_class').val(),difficulty:$('#filter_difficulty').val(),question_type:$('#filter_type').val(),search:$('#filter_search').val(),source:$('#filter_source').val(),job_id:'<?= $jobId ?>'});
  const res=await fetch('ajax/get_questions.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:fd});
  const data=await res.json();
  table.clear();
  data.forEach((q,i)=>table.row.add([
    i+1, esc(q.subject_name||''), esc(q.class_name||''), esc(q.question_type||''), esc(q.difficulty||''), sourceBadge(q.source),
    esc((q.question||'').substring(0,80)), esc(q.marks||1),
    `<button class="btn btn-sm btn-outline-primary me-1" data-question='${encodeURIComponent(JSON.stringify(q))}'><i class="fas fa-pen"></i></button><button class="btn btn-sm btn-outline-success me-1" title="Regenerate with AI" onclick="regenerateBankQuestion(${q.id})"><i class="fas fa-wand-magic-sparkles"></i></button><button class="btn btn-sm btn-outline-danger me-1" onclick="deleteQuestion(${q.id})"><i class="fas fa-trash"></i></button>${parseInt(q.diagram_required||0,10)===1?`<button class="btn btn-sm btn-outline-info" onclick="viewDiagram(${q.id})"><i class="fas fa-draw-polygon"></i></button>`:''}`
  ]));
  table.draw();
  $('#questionTable button[data-question]').each(function(){this.onclick=()=>editQuestion(JSON.parse(decodeURIComponent(this.dataset.question)));});
}
function editQuestion(q){fillQuestion(q);questionModal.show();}
async function deleteQuestion(id){if(!confirm('Delete this question?'))return;const res=await fetch('ajax/delete_question.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams({id})});const data=await res.json();alert(data.message||'Done');if(data.success)loadQuestions();}
async function regenerateBankQuestion(id){
  if(!confirm('Regenerate this question with AI? The current version will be replaced.'))return;
  const btnHtml='<i class="fas fa-spinner fa-spin"></i>';
  const res=await fetch('ajax/regenerate_bank_question.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams({id})});
  let data; try{data=await res.json();}catch(e){alert('Server error during regeneration.');return;}
  alert(data.message||(data.success?'Regenerated':'Failed'));
  if(data.success)loadQuestions();
}
async function viewDiagram(id){const res=await fetch('ajax/get_diagram.php?id='+id);const data=await res.json();if(!data.success){alert(data.message||'Diagram not found');return;}document.getElementById('diagramModalBody').innerHTML=data.html;diagramModal.show();}
document.addEventListener('DOMContentLoaded',()=>{
  questionModal=new bootstrap.Modal(document.getElementById('questionModal'));
  diagramModal=new bootstrap.Modal(document.getElementById('diagramModal'));
  table=new DataTable('#questionTable');
  document.getElementById('question_type').addEventListener('change',showMcqFields);
  document.getElementById('filterBtn').addEventListener('click',loadQuestions);
  document.getElementById('addQuestionBtn').addEventListener('click',resetQuestionForm);
  document.getElementById('questionForm').addEventListener('submit',async(e)=>{e.preventDefault();const res=await fetch('ajax/save_question.php',{method:'POST',body:new URLSearchParams(new FormData(e.target))});const data=await res.json();alert(data.message||'Saved');if(data.success){questionModal.hide();loadQuestions();}});
  document.getElementById('csv_file').addEventListener('change',(e)=>{const file=e.target.files[0];if(!file)return;const r=new FileReader();r.onload=()=>{document.getElementById('csvPreview').textContent=r.result.split(/\r?\n/).slice(0,5).join('\n');};r.readAsText(file);});
  document.getElementById('importForm').addEventListener('submit',async(e)=>{e.preventDefault();const formData=new FormData(e.target);const res=await fetch('ajax/import_questions.php',{method:'POST',body:formData});const data=await res.json();document.getElementById('importResult').textContent=`Imported: ${data.imported||0}, Failed: ${data.failed||0}${data.errors&&data.errors.length? ' | ' + data.errors.join('; '):''}`;if(data.success)loadQuestions();});
  loadQuestions();showMcqFields();
});
</script>
</body>
</html>
