<?php
session_start();
require_once 'db.php';

$role = $_SESSION['role'] ?? '';
if (!isset($_SESSION['user_id']) || !in_array($role, ['admin', 'exam_editor', 'course_editor'])) {
    die("<div style='padding:20px; color:red; font-weight:bold;'>Access Denied. You do not have permission.</div>");
}

$exam_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$stmt = $pdo->prepare("SELECT * FROM exams WHERE id = ?");
$stmt->execute([$exam_id]);
$exam = $stmt->fetch();

if (!$exam) {
    die("Exam not found!");
}

$tab = isset($_GET['tab']) ? $_GET['tab'] : 'settings';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_settings'])) {
    $title = trim($_POST['title']);
    $live_start_date = !empty($_POST['live_start_date']) ? $_POST['live_start_date'] : null;
    $live_end_date = !empty($_POST['live_end_date']) ? $_POST['live_end_date'] : null;
    $practice_date = !empty($_POST['practice_date']) ? $_POST['practice_date'] : null;
    $duration = (int)$_POST['duration'];
    $max_attempts = (int)$_POST['max_attempts'];
    $negative_marks = (float)$_POST['negative_marks'];
    $passcode = trim($_POST['exam_passcode']);
    $exam_type = $_POST['exam_type'] ?? 'live';

    $stmt = $pdo->prepare("UPDATE exams SET title = ?, live_start_date = ?, live_end_date = ?, duration = ?, max_attempts = ?, negative_marks = ?, passcode = ?, practice_date = ?, exam_type = ? WHERE id = ?");
    $stmt->execute([$title, $live_start_date, $live_end_date, $duration, $max_attempts, $negative_marks, $passcode, $practice_date, $exam_type, $exam_id]);
    
    header("Location: admin_edit_exam.php?id=$exam_id&tab=settings&msg=saved");
    exit;
}

if (isset($_GET['delete_q'])) {
    $del = (int)$_GET['delete_q'];
    $pdo->prepare("DELETE FROM questions WHERE id = ? AND exam_id = ?")->execute([$del, $exam_id]);
    header("Location: admin_edit_exam.php?id=$exam_id&tab=questions&msg=q_deleted");
    exit;
}

if (isset($_GET['copy_q'])) {
    $cpy = (int)$_GET['copy_q'];
    $st = $pdo->prepare("SELECT * FROM questions WHERE id = ? AND exam_id = ?");
    $st->execute([$cpy, $exam_id]);
    $q_to_copy = $st->fetch(PDO::FETCH_ASSOC);
    if ($q_to_copy) {
        $_SESSION['copied_question'] = $q_to_copy;
        header("Location: admin_edit_exam.php?id=$exam_id&tab=questions&msg=q_copied");
        exit;
    }
}

if (isset($_GET['paste_q'])) {
    if (isset($_SESSION['copied_question'])) {
        $q = $_SESSION['copied_question'];
        $stmt = $pdo->prepare("INSERT INTO questions (exam_id, question_text, image_url, opt_a, opt_b, opt_c, opt_d, correct_opt, explanation, explanation_image_url, mark) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$exam_id, $q['question_text'], $q['image_url'], $q['opt_a'], $q['opt_b'], $q['opt_c'], $q['opt_d'], $q['correct_opt'], $q['explanation'], $q['explanation_image_url'] ?? null, $q['mark']]);
        header("Location: admin_edit_exam.php?id=$exam_id&tab=questions&msg=q_pasted");
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_question'])) {
    $qt = trim($_POST['question_text']);
    $optA = trim($_POST['opt_a']);
    $optB = trim($_POST['opt_b']);
    $optC = trim($_POST['opt_c']);
    $optD = trim($_POST['opt_d']);
    $correct = $_POST['correct'];
    $explanation = trim($_POST['explanation']);
    
    $image_url = null;
    $upload_dir = 'uploads/questions/';
    if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
        
    if (isset($_FILES['question_image']) && $_FILES['question_image']['error'] == 0) {
        $file_ext = pathinfo($_FILES['question_image']['name'], PATHINFO_EXTENSION);
        $file_name = time() . '_' . rand(100, 999) . '.' . $file_ext;
        move_uploaded_file($_FILES['question_image']['tmp_name'], $upload_dir . $file_name);
        $image_url = $upload_dir . $file_name;
    }
    
    $expl_image_url = null;
    if (isset($_FILES['explanation_image']) && $_FILES['explanation_image']['error'] == 0) {
        $file_ext = pathinfo($_FILES['explanation_image']['name'], PATHINFO_EXTENSION);
        $file_name = 'expl_' . time() . '_' . rand(100, 999) . '.' . $file_ext;
        move_uploaded_file($_FILES['explanation_image']['tmp_name'], $upload_dir . $file_name);
        $expl_image_url = $upload_dir . $file_name;
    }

    $stmt = $pdo->prepare("INSERT INTO questions (exam_id, question_text, image_url, opt_a, opt_b, opt_c, opt_d, correct_opt, explanation, explanation_image_url, mark) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([$exam_id, $qt, $image_url, $optA, $optB, $optC, $optD, $correct, $explanation, $expl_image_url, $exam['per_question_mark'] ?? 1.0]);
    
    header("Location: admin_edit_exam.php?id=$exam_id&tab=questions&msg=q_added");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_question'])) {
    $q_id = (int)$_POST['question_id'];
    $qt = trim($_POST['question_text']);
    $optA = trim($_POST['opt_a']);
    $optB = trim($_POST['opt_b']);
    $optC = trim($_POST['opt_c']);
    $optD = trim($_POST['opt_d']);
    $correct = $_POST['correct'];
    $explanation = trim($_POST['explanation']);
    
    $upload_dir = 'uploads/questions/';
    if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
    
    $update_fields = ["question_text = ?", "opt_a = ?", "opt_b = ?", "opt_c = ?", "opt_d = ?", "correct_opt = ?", "explanation = ?"];
    $params = [$qt, $optA, $optB, $optC, $optD, $correct, $explanation];
    
    if (isset($_FILES['question_image']) && $_FILES['question_image']['error'] == 0) {
        $file_ext = pathinfo($_FILES['question_image']['name'], PATHINFO_EXTENSION);
        $file_name = time() . '_' . rand(100, 999) . '.' . $file_ext;
        move_uploaded_file($_FILES['question_image']['tmp_name'], $upload_dir . $file_name);
        $update_fields[] = "image_url = ?";
        $params[] = $upload_dir . $file_name;
    }
    
    if (isset($_FILES['explanation_image']) && $_FILES['explanation_image']['error'] == 0) {
        $file_ext = pathinfo($_FILES['explanation_image']['name'], PATHINFO_EXTENSION);
        $file_name = 'expl_' . time() . '_' . rand(100, 999) . '.' . $file_ext;
        move_uploaded_file($_FILES['explanation_image']['tmp_name'], $upload_dir . $file_name);
        $update_fields[] = "explanation_image_url = ?";
        $params[] = $upload_dir . $file_name;
    }
    
    $params[] = $q_id;
    $params[] = $exam_id;
    
    $stmt = $pdo->prepare("UPDATE questions SET " . implode(', ', $update_fields) . " WHERE id = ? AND exam_id = ?");
    $stmt->execute($params);
    
    header("Location: admin_edit_exam.php?id=$exam_id&tab=questions&msg=q_updated");
    exit;
}

$q_stmt = $pdo->prepare("SELECT * FROM questions WHERE exam_id = ?");
$q_stmt->execute([$exam_id]);
$questions = $q_stmt->fetchAll();

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Exam - <?php echo htmlspecialchars($exam['title']); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
    
    <!-- TinyMCE 6 open source free version, NO API KEY needed -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/6.8.3/tinymce.min.js"></script>

    <style>
        body { background-color: #f3f4f6; color: #1f2937; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; }
        .sidebar-item { color: #4b5563; padding: 12px 16px; border-radius: 8px; cursor: pointer; transition: all 0.2s; }
        .sidebar-item:hover { color: #111827; background-color: #e5e7eb; }
        .sidebar-item.active { background-color: #2563eb; color: #fff; font-weight: 500; }
        .form-label { font-size: 0.75rem; text-transform: uppercase; font-weight: 700; color: #4b5563; letter-spacing: 0.05em; margin-bottom: 6px; display: block; }
        .custom-input { background-color: #ffffff; border: 1px solid #d1d5db; color: #111827; padding: 10px 12px; border-radius: 6px; width: 100%; transition: border-color 0.2s; outline: none; }
        .custom-input:focus { border-color: #2563eb; outline: 2px solid #bfdbfe; }
        .save-btn { background-color: #2563eb; color: #fff; font-weight: 600; padding: 10px 24px; border-radius: 6px; border: none; cursor: pointer; transition: opacity 0.2s; }
        .save-btn:hover { opacity: 0.9; }
        .topbar-header { font-family: ui-serif, Georgia, Cambria, "Times New Roman", Times, serif; font-style: italic; font-size: 1.25rem; font-weight: 400; }
        
        .radio-wrapper { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; }
        .radio-custom {
            appearance: none; background-color: transparent; margin: 0; font: inherit; color: currentColor; width: 1.15em; height: 1.15em; border: 2px solid #9ca3af; border-radius: 50%; display: grid; place-content: center; cursor: pointer;
        }
        .radio-custom::before { content: ""; width: 0.65em; height: 0.65em; border-radius: 50%; transform: scale(0); transition: 120ms transform ease-in-out; box-shadow: inset 1em 1em var(--radio-color, #2563eb); background-color: #2563eb; }
        .radio-custom:checked::before { transform: scale(1); }
        .radio-custom:checked { border-color: #2563eb; }
        
        .success-msg { background-color: #dcfce7; border: 1px solid #bbf7d0; color: #166534; padding: 12px 16px; border-radius: 8px; margin-bottom: 24px; }
        ::-webkit-calendar-picker-indicator { filter: none; opacity: 1; }
    </style>
</head>
<body>

<div class="min-h-screen flex flex-col">
    <!-- Topbar -->
    <header class="border-b border-gray-200 bg-white p-4 flex items-center gap-4 shadow-sm">
        <a href="admin_exams.php?course_id=<?php echo $exam['course_id']; ?>" class="text-gray-500 hover:text-gray-900 transition"><i class="bi bi-arrow-left fs-5"></i></a>
        <div class="bg-blue-600 text-white text-xs font-bold px-2 py-1 rounded">ADMIN</div>
        <div class="topbar-header text-gray-900">EDIT EXAM: <?php echo strtoupper(htmlspecialchars($exam['title'])); ?></div>
    </header>

    <!-- Main Content -->
    <div class="flex flex-col md:flex-row flex-1 overflow-hidden p-4 md:p-6 gap-6 md:gap-8 max-w-6xl mx-auto w-full">
        
        <!-- Sidebar -->
        <aside class="w-full md:w-64 flex-shrink-0">
            <div class="border border-gray-200 rounded-xl p-2 bg-white shadow-sm">
                <a href="?id=<?php echo $exam_id; ?>&tab=settings" class="sidebar-item block <?php echo $tab === 'settings' ? 'active' : ''; ?>">Settings</a>
                <a href="?id=<?php echo $exam_id; ?>&tab=questions" class="sidebar-item block <?php echo $tab === 'questions' ? 'active' : ''; ?>">Questions</a>
                <a href="?id=<?php echo $exam_id; ?>&tab=results" class="sidebar-item block <?php echo $tab === 'results' ? 'active' : ''; ?>">Results</a>
            </div>
        </aside>

        <!-- Content Area -->
        <main class="flex-1 overflow-y-auto">
            <div class="border border-gray-200 rounded-xl p-4 md:p-8 bg-white shadow-sm">
                
                <?php if(isset($_GET['msg']) && $_GET['msg'] === 'saved'): ?>
                    <div class="success-msg mb-6">Settings updated successfully!</div>
                <?php endif; ?>
                
                <?php if(isset($_GET['msg']) && $_GET['msg'] === 'q_added'): ?>
                    <div class="success-msg mb-6">Question added successfully! You can add another one below.</div>
                <?php endif; ?>

                <?php if(isset($_GET['msg']) && $_GET['msg'] === 'q_copied'): ?>
                    <div class="success-msg mb-6">Question copied to clipboard! You can paste it into this or another exam.</div>
                <?php endif; ?>

                <?php if(isset($_GET['msg']) && $_GET['msg'] === 'q_pasted'): ?>
                    <div class="success-msg mb-6">Question pasted successfully!</div>
                <?php endif; ?>

                <?php if(isset($_GET['msg']) && $_GET['msg'] === 'q_updated'): ?>
                    <div class="success-msg mb-6">Question updated successfully!</div>
                <?php endif; ?>

                <?php if ($tab === 'settings'): ?>
                    <form method="POST">
                        <div class="space-y-6">
                            <div>
                                <label class="form-label">EXAM TITLE</label>
                                <input type="text" name="title" class="custom-input" value="<?php echo htmlspecialchars($exam['title']); ?>" required>
                            </div>
                            
                            <div>
                                <label class="form-label">EXAM TYPE</label>
                                <select name="exam_type" class="custom-input" required>
                                    <option value="live" <?php echo $exam['exam_type'] === 'live' ? 'selected' : ''; ?>>Live Exam</option>
                                    <option value="practice" <?php echo $exam['exam_type'] === 'practice' ? 'selected' : ''; ?>>Practice Exam</option>
                                </select>
                            </div>
                            
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div>
                                    <label class="form-label">LIVE START DATE (OPTIONAL)</label>
                                    <input type="datetime-local" name="live_start_date" class="custom-input" value="<?php echo $exam['live_start_date'] ? date('Y-m-d\TH:i', strtotime($exam['live_start_date'])) : ''; ?>">
                                </div>
                                <div>
                                    <label class="form-label">LIVE END DATE (OPTIONAL)</label>
                                    <input type="datetime-local" name="live_end_date" class="custom-input" value="<?php echo $exam['live_end_date'] ? date('Y-m-d\TH:i', strtotime($exam['live_end_date'])) : ''; ?>">
                                </div>
                            </div>
                            
                            <div>
                                <label class="form-label">PRACTICE RELEASE DATE (OPTIONAL)</label>
                                <input type="datetime-local" name="practice_date" class="custom-input" value="<?php echo $exam['practice_date'] ? date('Y-m-d\TH:i', strtotime($exam['practice_date'])) : ''; ?>">
                                <div class="text-[10px] text-gray-500 mt-1 uppercase tracking-wider">When practice mode opens (or live exam transitions to practice)</div>
                            </div>
                            
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div>
                                    <label class="form-label">DURATION (MINUTES)</label>
                                    <input type="number" name="duration" class="custom-input" value="<?php echo $exam['duration']; ?>" required>
                                </div>
                                <div>
                                    <label class="form-label">MAX ATTEMPTS</label>
                                    <input type="number" name="max_attempts" class="custom-input" value="<?php echo isset($exam['max_attempts']) ? $exam['max_attempts'] : 1; ?>" required min="1">
                                </div>
                            </div>
                            
                            <div>
                                <label class="form-label">NEGATIVE MARKING</label>
                                <input type="number" step="0.01" name="negative_marks" class="custom-input" value="<?php echo isset($exam['negative_marks']) ? $exam['negative_marks'] : 0; ?>">
                            </div>
                            
                            <div>
                                <label class="form-label">EXAM PASSCODE (OPTIONAL)</label>
                                <input type="text" name="exam_passcode" class="custom-input" placeholder="Leave blank for no passcode protection" value="<?php echo htmlspecialchars($exam['passcode'] ?? ''); ?>">
                            </div>
                            
                            <div class="pt-4">
                                <button type="submit" name="save_settings" class="save-btn flex items-center gap-2">
                                    <i class="bi bi-save"></i> SAVE SETTINGS
                                </button>
                            </div>
                        </div>
                    </form>
                <?php elseif ($tab === 'questions'): ?>
                    
                    <?php 
                    $edit_q = null;
                    if (isset($_GET['edit_q_id'])) {
                        $st = $pdo->prepare("SELECT * FROM questions WHERE id = ? AND exam_id = ?");
                        $st->execute([(int)$_GET['edit_q_id'], $exam_id]);
                        $edit_q = $st->fetch(PDO::FETCH_ASSOC);
                    }
                    ?>
                    
                    <div class="mb-8" id="qform">
                        <div class="flex justify-between items-center mb-4">
                            <label class="form-label mb-0"><?php echo $edit_q ? 'EDIT QUESTION' : 'ADD NEW QUESTION'; ?></label>
                            <?php if ($edit_q): ?>
                                <a href="?id=<?php echo $exam_id; ?>&tab=questions" class="text-xs font-bold text-blue-600 hover:underline">CANCEL EDIT</a>
                            <?php endif; ?>
                        </div>
                        <form method="POST" enctype="multipart/form-data">
                            <?php if ($edit_q): ?>
                                <input type="hidden" name="question_id" value="<?php echo $edit_q['id']; ?>">
                            <?php endif; ?>
                            <div class="space-y-6">
                                <div>
                                    <div class="flex items-center justify-between mb-2">
                                        <label class="form-label mb-0">QUESTION TEXT</label>
                                        <div class="text-xs bg-indigo-50 border border-indigo-200 text-indigo-700 px-2 py-1 rounded font-bold shadow-sm inline-flex items-center gap-1">
                                            <i class="bi bi-arrows-angle-expand"></i> Images can be resized by clicking on them!
                                        </div>
                                    </div>
                                    <div id="quill-qtext" style="background: white; color: black; min-height: 200px; border-radius: 4px; font-size: 16px;">
                                        <?php echo $edit_q ? $edit_q['question_text'] : ''; ?>
                                    </div>
                                    <textarea name="question_text" id="hidden_qtext" style="display:none;"></textarea>
                                </div>
                                
                                <div class="bg-blue-50 p-4 rounded border border-blue-100">
                                    <label class="form-label flex items-center gap-2 text-blue-800">
                                        <i class="bi bi-image"></i> OR UPLOAD QUESTION IMAGE (OPTIONAL)
                                    </label>
                                    <?php if($edit_q && $edit_q['image_url']): ?>
                                        <div class="mb-2"><img src="<?php echo htmlspecialchars($edit_q['image_url']); ?>" style="max-height: 150px; width: auto; object-fit: contain;"></div>
                                    <?php endif; ?>
                                    <input type="file" name="question_image" id="question_image" accept="image/*" class="text-sm text-gray-600 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-white file:text-blue-700 hover:file:bg-blue-100 cursor-pointer">
                                </div>
                                
                                <div>
                                    <div class="flex items-center justify-between mb-3">
                                        <label class="form-label mb-0">OPTIONS (Select the correct one)</label>
                                        <div class="text-xs bg-indigo-50 border border-indigo-200 text-indigo-700 px-2 py-1 rounded font-bold shadow-sm inline-flex items-center gap-1">
                                            <i class="bi bi-ui-checks"></i> Single line option text
                                        </div>
                                    </div>
                                    <div class="radio-wrapper mb-[15px]">
                                        <input type="radio" name="correct" id="opt_correct_A" value="A" class="radio-custom" <?php echo ($edit_q && $edit_q['correct_opt'] === 'A') ? 'checked' : ''; ?> required>
                                        <span class="ml-2 font-bold text-gray-700 mr-2">A.</span>
                                        <input type="text" name="opt_a" id="opt_a" class="custom-input" placeholder="Option A text" value="<?php echo htmlspecialchars($edit_q['opt_a'] ?? ''); ?>" required>
                                    </div>
                                    <div class="radio-wrapper mb-[15px]">
                                        <input type="radio" name="correct" id="opt_correct_B" value="B" class="radio-custom" <?php echo ($edit_q && $edit_q['correct_opt'] === 'B') ? 'checked' : ''; ?>>
                                        <span class="ml-2 font-bold text-gray-700 mr-2">B.</span>
                                        <input type="text" name="opt_b" id="opt_b" class="custom-input" placeholder="Option B text" value="<?php echo htmlspecialchars($edit_q['opt_b'] ?? ''); ?>" required>
                                    </div>
                                    <div class="radio-wrapper mb-[15px]">
                                        <input type="radio" name="correct" id="opt_correct_C" value="C" class="radio-custom" <?php echo ($edit_q && $edit_q['correct_opt'] === 'C') ? 'checked' : ''; ?>>
                                        <span class="ml-2 font-bold text-gray-700 mr-2">C.</span>
                                        <input type="text" name="opt_c" id="opt_c" class="custom-input" placeholder="Option C text" value="<?php echo htmlspecialchars($edit_q['opt_c'] ?? ''); ?>" required>
                                    </div>
                                    <div class="radio-wrapper mb-[15px]">
                                        <input type="radio" name="correct" id="opt_correct_D" value="D" class="radio-custom" <?php echo ($edit_q && $edit_q['correct_opt'] === 'D') ? 'checked' : ''; ?>>
                                        <span class="ml-2 font-bold text-gray-700 mr-2">D.</span>
                                        <input type="text" name="opt_d" id="opt_d" class="custom-input" placeholder="Option D text" value="<?php echo htmlspecialchars($edit_q['opt_d'] ?? ''); ?>" required>
                                    </div>
                                </div>
                                
                                <div>
                                    <div class="flex items-center justify-between mb-2">
                                        <label class="form-label mb-0">EXPLANATION (SHOWN IN RESULTS)</label>
                                    </div>
                                    <textarea name="explanation" id="explanation" rows="3" class="custom-input" style="resize: vertical;"><?php echo $edit_q ? htmlspecialchars($edit_q['explanation']) : ''; ?></textarea>
                                </div>
                                
                                <div class="bg-blue-50 p-4 rounded border border-blue-100">
                                    <label class="form-label flex items-center gap-2 text-blue-800">
                                        <i class="bi bi-image"></i> OR UPLOAD EXPLANATION IMAGE (OPTIONAL)
                                    </label>
                                    <?php if($edit_q && $edit_q['explanation_image_url']): ?>
                                        <div class="mb-2"><img src="<?php echo htmlspecialchars($edit_q['explanation_image_url']); ?>" style="max-height: 150px; width: auto; object-fit: contain;"></div>
                                    <?php endif; ?>
                                    <input type="file" name="explanation_image" accept="image/*" class="text-sm text-gray-600 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-white file:text-blue-700 hover:file:bg-blue-100 cursor-pointer">
                                </div>
                                
                                <div class="pt-2 flex flex-wrap gap-3">
                                    <?php if ($edit_q): ?>
                                        <input type="hidden" name="edit_question" value="1">
                                        <button type="submit" class="save-btn flex items-center gap-2 bg-green-600 hover:bg-green-700">
                                            <i class="bi bi-save"></i> UPDATE QUESTION
                                        </button>
                                    <?php else: ?>
                                        <input type="hidden" name="add_question" value="1">
                                        <button type="submit" class="save-btn flex items-center gap-2">
                                            <i class="bi bi-plus-lg"></i> ADD QUESTION
                                        </button>
                                        <?php if (isset($_SESSION['copied_question'])): ?>
                                            <button type="button" onclick="pasteCopiedQuestion()" class="save-btn flex items-center gap-2 !bg-indigo-600 hover:!bg-indigo-700 no-underline text-white" title="Paste Copied Question">
                                                <i class="bi bi-clipboard"></i> PASTE QUESTION
                                            </button>
                                        <?php else: ?>
                                            <button type="button" class="save-btn flex items-center gap-2 !bg-gray-400 cursor-not-allowed opacity-70" title="First copy a question using the copy icon below" onclick="alert('Please copy a question first using the copy icon next to a question.')">
                                                <i class="bi bi-clipboard"></i> PASTE QUESTION
                                            </button>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </form>
                    </div>

                    <div class="border-t border-gray-200 pt-8 mt-8">
                        <label class="form-label mb-4">EXISTING QUESTIONS (<?php echo count($questions); ?>)</label>
                        <div class="space-y-4">
                            <?php foreach($questions as $i => $q): ?>
                                <div class="bg-gray-50 p-4 rounded-lg flex justify-between items-start border border-gray-200">
                                    <div class="overflow-hidden w-full px-2">
                                        <span class="text-gray-500 font-bold mr-2">Q<?php echo $i+1; ?>.</span>
                                        <div class="text-gray-900 inline-block align-top prose max-w-none">
                                            <?php 
                                            // Make sure images max out properly without losing aspect ratio
                                            echo str_replace('<img', '<img style="max-width:100%; height:auto; display:inline-block;"', $q['question_text']); 
                                            ?>
                                        </div>
                                    </div>
                                    <div class="flex gap-2 shrink-0">
                                        <button type="button" class="text-blue-500 hover:text-blue-700 transition" onclick="window.location='admin_edit_exam.php?id=<?php echo $exam_id; ?>&edit_q_id=<?php echo $q['id']; ?>&tab=questions#qform'" title="Edit Question"><i class="bi bi-pencil"></i></button>
                                        <button type="button" class="text-indigo-500 hover:text-indigo-700 font-medium transition text-sm flex items-center border border-indigo-200 px-2 rounded bg-indigo-50" onclick="window.location='admin_edit_exam.php?id=<?php echo $exam_id; ?>&copy_q=<?php echo $q['id']; ?>&tab=questions'"><i class="bi bi-copy mr-1"></i> Copy</button>
                                        <button type="button" class="text-red-400 hover:text-red-600 transition ml-1" onclick="if(confirm('Delete?')) window.location='admin_edit_exam.php?id=<?php echo $exam_id; ?>&delete_q=<?php echo $q['id']; ?>&tab=questions'" title="Delete Question"><i class="bi bi-trash"></i></button>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                            <?php if (empty($questions)): ?>
                                <div class="text-gray-500 italic text-sm">No questions added yet.</div>
                            <?php endif; ?>
                        </div>
                    </div>

                <?php elseif ($tab === 'results'): ?>
                    <?php
                        echo "<script>window.location='admin_results.php?exam_id=$exam_id';</script>";
                    ?>
                <?php endif; ?>

            </div>
        </main>
    </div>
</div>

<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
<!-- KaTeX for Math Equations (Word-like math support) -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css">
<script src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js"></script>

<style>
    /* Quill Custom Font Sizes CSS */
    <?php
    $font_sizes = [12, 14, 16, 18, 20, 24, 28, 32, 36];
    foreach($font_sizes as $s) {
        echo ".ql-snow .ql-picker.ql-size .ql-picker-label[data-value='{$s}px']::before,";
        echo ".ql-snow .ql-picker.ql-size .ql-picker-item[data-value='{$s}px']::before { content: '{$s}px'; }\n";
    }
    ?>
    .ql-snow .ql-picker.ql-size .ql-picker-label::before, 
    .ql-snow .ql-picker.ql-size .ql-picker-item::before { content: '16px'; }
    
    .ql-snow .ql-picker.ql-size { width: 75px; }
    .ql-snow .ql-picker.ql-size .ql-picker-options { max-height: 250px; overflow-y: auto; }

    /* Make quill resize vertical possible via wrapper */
    .ql-container {
        resize: vertical;
        overflow-y: auto;
    }

    /* Prevent image stretching in the editor */
    .ql-editor img {
        max-width: 100%; 
    }

    /* Math rendering improvements */
    .katex {
        font-size: 1.3em !important;
        color: #000000 !important;
        text-shadow: 0 0 1px rgba(0,0,0,0.1); /* Adds slight weight to the text */
    }
    .ql-formula {
        background: transparent !important;
        cursor: pointer;
        display: inline-block;
    }
</style>
<script src="https://cdn.quilljs.com/1.3.6/quill.min.js"></script>
<!-- Image resize requirement -->
<script>window.Quill = Quill;</script>
<script src="https://cdn.jsdelivr.net/npm/quill-image-resize-module@3.0.0/image-resize.min.js"></script>
<!-- MathLive for MS Word like visual math editing -->
<script defer src="https://unpkg.com/mathlive"></script>

<!-- Math Editor Modal -->
<div id="mathModal" class="hidden fixed inset-0 z-[100] bg-black bg-opacity-50 flex justify-center items-center backdrop-blur-sm">
    <div class="bg-white rounded-xl p-6 w-[95%] max-w-4xl shadow-2xl transform transition-all border border-gray-100">
        <div class="flex justify-between items-center mb-4 pb-3 border-b border-gray-100">
            <h3 class="text-xl font-extrabold text-gray-800 flex items-center gap-2">
                <span class="bg-indigo-100 text-indigo-600 p-2 rounded-lg leading-none"><i class="bi bi-calculator"></i></span>
                Visual Math Equation Editor
            </h3>
            <button type="button" onclick="closeMathModal()" class="text-gray-400 hover:text-red-500 text-3xl transition leading-none">&times;</button>
        </div>
        
        <div class="mb-5 border-2 border-indigo-200 rounded-xl p-2 bg-indigo-50/50 shadow-inner">
            <math-field id="mf" style="width: 100%; font-size: 32px; min-height: 150px; outline: none; background: white; padding: 15px; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.05);"></math-field>
        </div>
        
        <div class="flex items-center justify-between">
            <div class="text-xs text-gray-500 flex items-center gap-2 max-w-sm">
                <i class="bi bi-keyboard text-lg text-indigo-400"></i>
                <span>Type naturally like MS Word. Use <kbd class="bg-gray-100 border border-gray-300 rounded px-1">/</kbd> for fractions, <kbd class="bg-gray-100 border border-gray-300 rounded px-1">^</kbd> for exponents, or virtual keyboard!</span>
            </div>
            <div class="flex gap-3">
                <button type="button" onclick="closeMathModal()" class="px-5 py-2.5 border border-gray-300 rounded-lg text-gray-700 bg-white hover:bg-gray-50 font-medium transition shadow-sm">Cancel</button>
                <button type="button" onclick="insertMath()" class="px-6 py-2.5 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 font-bold transition shadow-md flex items-center gap-2">
                    <i class="bi bi-check-circle-fill"></i> Save Equation
                </button>
            </div>
        </div>
    </div>
</div>

<script>
    let currentMathNode = null;

    function openMathModal(existingLatex = '', node = null) {
        currentMathNode = node;
        document.getElementById('mathModal').classList.remove('hidden');
        const mf = document.getElementById('mf');
        // Prevent MathLive focus behavior from scrolling weirdly
        setTimeout(() => {
            mf.value = existingLatex;
            mf.focus();
        }, 100);
    }

    function closeMathModal() {
        document.getElementById('mathModal').classList.add('hidden');
        currentMathNode = null;
        document.getElementById('mf').value = '';
    }

    function insertMath() {
        if(typeof quillq === 'undefined') return closeMathModal();
        
        const mf = document.getElementById('mf');
        const latex = mf.value;
        if (!latex) {
            return closeMathModal();
        }

        if (currentMathNode) {
            // Editing existing formula
            let blot = Quill.find(currentMathNode);
            if (blot) {
                let index = quillq.getIndex(blot);
                quillq.deleteText(index, 1);
                quillq.insertEmbed(index, 'formula', latex);
            }
        } else {
            // Inserting new formula
            let range = quillq.getSelection(true);
            if (range) {
                quillq.insertEmbed(range.index, 'formula', latex);
                quillq.setSelection(range.index + 1);
            }
        }
        closeMathModal();
    }

    if (document.getElementById('quill-qtext')) {
        var Size = Quill.import('attributors/style/size');
        var sizes = ['12px', '14px', '16px', '18px', '20px', '24px', '28px', '32px', '36px'];
        Size.whitelist = sizes;
        Quill.register(Size, true);

        var quillq = new Quill('#quill-qtext', {
            theme: 'snow',
            modules: {
                formula: true, // Enables MS Word-like Math equation tool
                imageResize: {
                    displaySize: true
                },
                toolbar: [
                    [{ 'size': sizes }],
                    ['bold', 'italic', 'underline', 'strike'],
                    [{ 'script': 'sub'}, { 'script': 'super' }], // Super/Sub script for simple formulas
                    [{ 'color': [] }, { 'background': [] }],
                    [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                    ['link', 'image', 'video', 'formula'], // Formula button added
                    ['clean']
                ]
            }
        });

        // Override the default formula button handler to show MathLive modal
        quillq.getModule('toolbar').addHandler('formula', function() {
            openMathModal();
        });

        // Make existing equations editable on click
        quillq.root.addEventListener('click', function(e) {
            let formulaNode = e.target.closest('.ql-formula');
            if (formulaNode) {
                let latex = formulaNode.getAttribute('data-value');
                openMathModal(latex, formulaNode);
            }
        });

        const form = document.querySelector('form[enctype="multipart/form-data"]') || document.querySelector('form');
        if(form && document.getElementById('hidden_qtext')) {
            form.addEventListener('submit', function(e) {
                var html = quillq.root.innerHTML;
                if (html === '<p><br></p>') html = '';
                document.getElementById('hidden_qtext').value = html;
            });
        }
    }
    function pasteCopiedQuestion() {
        <?php if(isset($_SESSION['copied_question'])): $c_q = $_SESSION['copied_question']; ?>
        if(typeof quillq !== 'undefined') {
            quillq.root.innerHTML = <?php echo json_encode($c_q['question_text']); ?>;
        } else {
            document.getElementById('hidden_qtext').value = <?php echo json_encode($c_q['question_text']); ?>;
        }
        document.querySelector('input[name="opt_a"]').value = <?php echo json_encode($c_q['opt_a']); ?>;
        document.querySelector('input[name="opt_b"]').value = <?php echo json_encode($c_q['opt_b']); ?>;
        document.querySelector('input[name="opt_c"]').value = <?php echo json_encode($c_q['opt_c']); ?>;
        document.querySelector('input[name="opt_d"]').value = <?php echo json_encode($c_q['opt_d']); ?>;
        if(document.querySelector('input[name="correct"][value="' + <?php echo json_encode($c_q['correct_opt']); ?> + '"]')) {
            document.querySelector('input[name="correct"][value="' + <?php echo json_encode($c_q['correct_opt']); ?> + '"]').checked = true;
        }
        document.querySelector('textarea[name="explanation"]').value = <?php echo json_encode($c_q['explanation'] ?? ''); ?>;
        <?php endif; ?>
        
        document.getElementById('qform').scrollIntoView({behavior: 'smooth'});
    }
</script>

</body>
</html>
