<?php
require_once '../includes/init.php';

$user = new User($pdo);
if (!$user->isLoggedIn() || !$user->isTeacher()) {
    header("Location: ../index.php");
    exit;
}

$message = '';
$error = '';

// Download sample CSV
if (isset($_GET['download_sample']) && $_GET['download_sample'] === 'questions') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="questions_sample.csv"');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['Question', 'A', 'B', 'C', 'D', 'E', 'Correct(A-E)', 'SubjectCode', 'Session', 'Term', 'Class']);
    fputcsv($out, ['What is 2+2?', '1', '2', '3', '4', '5', 'D', 'MTH', '2024/2025', '1st Term', 'JSS1']);
    fclose($out);
    exit;
}

// Handle Image Upload Helper
function uploadImage($file) {
    if (isset($file) && $file['error'] == 0) {
        $target_dir = "../assets/uploads/questions/";
        $filename = time() . "_" . basename($file["name"]);
        $target_file = $target_dir . $filename;
        $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
        
        // Check valid image
        $check = getimagesize($file["tmp_name"]);
        if ($check !== false) {
            if (move_uploaded_file($file["tmp_name"], $target_file)) {
                return "assets/uploads/questions/" . $filename;
            }
        }
    }
    return null;
}

// Add Passage
if (isset($_POST['add_passage'])) {
    $p_title = trim($_POST['p_title']);
    $p_content = trim($_POST['p_content']);
    $p_subject_id = $_POST['p_subject_id'] ?? null;
    $p_class_id = $_POST['p_class_id'] ?? null;
    $p_session = $_POST['p_session'] ?? null;
    $p_term = $_POST['p_term'] ?? null;
    if (!empty($p_content)) {
        $stmt = $pdo->prepare("INSERT INTO passages (title, content, subject_id, class_id, session, term) VALUES (?, ?, ?, ?, ?, ?)");
        if ($stmt->execute([$p_title, $p_content, $p_subject_id, $p_class_id, $p_session, $p_term])) {
            $message = "Passage saved.";
        } else {
            $error = "Failed to save passage.";
        }
    } else {
        $error = "Passage content is required.";
    }
}

// Update Question
if (isset($_POST['update_question'])) {
    $question_id = (int)($_POST['question_id'] ?? 0);
    $subject_id = $_POST['subject_id'] ?? null;
    $class_id = $_POST['class_id'] ?? null;
    $question_text = trim($_POST['question_text'] ?? '');
    $question_type = $_POST['question_type'] ?? 'single_choice';
    $option_a = trim($_POST['option_a'] ?? '');
    $option_b = trim($_POST['option_b'] ?? '');
    $option_c = trim($_POST['option_c'] ?? '');
    $option_d = trim($_POST['option_d'] ?? '');
    $option_e = trim($_POST['option_e'] ?? '');
    $correct = $_POST['correct_answer'] ?? null;
    $session = $_POST['session'] ?? null;
    $term = $_POST['term'] ?? null;
    $passage_id = !empty($_POST['passage_id']) ? $_POST['passage_id'] : null;
    $media_id = !empty($_POST['media_id']) ? $_POST['media_id'] : null;
    $new_image_path = uploadImage($_FILES['image_edit'] ?? null);

    if ($question_id && !empty($question_text) && !empty($option_a) && !empty($option_b) && !empty($subject_id)) {
        if ($new_image_path) {
            $stmt = $pdo->prepare("
                UPDATE questions
                SET subject_id = ?, class_id = ?, question_text = ?, option_a = ?, option_b = ?, option_c = ?, option_d = ?, option_e = ?, correct_answer = ?, image_path = ?, passage_id = ?, media_id = ?, session = ?, term = ?, question_type = ?
                WHERE question_id = ?
            ");
            $ok = $stmt->execute([$subject_id, $class_id, $question_text, $option_a, $option_b, $option_c, $option_d, $option_e, $correct, $new_image_path, $passage_id, $media_id, $session, $term, $question_type, $question_id]);
        } else {
            $stmt = $pdo->prepare("
                UPDATE questions
                SET subject_id = ?, class_id = ?, question_text = ?, option_a = ?, option_b = ?, option_c = ?, option_d = ?, option_e = ?, correct_answer = ?, passage_id = ?, media_id = ?, session = ?, term = ?, question_type = ?
                WHERE question_id = ?
            ");
            $ok = $stmt->execute([$subject_id, $class_id, $question_text, $option_a, $option_b, $option_c, $option_d, $option_e, $correct, $passage_id, $media_id, $session, $term, $question_type, $question_id]);
        }
        if ($ok) {
            $message = "Question updated.";
        } else {
            $error = "Failed to update question.";
        }
    } else {
        $error = "Please fill required fields.";
    }
}

// Add Question
if (isset($_POST['add_question'])) {
    $subject_id = $_POST['subject_id'];
    $class_id = $_POST['class_id'] ?? null;
    $question_text = trim($_POST['question_text']);
    $question_type = $_POST['question_type'] ?? 'single_choice';
    $option_a = trim($_POST['option_a']);
    $option_b = trim($_POST['option_b']);
    $option_c = trim($_POST['option_c']);
    $option_d = trim($_POST['option_d']);
    $option_e = trim($_POST['option_e']);
    $correct = $_POST['correct_answer'];
    $session = $_POST['session'];
    $term = $_POST['term'];
    // Passage: use selected or quick-create inline
    $passage_id = !empty($_POST['passage_id']) ? $_POST['passage_id'] : null;
    if (empty($passage_id) && !empty($_POST['p_content_inline'])) {
        $p_title_inline = trim($_POST['p_title_inline'] ?? '');
        $p_content_inline = trim($_POST['p_content_inline']);
        $p_subject_inline = $_POST['p_subject_id_inline'] ?? null;
        $p_class_inline = $_POST['p_class_id_inline'] ?? null;
        $stmtP = $pdo->prepare("INSERT INTO passages (title, content, subject_id, class_id) VALUES (?, ?, ?, ?)");
        if ($stmtP->execute([$p_title_inline, $p_content_inline, $p_subject_inline, $p_class_inline])) {
            $passage_id = $pdo->lastInsertId();
        }
    }
    $media_id = !empty($_POST['media_id']) ? $_POST['media_id'] : null;
    
    $image_path = uploadImage($_FILES['image']);

    if (!empty($question_text) && !empty($option_a) && !empty($option_b)) {
        $stmt = $pdo->prepare("INSERT INTO questions (subject_id, class_id, question_text, option_a, option_b, option_c, option_d, option_e, correct_answer, image_path, passage_id, media_id, session, term, question_type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        if ($stmt->execute([$subject_id, $class_id, $question_text, $option_a, $option_b, $option_c, $option_d, $option_e, $correct, $image_path, $passage_id, $media_id, $session, $term, $question_type])) {
            $message = "Question added successfully.";
        } else {
            $error = "Failed to add question.";
        }
    } else {
        $error = "Please fill required fields.";
    }
}

// Bulk Upload Shared Photos
if (isset($_POST['upload_photos'])) {
    if (!empty($_FILES['attachments']['name'][0])) {
        $count = 0;
        $baseDir = "../assets/uploads/shared/";
        if (!is_dir($baseDir)) {
            @mkdir($baseDir, 0777, true);
        }
        foreach ($_FILES['attachments']['name'] as $idx => $name) {
            if ($_FILES['attachments']['error'][$idx] === 0) {
                $filename = time() . "_" . basename($name);
                $target = $baseDir . $filename;
                $type = strtolower(pathinfo($target, PATHINFO_EXTENSION));
                if (in_array($type, ['jpg','jpeg','png','gif','webp'])) {
                    if (move_uploaded_file($_FILES['attachments']['tmp_name'][$idx], $target)) {
                        $rel = "assets/uploads/shared/" . $filename;
                        $stmt = $pdo->prepare("INSERT INTO media_library (file_path) VALUES (?)");
                        if ($stmt->execute([$rel])) $count++;
                    }
                }
            }
        }
        $message = "Uploaded $count shared photos.";
    } else {
        $error = "Please select photos to upload.";
    }
}

// Bulk Upload (CSV / DOCX)
if (isset($_POST['upload_csv'])) {
    if (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] == 0) {
        $file = $_FILES['csv_file']['tmp_name'];
        $original_name = $_FILES['csv_file']['name'];
        $ext = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));
        
        // Get Form Values (Global for this batch)
        $g_subject_id = !empty($_POST['subject_id']) ? $_POST['subject_id'] : null;
        $g_class_id = !empty($_POST['class_id']) ? $_POST['class_id'] : null;
        $g_session = !empty($_POST['session']) ? $_POST['session'] : null;
        $g_term = !empty($_POST['term']) ? $_POST['term'] : null;
        $g_type = !empty($_POST['question_type']) ? $_POST['question_type'] : 'single_choice';

        $success_count = 0;

        if ($ext === 'docx') {
            require_once '../classes/DocxImport.php';
            $imported_questions = DocxImport::parse($file);
            
            if (is_array($imported_questions)) {
                foreach ($imported_questions as $q) {
                    $q_text = isset($q['question_text']) ? trim($q['question_text']) : '';
                    // Use local type if valid, else global
                    $q_type = isset($q['question_type']) ? trim($q['question_type']) : $g_type;
                    
                    // Options
                    $opts = isset($q['options']) ? explode('|', $q['options']) : [];
                    $opt_a = isset($opts[0]) ? trim($opts[0]) : '';
                    $opt_b = isset($opts[1]) ? trim($opts[1]) : '';
                    $opt_c = isset($opts[2]) ? trim($opts[2]) : '';
                    $opt_d = isset($opts[3]) ? trim($opts[3]) : '';
                    $opt_e = isset($opts[4]) ? trim($opts[4]) : '';
                    
                    // Correct Answer
                    $correct = '';
                    if (isset($q['correct_indices'])) {
                        $idx = (int)$q['correct_indices'];
                        $map = ['A','B','C','D','E'];
                        if (isset($map[$idx])) $correct = $map[$idx];
                    }
                    
                    // Subject ID from docx overrides global if present
                    $final_subject_id = $g_subject_id;
                    if (isset($q['subject_id']) && is_numeric($q['subject_id'])) {
                        $final_subject_id = $q['subject_id'];
                    }

                    if ($final_subject_id && !empty($q_text) && !empty($opt_a) && !empty($opt_b)) {
                        $stmt_ins = $pdo->prepare("INSERT INTO questions (subject_id, class_id, question_text, option_a, option_b, option_c, option_d, option_e, correct_answer, session, term, question_type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                        if ($stmt_ins->execute([$final_subject_id, $g_class_id, $q_text, $opt_a, $opt_b, $opt_c, $opt_d, $opt_e, $correct, $g_session, $g_term, $q_type])) {
                            $success_count++;
                        }
                    }
                }
                $message = "Imported $success_count questions from DOCX.";
            } else {
                $error = $imported_questions;
            }
        } elseif ($ext === 'csv') {
            if (($handle = fopen($file, "r")) !== FALSE) {
                $row = 0;
                while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                    // Header check (skip if first row looks like header)
                    if ($row == 0 && (strtolower($data[0]) == 'question' || strtolower($data[0]) == 'question text')) {
                        $row++;
                        continue;
                    }
                    
                    // Expected CSV Format: 
                    // Question, A, B, C, D, E, Correct(A-E), SubjectCode(opt), Session(opt), Term(opt), ClassName(opt)
                    
                    $q_text = trim($data[0]);
                    $opt_a = trim($data[1]);
                    $opt_b = trim($data[2]);
                    $opt_c = trim($data[3]);
                    $opt_d = trim($data[4]);
                    $opt_e = trim($data[5]);
                    $correct = strtoupper(trim($data[6]));
                    
                    // Use Global or CSV
                    $subj_code = isset($data[7]) ? trim($data[7]) : '';
                    $sess = isset($data[8]) ? trim($data[8]) : '';
                    $term = isset($data[9]) ? trim($data[9]) : '';
                    $class_name = isset($data[10]) ? trim($data[10]) : '';
    
                    // Resolve Subject
                    $final_subject_id = $g_subject_id;
                    if (!$final_subject_id && $subj_code) {
                        $stmt = $pdo->prepare("SELECT subject_id FROM subjects WHERE subject_code = ?");
                        $stmt->execute([$subj_code]);
                        $subj = $stmt->fetch();
                        if ($subj) $final_subject_id = $subj['subject_id'];
                    }
    
                    // Resolve Class
                    $final_class_id = $g_class_id;
                    if (!$final_class_id && $class_name) {
                        $stmt = $pdo->prepare("SELECT class_id FROM classes WHERE class_name = ?");
                        $stmt->execute([$class_name]);
                        $c = $stmt->fetch();
                        if ($c) $final_class_id = $c['class_id'];
                    }
    
                    // Resolve Session/Term
                    $final_session = $g_session ?: $sess;
                    $final_term = $g_term ?: $term;
                    
                    if ($final_subject_id && !empty($q_text)) {
                        $stmt_ins = $pdo->prepare("INSERT INTO questions (subject_id, class_id, question_text, option_a, option_b, option_c, option_d, option_e, correct_answer, session, term, question_type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                        if ($stmt_ins->execute([$final_subject_id, $final_class_id, $q_text, $opt_a, $opt_b, $opt_c, $opt_d, $opt_e, $correct, $final_session, $final_term, $g_type])) {
                            $success_count++;
                        }
                    }
                    $row++;
                }
                fclose($handle);
                $message = "Imported $success_count questions from CSV.";
            }
        } else {
            $error = "Invalid file type. Please upload CSV or DOCX.";
        }
    }
}

// Delete Question
if (isset($_POST['delete_question'])) {
    $qid = $_POST['question_id'];
    $pdo->prepare("DELETE FROM questions WHERE question_id = ?")->execute([$qid]);
    $message = "Question deleted.";
}

// Delete Passage
if (isset($_POST['delete_passage'])) {
    $pid = $_POST['passage_id'];
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM questions WHERE passage_id = ?");
    $stmt->execute([$pid]);
    if ($stmt->fetchColumn() > 0) {
        $error = "Cannot delete passage. It is linked to questions.";
    } else {
        $pdo->prepare("DELETE FROM passages WHERE passage_id = ?")->execute([$pid]);
        $message = "Passage deleted.";
    }
}

// Delete Media
if (isset($_POST['delete_media'])) {
    $mid = $_POST['media_id'];
    $stmt = $pdo->prepare("SELECT file_path FROM media_library WHERE media_id = ?");
    $stmt->execute([$mid]);
    $m = $stmt->fetch();
    if ($m) {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM questions WHERE media_id = ?");
        $stmt->execute([$mid]);
        if ($stmt->fetchColumn() > 0) {
            $error = "Cannot delete media. It is linked to questions.";
        } else {
            if (file_exists("../" . $m['file_path'])) {
                unlink("../" . $m['file_path']);
            }
            $pdo->prepare("DELETE FROM media_library WHERE media_id = ?")->execute([$mid]);
            $message = "Media deleted.";
        }
    }
}

$subjects = $pdo->query("SELECT * FROM subjects")->fetchAll();
$classes = $pdo->query("SELECT * FROM classes")->fetchAll();

// Session/Term options
$currentYear = (int)date('Y');
$sessions = [
    ($currentYear-1) . '/' . $currentYear,
    $currentYear . '/' . ($currentYear+1),
    ($currentYear+1) . '/' . ($currentYear+2),
];
$terms = ['1st Term','2nd Term','3rd Term'];

// Filter Logic
$where = [];
$params = [];
if (isset($_GET['subject_id']) && !empty($_GET['subject_id'])) {
    $where[] = "q.subject_id = ?";
    $params[] = $_GET['subject_id'];
}
if (isset($_GET['class_id']) && !empty($_GET['class_id'])) {
    $where[] = "q.class_id = ?";
    $params[] = $_GET['class_id'];
}
if (isset($_GET['session']) && !empty($_GET['session'])) {
    $where[] = "q.session = ?";
    $params[] = $_GET['session'];
}
if (isset($_GET['term']) && !empty($_GET['term'])) {
    $where[] = "q.term = ?";
    $params[] = $_GET['term'];
}
$where_clause = count($where) ? ('WHERE ' . implode(' AND ', $where)) : '';

// Pagination
$per_page = 20;
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $per_page;

// Total count
$countStmt = $pdo->prepare("SELECT COUNT(*) as cnt FROM questions q $where_clause");
$countStmt->execute($params);
$total = (int)$countStmt->fetchColumn();
$total_pages = max(1, (int)ceil($total / $per_page));

$questions = $pdo->prepare("
    SELECT q.*, s.name as subject_name 
    FROM questions q 
    JOIN subjects s ON q.subject_id = s.subject_id 
    $where_clause 
    ORDER BY q.question_id DESC
    LIMIT $per_page OFFSET $offset
");
$questions->execute($params);
$questions_list = $questions->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Question Bank</title>
    <link rel="stylesheet" href="../assets/css/admin.css">
    <!-- TinyMCE (Free, Secure, Modern) -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/6.8.2/tinymce.min.js" referrerpolicy="origin"></script>
    <script>
        tinymce.init({
            selector: 'textarea.rich-text',
            plugins: 'anchor autolink charmap codesample emoticons image link lists media searchreplace table visualblocks wordcount',
            toolbar: 'undo redo | blocks fontfamily fontsize | bold italic underline strikethrough | link image media table | align lineheight | numlist bullist indent outdent | emoticons charmap | removeformat',
            height: 200,
            menubar: false,
            setup: function (editor) {
                editor.on('change', function () {
                    editor.save();
                });
            }
        });
    </script>
</head>
<body>
    <?php include '../includes/admin_sidebar.php'; ?>
    <div class="content">
        <?php include '../includes/page_header.php'; ?>
        <h1>Question Bank</h1>
        <?php if ($message): ?> <div style="color: green;"><?php echo $message; ?></div> <?php endif; ?>
        <?php if ($error): ?> <div style="color: red;"><?php echo $error; ?></div> <?php endif; ?>

        <div class="card">
            <h3>Add New Question</h3>
            <form method="POST" enctype="multipart/form-data">
                <div class="form-grid">
                    <div>
                        <label>Class</label>
                        <select name="class_id" required>
                            <option value="">Select Class</option>
                            <?php foreach ($classes as $c): ?>
                                <option value="<?php echo $c['class_id']; ?>"><?php echo $c['class_name']; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label>Session</label>
                        <select name="session" required>
                            <option value="">Select Session</option>
                            <?php foreach ($sessions as $sess): ?>
                                <option value="<?php echo $sess; ?>"><?php echo $sess; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="form-grid">
                    <div>
                        <label>Term</label>
                        <select name="term" required>
                            <option value="">Select Term</option>
                            <?php foreach ($terms as $t): ?>
                                <option value="<?php echo $t; ?>"><?php echo $t; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label>Subject</label>
                        <select name="subject_id" required>
                            <option value="">Select Subject</option>
                            <?php foreach ($subjects as $s): ?>
                                <option value="<?php echo $s['subject_id']; ?>"><?php echo $s['name']; ?> (<?php echo $s['subject_code']; ?>)</option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="form-grid">
                    <div>
                        <label>Question Type</label>
                        <select name="question_type" id="question_type" required>
                            <option value="single_choice">Single Choice</option>
                            <option value="multiple_choice">Multichoice</option>
                            <option value="true_false">True/False</option>
                        </select>
                    </div>
                </div>
                <textarea name="question_text" id="question_text" class="rich-text" placeholder="Question Text" required rows="3"></textarea>
                <input type="file" name="image" accept="image/*">
                <p><small>Optional Image</small></p>
                <div class="card" style="margin-top:10px;">
                    <h3 style="margin-bottom:10px;">Attachments</h3>
                    <?php
                    $passages = $pdo->query("SELECT passage_id, title FROM passages ORDER BY passage_id DESC")->fetchAll();
                    $media = $pdo->query("SELECT media_id, file_path FROM media_library ORDER BY media_id DESC")->fetchAll();
                    ?>
                    <div style="display:flex; gap:16px; flex-wrap:wrap;">
                        <div style="flex:1; min-width:280px;">
                            <div style="margin-bottom:8px;">
                                <label style="font-weight:600;">Passage</label>
                            </div>
                            <div style="display:flex; gap:8px; margin-bottom:8px;">
                                <button type="button" class="btn btn-primary" id="usePassageBtn">Use Existing</button>
                                <button type="button" class="btn" id="createPassageBtn">Create New</button>
                            </div>
                            <div id="usePassagePanel">
                                <select name="passage_id" class="w-full">
                                    <option value="">No Passage</option>
                                    <?php foreach ($passages as $p): ?>
                                        <option value="<?php echo $p['passage_id']; ?>"><?php echo htmlspecialchars($p['title'] ?: ('Passage #' . $p['passage_id'])); ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <p style="color:#64748b; font-size:13px;">Select a saved passage to attach to this question.</p>
                            </div>
                            <div id="createPassagePanel" style="display:none;">
                                <p style="color:#475569; font-size:14px; margin:6px 0;">Quick-create a passage and attach it.</p>
                                <input type="text" name="p_title_inline" placeholder="Passage Title (optional)">
                                <textarea name="p_content_inline" class="rich-text" rows="4" placeholder="Write passage content here"></textarea>
                                <div class="form-grid">
                                    <div>
                                        <select name="p_subject_id_inline">
                                            <option value="">Subject (optional)</option>
                                            <?php foreach ($subjects as $s): ?>
                                                <option value="<?php echo $s['subject_id']; ?>"><?php echo $s['name']; ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div>
                                        <select name="p_class_id_inline">
                                            <option value="">Class (optional)</option>
                                            <?php foreach ($classes as $c): ?>
                                                <option value="<?php echo $c['class_id']; ?>"><?php echo $c['class_name']; ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                <p style="color:#64748b; font-size:13px;">When you save the question, the passage will be created and linked.</p>
                            </div>
                        </div>
                        <div style="flex:1; min-width:280px;">
                            <label style="font-weight:600;">Shared Photo</label>
                            <select name="media_id" class="w-full">
                                <option value="">No Photo</option>
                                <?php foreach ($media as $m): ?>
                                    <option value="<?php echo $m['media_id']; ?>"><?php echo htmlspecialchars($m['file_path']); ?></option>
                                <?php endforeach; ?>
                            </select>
                            <p style="color:#64748b; font-size:13px;">Choose a previously uploaded photo to include.</p>
                        </div>
                    </div>
                </div>

                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                    <div id="optA_wrap">
                        <label>Option A</label>
                        <textarea name="option_a" class="rich-text" placeholder="Option A"></textarea>
                    </div>
                    <div id="optB_wrap">
                        <label>Option B</label>
                        <textarea name="option_b" class="rich-text" placeholder="Option B"></textarea>
                    </div>
                    <div id="optC_wrap">
                        <label>Option C</label>
                        <textarea name="option_c" class="rich-text" placeholder="Option C"></textarea>
                    </div>
                    <div id="optD_wrap">
                        <label>Option D</label>
                        <textarea name="option_d" class="rich-text" placeholder="Option D"></textarea>
                    </div>
                </div>
                <div style="margin-top: 10px;" id="optE_wrap">
                    <label>Option E (Optional)</label>
                    <textarea name="option_e" class="rich-text" placeholder="Option E"></textarea>
                </div>
                
                <div style="display: flex; gap: 10px;">
                    <select name="correct_answer" id="correct_answer" required style="width: 50%;">
                        <option value="">Correct Answer</option>
                        <option value="A">Option A</option>
                        <option value="B">Option B</option>
                        <option value="C">Option C</option>
                        <option value="D">Option D</option>
                        <option value="E">Option E</option>
                    </select>
                </div>

                <button type="submit" name="add_question" class="btn">Add Question</button>
                <a class="btn" style="background:#28a745" href="?download_sample=questions">Download Sample CSV</a>
            </form>
        </div>

        <div class="card">
            <h3>Create Passage</h3>
            <form method="POST">
                <input type="text" name="p_title" placeholder="Title (optional)">
                <select name="p_subject_id">
                    <option value="">Subject (optional)</option>
                    <?php foreach ($subjects as $s): ?>
                        <option value="<?php echo $s['subject_id']; ?>"><?php echo $s['name']; ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="p_class_id">
                    <option value="">Class (optional)</option>
                    <?php foreach ($classes as $c): ?>
                        <option value="<?php echo $c['class_id']; ?>"><?php echo $c['class_name']; ?></option>
                    <?php endforeach; ?>
                </select>
                <div style="display:flex; gap:10px;">
                    <select name="p_session" style="width:50%;">
                        <option value="">Session</option>
                        <?php foreach ($sessions as $sess): ?>
                            <option value="<?php echo $sess; ?>"><?php echo $sess; ?></option>
                        <?php endforeach; ?>
                    </select>
                    <select name="p_term" style="width:50%;">
                        <option value="">Term</option>
                        <?php foreach ($terms as $t): ?>
                            <option value="<?php echo $t; ?>"><?php echo $t; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <textarea name="p_content" id="p_content" class="rich-text" rows="6" placeholder="Paste passage content. Basic HTML is allowed."></textarea>
                <button type="submit" name="add_passage" class="btn">Save Passage</button>
            </form>
        </div>

        <div class="card">
            <h3>Bulk Upload Questions (CSV / DOCX)</h3>
            <p>
                <strong>CSV Format:</strong> <code>Question, A, B, C, D, E, Correct(A-E), [SubjectCode], [Session], [Term]</code><br>
                <small>Columns in [] are optional if selected below.</small><br>
                <a href="data:text/csv;charset=utf-8,Question,OptionA,OptionB,OptionC,OptionD,OptionE,Correct,SubjectCode,Session,Term%0AWhat is 1+1?,1,2,3,4,,B,MATH101,2024/2025,1st Term" download="questions_sample.csv" style="color: #007bff; text-decoration: none;">Download Sample CSV</a>
            </p>
            <p style="margin-top: 10px; background: #f8f9fa; padding: 10px; border-radius: 4px;">
                <strong>DOCX Format (Text only):</strong><br>
                <code>subject_id: 1</code><br>
                <code>question_type: single_choice</code><br>
                <code>question_text: Democracy entails the following except ________.</code><br>
                <code>options: Option 1|Option 2|Option 3|Option 4</code><br>
                <code>correct_indices: 3</code> (0-based index, so 3 means 4th option)<br>
                <small>Separate questions with new lines. Global dropdowns below apply if fields are missing in DOCX.</small>
            </p>
            <form method="POST" enctype="multipart/form-data">
                <div class="form-grid">
                    <div class="form-group">
                        <label>Subject (Applies to all if not in file)</label>
                        <select name="subject_id" class="form-control">
                            <option value="">-- From File --</option>
                            <?php foreach ($subjects as $s): ?>
                                <option value="<?php echo $s['subject_id']; ?>"><?php echo $s['name']; ?> (<?php echo $s['subject_code']; ?>)</option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Class (Applies to all)</label>
                        <select name="class_id" class="form-control">
                            <option value="">-- From File --</option>
                            <?php foreach ($classes as $c): ?>
                                <option value="<?php echo $c['class_id']; ?>"><?php echo $c['class_name']; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="form-grid">
                    <div class="form-group">
                        <label>Session</label>
                        <select name="session" class="form-control">
                            <option value="">-- From File --</option>
                            <?php foreach ($sessions as $sess): ?>
                                <option value="<?php echo $sess; ?>"><?php echo $sess; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Term</label>
                        <select name="term" class="form-control">
                            <option value="">-- From File --</option>
                            <?php foreach ($terms as $t): ?>
                                <option value="<?php echo $t; ?>"><?php echo $t; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Question Type</label>
                        <select name="question_type" class="form-control">
                            <option value="single_choice">Single Choice</option>
                            <option value="multiple_choice">Multichoice</option>
                            <option value="true_false">True/False</option>
                        </select>
                    </div>
                </div>
                
                <input type="file" name="csv_file" accept=".csv, .docx" required style="margin-top:10px;">
                <button type="submit" name="upload_csv" class="btn">Upload File</button>
            </form>
        </div>

        <div class="card">
            <h3>Bulk Upload Shared Photos</h3>
            <form method="POST" enctype="multipart/form-data">
                <input type="file" name="attachments[]" accept="image/*" multiple required>
                <button type="submit" name="upload_photos" class="btn">Upload Photos</button>
            </form>
        </div>

        <hr>
        
        <form method="GET">
            <div style="display:flex; gap:10px; flex-wrap:wrap;">
            <select name="subject_id">
                <option value="">All Subjects</option>
                <?php foreach ($subjects as $s): ?>
                    <option value="<?php echo $s['subject_id']; ?>" <?php if(isset($_GET['subject_id']) && $_GET['subject_id'] == $s['subject_id']) echo 'selected'; ?>>
                        <?php echo $s['name']; ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <select name="class_id">
                <option value="">All Classes</option>
                <?php foreach ($classes as $c): ?>
                    <option value="<?php echo $c['class_id']; ?>" <?php if(isset($_GET['class_id']) && $_GET['class_id'] == $c['class_id']) echo 'selected'; ?>>
                        <?php echo $c['class_name']; ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <select name="session">
                <option value="">All Sessions</option>
                <?php foreach ($sessions as $sess): ?>
                    <option value="<?php echo $sess; ?>" <?php if(isset($_GET['session']) && $_GET['session'] == $sess) echo 'selected'; ?>>
                        <?php echo $sess; ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <select name="term">
                <option value="">All Terms</option>
                <?php foreach ($terms as $t): ?>
                    <option value="<?php echo $t; ?>" <?php if(isset($_GET['term']) && $_GET['term'] == $t) echo 'selected'; ?>>
                        <?php echo $t; ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <button type="submit" class="btn">Filter</button>
            </div>
        </form>

        <div class="table-responsive">
        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Question</th>
                    <th>Image</th>
                    <th>Shared</th>
                    <th>Passage</th>
                    <th>Subject</th>
                    <th>Class</th>
                    <th>Correct</th>
                    <th>Session/Term</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($questions_list as $q): ?>
                <tr>
                    <td><?php echo $q['question_id']; ?></td>
                    <td>
                        <?php echo substr(htmlspecialchars($q['question_text']), 0, 50) . '...'; ?>
                        <br>
                        <small>
                            A: <?php echo $q['option_a']; ?>, 
                            B: <?php echo $q['option_b']; ?>, 
                            C: <?php echo $q['option_c']; ?>, 
                            D: <?php echo $q['option_d']; ?>
                            <?php if($q['option_e']) echo ", E: " . $q['option_e']; ?>
                        </small>
                    </td>
                    <td>
                        <?php if ($q['image_path']): ?>
                            <img src="../<?php echo $q['image_path']; ?>" class="preview">
                        <?php else: ?>
                            -
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if (!empty($q['media_id'])) {
                            $ms = $pdo->prepare('SELECT file_path FROM media_library WHERE media_id = ?');
                            $ms->execute([$q['media_id']]);
                            $mf = $ms->fetch();
                            echo $mf ? '<img src="../'.$mf['file_path'].'" class="preview">' : '-';
                        } else { echo '-'; } ?>
                    </td>
                    <td>
                        <?php if (!empty($q['passage_id'])) {
                            $ps = $pdo->prepare('SELECT title FROM passages WHERE passage_id = ?');
                            $ps->execute([$q['passage_id']]);
                            $pf = $ps->fetch();
                            echo $pf ? htmlspecialchars($pf['title'] ?: ('Passage #'.$q['passage_id'])) : '-';
                        } else { echo '-'; } ?>
                    </td>
                    <td><?php echo $q['subject_name']; ?></td>
                    <td>
                        <?php
                        if (!empty($q['class_id'])) {
                            $stmt = $pdo->prepare('SELECT class_name FROM classes WHERE class_id = ?');
                            $stmt->execute([$q['class_id']]);
                            $c = $stmt->fetch();
                            echo $c ? htmlspecialchars($c['class_name']) : 'N/A';
                        } else {
                            echo 'N/A';
                        }
                        ?>
                    </td>
                    <td><?php echo $q['correct_answer']; ?></td>
                    <td><?php echo $q['session'] . ' / ' . $q['term']; ?></td>
                    <td>
                        <button type="button"
                                class="btn"
                                onclick="openEditQuestionModal(<?php echo $q['question_id']; ?>)"
                                data-qid="<?php echo $q['question_id']; ?>"
                                data-question='<?php echo json_encode([
                                    'question_id' => $q['question_id'],
                                    'subject_id' => $q['subject_id'],
                                    'class_id' => $q['class_id'],
                                    'question_text' => $q['question_text'],
                                    'option_a' => $q['option_a'],
                                    'option_b' => $q['option_b'],
                                    'option_c' => $q['option_c'],
                                    'option_d' => $q['option_d'],
                                    'option_e' => $q['option_e'],
                                    'correct_answer' => $q['correct_answer'],
                                    'session' => $q['session'],
                                    'term' => $q['term'],
                                    'passage_id' => $q['passage_id'],
                                    'media_id' => $q['media_id'],
                                    'question_type' => $q['question_type'] ?? 'single_choice'
                                ]); ?>'>
                            Edit
                        </button>
                        <form method="POST" style="display:inline;" onsubmit="return confirm('Delete?');">
                            <input type="hidden" name="question_id" value="<?php echo $q['question_id']; ?>">
                            <button type="submit" name="delete_question" class="btn btn-danger">Delete</button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            </table>
        </div>
        
        <div style="margin-top:15px; display:flex; gap:8px; flex-wrap:wrap;">
            <?php
            $qs = $_GET;
            for ($p=1; $p<=$total_pages; $p++) {
                $qs['page'] = $p;
                $url = '?' . http_build_query($qs);
                $active = $p === $page;
                echo '<a href="'.$url.'" class="btn" style="background:'.($active?'#007bff':'#6c757d').';">'. $p .'</a>';
            }
            ?>
        </div>
        
        <hr>

        <div class="card">
            <h3>Manage Passages</h3>
            <div style="overflow-x: auto;">
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Title</th>
                            <th>Content Preview</th>
                            <th>Subject/Class</th>
                            <th>Session/Term</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $passages_all = $pdo->query("SELECT p.*, s.name as subject_name, c.class_name 
                                                   FROM passages p 
                                                   LEFT JOIN subjects s ON p.subject_id = s.subject_id 
                                                   LEFT JOIN classes c ON p.class_id = c.class_id 
                                                   ORDER BY p.passage_id DESC")->fetchAll();
                        foreach ($passages_all as $p): ?>
                        <tr>
                            <td><?php echo $p['passage_id']; ?></td>
                            <td><?php echo htmlspecialchars($p['title']); ?></td>
                            <td><?php echo substr(strip_tags($p['content']), 0, 100) . '...'; ?></td>
                            <td>
                                <?php echo $p['subject_name'] ? $p['subject_name'] : '-'; ?> / 
                                <?php echo $p['class_name'] ? $p['class_name'] : '-'; ?>
                            </td>
                            <td><?php echo $p['session'] . ' ' . $p['term']; ?></td>
                            <td>
                                <form method="POST" onsubmit="return confirm('Delete Passage? Questions using this will lose the passage.');">
                                    <input type="hidden" name="passage_id" value="<?php echo $p['passage_id']; ?>">
                                    <button type="submit" name="delete_passage" class="btn btn-danger">Delete</button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="card">
            <h3>Manage Media Library</h3>
            <div style="display: flex; flex-wrap: wrap; gap: 10px;">
                <?php 
                $media_all = $pdo->query("SELECT * FROM media_library ORDER BY media_id DESC")->fetchAll();
                foreach ($media_all as $m): ?>
                <div style="border:1px solid #ddd; padding:5px; text-align:center;">
                    <img src="../<?php echo $m['file_path']; ?>" style="width:100px; height:100px; object-fit:cover;">
                    <br>
                    <form method="POST" onsubmit="return confirm('Delete this photo?');" style="margin-top:5px;">
                        <input type="hidden" name="media_id" value="<?php echo $m['media_id']; ?>">
                        <button type="submit" name="delete_media" style="background:red; color:white; border:none; padding:2px 5px; cursor:pointer;">Del</button>
                    </form>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        

        <div class="main-footer">
            &copy; 2026 Designed by FGV
        </div>
    </div>
    <div class="modal-backdrop" id="editQuestionBackdrop">
        <div class="modal">
            <header>Edit Question</header>
            <form method="POST" id="editQuestionForm" enctype="multipart/form-data">
                <input type="hidden" name="question_id" id="edit_q_id">
                <div class="form-grid">
                    <div class="form-group">
                        <label>Class</label>
                        <select name="class_id" id="edit_q_class_id" class="form-control" required>
                            <option value="">Select Class</option>
                            <?php foreach ($classes as $c): ?>
                                <option value="<?php echo $c['class_id']; ?>"><?php echo $c['class_name']; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Session</label>
                        <select name="session" id="edit_q_session" class="form-control" required>
                            <option value="">Select Session</option>
                            <?php foreach ($sessions as $sess): ?>
                                <option value="<?php echo $sess; ?>"><?php echo $sess; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="form-grid">
                    <div class="form-group">
                        <label>Term</label>
                        <select name="term" id="edit_q_term" class="form-control" required>
                            <option value="">Select Term</option>
                            <?php foreach ($terms as $t): ?>
                                <option value="<?php echo $t; ?>"><?php echo $t; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Subject</label>
                        <select name="subject_id" id="edit_q_subject_id" class="form-control" required>
                            <option value="">Select Subject</option>
                            <?php foreach ($subjects as $s): ?>
                                <option value="<?php echo $s['subject_id']; ?>"><?php echo $s['name']; ?> (<?php echo $s['subject_code']; ?>)</option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="form-grid">
                    <div class="form-group">
                        <label>Question Type</label>
                        <select name="question_type" id="edit_q_type" class="form-control" required>
                            <option value="single_choice">Single Choice</option>
                            <option value="multiple_choice">Multichoice</option>
                            <option value="true_false">True/False</option>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label>Question Text</label>
                    <textarea name="question_text" id="edit_q_question_text" class="rich-text" rows="4" required></textarea>
                </div>
                <div class="form-grid">
                    <div class="form-group">
                        <label>Option A</label>
                        <textarea name="option_a" id="edit_q_option_a" class="rich-text"></textarea>
                    </div>
                    <div class="form-group">
                        <label>Option B</label>
                        <textarea name="option_b" id="edit_q_option_b" class="rich-text"></textarea>
                    </div>
                </div>
                <div class="form-grid">
                    <div class="form-group">
                        <label>Option C</label>
                        <textarea name="option_c" id="edit_q_option_c" class="rich-text"></textarea>
                    </div>
                    <div class="form-group">
                        <label>Option D</label>
                        <textarea name="option_d" id="edit_q_option_d" class="rich-text"></textarea>
                    </div>
                </div>
                <div class="form-group">
                    <label>Option E (Optional)</label>
                    <textarea name="option_e" id="edit_q_option_e" class="rich-text"></textarea>
                </div>
                <div class="form-grid">
                    <div class="form-group">
                        <label>Correct Answer</label>
                        <select name="correct_answer" id="edit_q_correct" class="form-control" required>
                            <option value="">Select</option>
                            <option value="A">A</option>
                            <option value="B">B</option>
                            <option value="C">C</option>
                            <option value="D">D</option>
                            <option value="E">E</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Image (replace)</label>
                        <input type="file" name="image_edit" accept="image/*" class="form-control">
                    </div>
                </div>
                <div class="form-grid">
                    <div class="form-group">
                        <label>Passage</label>
                        <select name="passage_id" id="edit_q_passage_id" class="form-control">
                            <option value="">No Passage</option>
                            <?php
                            $passages = $pdo->query("SELECT passage_id, title FROM passages ORDER BY passage_id DESC")->fetchAll();
                            foreach ($passages as $p): ?>
                                <option value="<?php echo $p['passage_id']; ?>"><?php echo htmlspecialchars($p['title'] ?: ('Passage #'.$p['passage_id'])); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Shared Photo</label>
                        <select name="media_id" id="edit_q_media_id" class="form-control">
                            <option value="">No Photo</option>
                            <?php
                            $media = $pdo->query("SELECT media_id, file_path FROM media_library ORDER BY media_id DESC")->fetchAll();
                            foreach ($media as $m): ?>
                                <option value="<?php echo $m['media_id']; ?>"><?php echo htmlspecialchars($m['file_path']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="actions">
                    <button type="button" class="btn" onclick="closeEditQuestionModal()">Cancel</button>
                    <button type="submit" name="update_question" class="btn btn-primary">Save Changes</button>
                </div>
            </form>
        </div>
    </div>
<script>
    (function(){
        const useBtn = document.getElementById('usePassageBtn');
        const createBtn = document.getElementById('createPassageBtn');
        const usePanel = document.getElementById('usePassagePanel');
        const createPanel = document.getElementById('createPassagePanel');
        if (useBtn && createBtn) {
            useBtn.addEventListener('click', function(){
                useBtn.classList.add('btn-primary');
                createBtn.classList.remove('btn-primary');
                usePanel.style.display = '';
                createPanel.style.display = 'none';
            });
            createBtn.addEventListener('click', function(){
                createBtn.classList.add('btn-primary');
                useBtn.classList.remove('btn-primary');
                usePanel.style.display = 'none';
                createPanel.style.display = '';
            });
        }
    })();
    function openEditQuestionModal(id) {
        const btn = document.querySelector('button[data-qid="'+id+'"]');
        if (!btn) return;
        const data = JSON.parse(btn.getAttribute('data-question'));
        const bd = document.getElementById('editQuestionBackdrop');
        if (!bd) return;
        document.getElementById('edit_q_id').value = data.question_id || '';
        document.getElementById('edit_q_class_id').value = data.class_id || '';
        document.getElementById('edit_q_session').value = data.session || '';
        document.getElementById('edit_q_term').value = data.term || '';
        document.getElementById('edit_q_subject_id').value = data.subject_id || '';
        document.getElementById('edit_q_type').value = data.question_type || 'single_choice';
        if (window.tinymce && tinymce.get('edit_q_question_text')) {
            tinymce.get('edit_q_question_text').setContent(data.question_text || '');
        } else {
            document.getElementById('edit_q_question_text').value = data.question_text || '';
        }
        const setRT = (id, val) => {
            if (window.tinymce && tinymce.get(id)) tinymce.get(id).setContent(val || ''); else document.getElementById(id).value = val || '';
        };
        setRT('edit_q_option_a', data.option_a || '');
        setRT('edit_q_option_b', data.option_b || '');
        setRT('edit_q_option_c', data.option_c || '');
        setRT('edit_q_option_d', data.option_d || '');
        setRT('edit_q_option_e', data.option_e || '');
        document.getElementById('edit_q_correct').value = data.correct_answer || '';
        document.getElementById('edit_q_passage_id').value = data.passage_id || '';
        document.getElementById('edit_q_media_id').value = data.media_id || '';
        bd.classList.add('show');
        document.body.classList.add('modal-open');
    }
    function closeEditQuestionModal() {
        const bd = document.getElementById('editQuestionBackdrop');
        if (bd) bd.classList.remove('show');
        document.body.classList.remove('modal-open');
    }
    (function(){
        const typeSel = document.getElementById('question_type');
        const optC = document.getElementById('optC_wrap');
        const optD = document.getElementById('optD_wrap');
        const optE = document.getElementById('optE_wrap');
        const correct = document.getElementById('correct_answer');
        const update = () => {
            const v = typeSel.value;
            if (v === 'true_false') {
                optC.style.display = 'none';
                optD.style.display = 'none';
                optE.style.display = 'none';
                Array.from(correct.options).forEach(o => {
                    o.style.display = (o.value === '' || o.value === 'A' || o.value === 'B') ? '' : 'none';
                });
                if (!['A','B'].includes(correct.value)) correct.value = '';
            } else {
                optC.style.display = '';
                optD.style.display = '';
                optE.style.display = '';
                Array.from(correct.options).forEach(o => { o.style.display = ''; });
            }
        };
        if (typeSel) {
            typeSel.addEventListener('change', update);
            update();
        }
    })();
</script>
</body>
</html>
