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

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

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

if (isset($_POST['create_exam'])) {
    $title = trim($_POST['title']);
    $duration = (int)$_POST['duration'];
    $class_id = $_POST['class_id'];
    $subject_id = $_POST['subject_id'];
    $randomize = isset($_POST['randomize']) ? 1 : 0;
    $session = $_POST['session'] ?? null;
    $term = $_POST['term'] ?? null;
    $question_quota = isset($_POST['question_quota']) ? (int)$_POST['question_quota'] : null;
    $show_result = isset($_POST['show_result']) ? 1 : 0;
    $allowed_attempts = isset($_POST['allowed_attempts']) ? (int)$_POST['allowed_attempts'] : 1;
    $exam_type = ($_POST['exam_type'] ?? 'test') === 'exam' ? 'exam' : 'test';
    $total_score = isset($_POST['total_score']) ? (int)$_POST['total_score'] : ($exam_type === 'exam' ? 30 : 20);
    $start_at = !empty($_POST['start_at']) ? str_replace('T',' ', $_POST['start_at']) . (strlen($_POST['start_at'])==16?':00':'') : null;
    $end_at = !empty($_POST['end_at']) ? str_replace('T',' ', $_POST['end_at']) . (strlen($_POST['end_at'])==16?':00':'') : null;
    
    if (!empty($title) && $duration > 0 && !empty($class_id) && !empty($subject_id)) {
        $stmt = $pdo->prepare("INSERT INTO exams (title, duration, status, class_id, subject_id, randomize_questions, session, term, question_quota, show_result_to_student, allowed_attempts, exam_type, total_score, start_at, end_at) VALUES (?, ?, 'inactive', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        if ($stmt->execute([$title, $duration, $class_id, $subject_id, $randomize, $session, $term, $question_quota, $show_result, $allowed_attempts, $exam_type, $total_score, $start_at, $end_at])) {
            $message = "Exam created successfully. Now assign students.";
        } else {
            $error = "Failed to create exam.";
        }
    } else {
        $error = "Please fill all fields.";
    }
}

if (isset($_POST['update_exam'])) {
    $exam_id = (int)$_POST['exam_id'];
    $title = trim($_POST['title']);
    $class_id = $_POST['class_id'];
    $subject_id = $_POST['subject_id'];
    $session = $_POST['session'] ?? null;
    $term = $_POST['term'] ?? null;
    $exam_type = ($_POST['exam_type'] ?? 'test') === 'exam' ? 'exam' : 'test';
    $total_score = isset($_POST['total_score']) ? (int)$_POST['total_score'] : ($exam_type === 'exam' ? 30 : 20);
    $duration = (int)$_POST['duration'];
    $question_quota = isset($_POST['question_quota']) ? (int)$_POST['question_quota'] : null;
    $allowed_attempts = isset($_POST['allowed_attempts']) ? (int)$_POST['allowed_attempts'] : 1;
    $randomize = isset($_POST['randomize']) ? 1 : 0;
    $show_result = isset($_POST['show_result']) ? 1 : 0;
    $start_at = !empty($_POST['start_at']) ? str_replace('T',' ', $_POST['start_at']) . (strlen($_POST['start_at'])==16?':00':'') : null;
    $end_at = !empty($_POST['end_at']) ? str_replace('T',' ', $_POST['end_at']) . (strlen($_POST['end_at'])==16?':00':'') : null;

    if ($exam_id && !empty($title) && $duration > 0 && !empty($class_id) && !empty($subject_id)) {
        $stmt = $pdo->prepare("
            UPDATE exams 
            SET title = ?, class_id = ?, subject_id = ?, session = ?, term = ?, 
                exam_type = ?, total_score = ?, duration = ?, question_quota = ?, 
                allowed_attempts = ?, randomize_questions = ?, show_result_to_student = ?,
                start_at = ?, end_at = ?
            WHERE exam_id = ?
        ");
        if ($stmt->execute([$title, $class_id, $subject_id, $session, $term, $exam_type, $total_score, $duration, $question_quota, $allowed_attempts, $randomize, $show_result, $start_at, $end_at, $exam_id])) {
            $message = "Exam updated.";
        } else {
            $error = "Failed to update exam.";
        }
    } else {
        $error = "Please fill all fields.";
    }
}
if (isset($_POST['toggle_status'])) {
    $exam_id = $_POST['exam_id'];
    $current_status = $_POST['current_status'];
    $new_status = ($current_status == 'active') ? 'inactive' : 'active';
    
    $stmt = $pdo->prepare("UPDATE exams SET status = ? WHERE exam_id = ?");
    $stmt->execute([$new_status, $exam_id]);
    $message = "Exam status updated.";
}

if (isset($_POST['delete_exam'])) {
    $pdo->prepare("DELETE FROM exams WHERE exam_id = ?")->execute([$_POST['exam_id']]);
    $message = "Exam deleted.";
}

if (isset($_POST['assign_class_students'])) {
    $exam_id = (int)($_POST['exam_id'] ?? 0);
    $class_id = (int)($_POST['class_id'] ?? 0);
    if ($exam_id && $class_id) {
        $pdo->prepare("DELETE FROM exam_assignments WHERE exam_id = ?")->execute([$exam_id]);
        $stmtSt = $pdo->prepare("SELECT user_id FROM users WHERE role = 'student' AND class_id = ? ORDER BY user_id ASC");
        $stmtSt->execute([$class_id]);
        $ids = $stmtSt->fetchAll(PDO::FETCH_COLUMN);
        $count = 0;
        if (!empty($ids)) {
            $ins = $pdo->prepare("INSERT INTO exam_assignments (exam_id, user_id) VALUES (?, ?)");
            foreach ($ids as $uid) {
                $ins->execute([$exam_id, $uid]);
                $count++;
            }
        }
        $message = "Assigned $count students from selected class.";
    } else {
        $error = "Please select a class.";
    }
}

// Generate per-student timetable within exam schedule
if (isset($_POST['generate_timetable'])) {
    $exam_id = (int)($_POST['exam_id'] ?? 0);
    if ($exam_id) {
        $stmtE = $pdo->prepare("SELECT start_at, end_at, duration FROM exams WHERE exam_id = ?");
        $stmtE->execute([$exam_id]);
        $ex = $stmtE->fetch();
        if (!$ex || empty($ex['start_at']) || empty($ex['end_at'])) {
            $error = "Please set Start and End date/time on the exam before generating timetable.";
        } else {
            $start = new DateTime($ex['start_at']);
            $end = new DateTime($ex['end_at']);
            $durationMin = (int)$ex['duration'];
            $windowMinutes = max(0, (int)(($end->getTimestamp() - $start->getTimestamp()) / 60) - $durationMin);
            $stmtSt = $pdo->prepare("SELECT user_id FROM exam_assignments WHERE exam_id = ? ORDER BY user_id ASC");
            $stmtSt->execute([$exam_id]);
            $students = $stmtSt->fetchAll(PDO::FETCH_COLUMN);
            if (empty($students)) {
                $error = "No students assigned to this exam.";
            } else {
                // Shuffle students for randomness
                shuffle($students);
                $n = count($students);
                $step = $n > 0 ? max(1, (int)floor($windowMinutes / max(1, $n))) : 1;
                $ins = $pdo->prepare("
                    INSERT INTO student_exam_schedule (exam_id, user_id, slot_start, slot_end)
                    VALUES (?, ?, ?, ?)
                    ON DUPLICATE KEY UPDATE slot_start = VALUES(slot_start), slot_end = VALUES(slot_end)
                ");
                $count = 0;
                foreach ($students as $i => $uid) {
                    $offsetMin = min($windowMinutes, $i * $step + rand(0, min(10, $step)));
                    $slotStart = (clone $start)->modify('+' . $offsetMin . ' minutes');
                    $slotEnd = (clone $slotStart)->modify('+' . $durationMin . ' minutes');
                    $ins->execute([$exam_id, $uid, $slotStart->format('Y-m-d H:i:s'), $slotEnd->format('Y-m-d H:i:s')]);
                    $count++;
                }
                $message = "Generated timetable slots for $count students.";
            }
        }
    } else {
        $error = "Invalid exam id.";
    }
}
// Fetch Lists
$classes = $pdo->query("SELECT * FROM classes")->fetchAll();
$subjects = $pdo->query("SELECT * FROM subjects")->fetchAll();

// Pagination
$per_page = 20;
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $per_page;
$total = (int)$pdo->query("SELECT COUNT(*) FROM exams")->fetchColumn();
$total_pages = max(1, (int)ceil($total / $per_page));

$stmtExams = $pdo->prepare("
    SELECT e.*, c.class_name, s.name as subject_name
    FROM exams e
    LEFT JOIN classes c ON e.class_id = c.class_id
    LEFT JOIN subjects s ON e.subject_id = s.subject_id
    ORDER BY e.exam_id DESC
    LIMIT $per_page OFFSET $offset
");
$stmtExams->execute();
$exams = $stmtExams->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exam Control</title>
    <link rel="stylesheet" href="../assets/css/admin.css">
</head>
<body>
    <?php include '../includes/admin_sidebar.php'; ?>
    <div class="content">
        <?php include '../includes/page_header.php'; ?>
        <h1>Exam Control</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 collapsible fade-in" id="createExamCard">
            <div class="card-header">
                <div>
                    <h3 style="margin: 0; color: var(--primary-color);">Create New Exam</h3>
                    <p style="margin: 4px 0 0; color: var(--secondary-color); font-size: 0.9em;">Configure exam details, duration, and access controls.</p>
                </div>
                <span class="chev" id="createToggle">▾</span>
            </div>
            <div class="card-body">
            <form method="POST" class="exam-form">
                <div class="form-group">
                    <label>Exam Title</label>
                    <input type="text" name="title" placeholder="e.g., 1st Term Mathematics Exam" required class="form-control">
                </div>

                <div class="form-grid">
                    <div class="form-group">
                        <label>Class</label>
                        <select name="class_id" required class="form-control">
                            <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>Subject</label>
                        <select name="subject_id" required class="form-control">
                            <option value="">Select Subject</option>
                            <?php foreach ($subjects as $s): ?>
                                <option value="<?php echo $s['subject_id']; ?>"><?php echo $s['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="">Select Session</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="">Select Term</option>
                            <?php foreach ($terms as $t): ?>
                                <option value="<?php echo $t; ?>"><?php echo $t; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div class="form-grid">
                    <div class="form-group">
                        <label>Type</label>
                        <select name="exam_type" class="form-control" id="examType">
                            <option value="test">Test</option>
                            <option value="exam">Exam</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Total Score</label>
                        <input type="number" name="total_score" id="totalScore" placeholder="Default: 20 for Test, 30 for Exam" min="1" value="20" class="form-control">
                    </div>
                </div>

                <div class="form-grid">
                    <div class="form-group">
                        <label>Start Date & Time</label>
                        <input type="datetime-local" name="start_at" class="form-control">
                    </div>
                    <div class="form-group">
                        <label>End Date & Time</label>
                        <input type="datetime-local" name="end_at" class="form-control">
                    </div>
                </div>

                <div class="form-grid">
                    <div class="form-group">
                        <label>Duration (Minutes)</label>
                        <input type="number" name="duration" placeholder="60" required class="form-control">
                    </div>
                    <div class="form-group">
                        <label>Question Quota (Optional)</label>
                        <input type="number" name="question_quota" placeholder="All" min="1" class="form-control">
                    </div>
                </div>

                <div class="form-grid">
                     <div class="form-group">
                        <label>Allowed Attempts</label>
                        <input type="number" name="allowed_attempts" placeholder="Default: 1" min="1" value="1" class="form-control">
                     </div>
                </div>

                <div class="form-options">
                    <label class="checkbox-container">
                        <input type="checkbox" name="randomize" value="1" checked>
                        <span class="checkmark"></span>
                        Randomize Questions
                    </label>
                    <label class="checkbox-container">
                        <input type="checkbox" name="show_result" value="1">
                        <span class="checkmark"></span>
                        Show Result to Student
                    </label>
                </div>

                <button type="submit" name="create_exam" class="btn btn-primary btn-block" style="margin-top: 20px; height: 45px; font-size: 16px;">
                    Create Exam
                </button>
            </form>
            </div>
        </div>
        <div class="card fade-in">
        <div class="table-responsive">
        <table>
            <thead>
                <tr>
                    <th>Title</th>
                    <th>Type</th>
                    <th>Total</th>
                    <th>Class</th>
                    <th>Subject</th>
                    <th>Duration</th>
                    <th>Status</th>
                    <th>Schedule</th>
                    <th>Session/Term</th>
                    <th>Quota</th>
                    <th>Show Result</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($exams as $e): ?>
                <tr>
                    <td><?php echo htmlspecialchars($e['title']); ?></td>
                    <td><?php echo htmlspecialchars($e['exam_type'] ?? 'test'); ?></td>
                    <td><?php echo (int)($e['total_score'] ?? 20); ?></td>
                    <td><?php echo htmlspecialchars($e['class_name'] ?? 'All'); ?></td>
                    <td><?php echo htmlspecialchars($e['subject_name'] ?? 'None'); ?></td>
                    <td><?php echo $e['duration']; ?> min</td>
                    <td>
                        <span style="color: <?php echo $e['status'] == 'active' ? 'green' : 'red'; ?>; font-weight: bold;">
                            <?php echo strtoupper($e['status']); ?>
                        </span>
                    </td>
                    <td>
                        <?php
                        $now = new DateTime();
                        $start = !empty($e['start_at']) ? new DateTime($e['start_at']) : null;
                        $end = !empty($e['end_at']) ? new DateTime($e['end_at']) : null;
                        $state = '-';
                        if ($start || $end) {
                            if ($start && $now < $start) $state = 'Scheduled';
                            elseif ($end && $now > $end) $state = 'Closed';
                            else $state = 'Live';
                        }
                        echo $state;
                        ?>
                    </td>
                    <td><?php echo ($e['session'] ?: '-') . ' / ' . ($e['term'] ?: '-'); ?></td>
                    <td><?php echo $e['question_quota'] ?: '-'; ?></td>
                    <td><?php echo ($e['show_result_to_student'] ? 'Yes' : 'No'); ?></td>
                    <td>
                        <a href="preview_exam.php?exam_id=<?php echo $e['exam_id']; ?>" target="_blank" class="btn">Preview</a>
                        <button type="button"
                                class="btn btn-primary"
                                onclick="openManageExamModal(<?php echo $e['exam_id']; ?>)"
                                data-eid="<?php echo $e['exam_id']; ?>"
                                data-exam='<?php echo json_encode([
                                    'exam_id' => $e['exam_id'],
                                    'title' => $e['title'],
                                    'class_id' => $e['class_id'],
                                    'subject_id' => $e['subject_id'],
                                    'session' => $e['session'],
                                    'term' => $e['term'],
                                    'duration' => $e['duration'],
                                    'question_quota' => $e['question_quota'],
                                    'allowed_attempts' => $e['allowed_attempts'],
                                    'randomize_questions' => $e['randomize_questions'],
                                    'show_result_to_student' => $e['show_result_to_student'],
                                    'exam_type' => $e['exam_type'],
                                    'total_score' => $e['total_score'],
                                    'start_at' => $e['start_at'],
                                    'end_at' => $e['end_at'],
                                    'status' => $e['status']
                                ]); ?>'>
                            Manage
                        </button>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        </div>
        </div>
        
        <div style="margin-top:15px; display:flex; gap:8px; flex-wrap:wrap;">
            <?php
            for ($p=1; $p<=$total_pages; $p++) {
                $url = '?page=' . $p;
                $active = $p === $page;
                echo '<a href="'.$url.'" class="btn" style="background:'.($active?'#007bff':'#6c757d').';">'. $p .'</a>';
            }
            ?>
        </div>
        <div class="main-footer">
            &copy; 2026 Designed by FGV
        </div>
    </div>
    <div class="modal-backdrop" id="editExamBackdrop">
        <div class="modal">
            <header>Edit Exam</header>
            <form method="POST" id="editExamForm">
                <input type="hidden" name="exam_id" id="edit_exam_id">
                <div class="form-group">
                    <label>Title</label>
                    <input type="text" name="title" id="edit_title" class="form-control" required>
                </div>
                <div class="form-grid">
                    <div class="form-group">
                        <label>Class</label>
                        <select name="class_id" id="edit_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>Subject</label>
                        <select name="subject_id" id="edit_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']; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="form-grid">
                    <div class="form-group">
                        <label>Session</label>
                        <select name="session" id="edit_session" class="form-control">
                            <option value="">Select Session</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" id="edit_term" class="form-control">
                            <option value="">Select Term</option>
                            <?php foreach ($terms as $t): ?>
                                <option value="<?php echo $t; ?>"><?php echo $t; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="form-grid">
                    <div class="form-group">
                        <label>Type</label>
                        <select name="exam_type" id="edit_exam_type" class="form-control">
                            <option value="test">Test</option>
                            <option value="exam">Exam</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Total Score</label>
                        <input type="number" name="total_score" id="edit_total_score" class="form-control" min="1">
                    </div>
                </div>
                <div class="form-grid">
                    <div class="form-group">
                        <label>Start Date & Time</label>
                        <input type="datetime-local" name="start_at" id="edit_start_at" class="form-control">
                    </div>
                    <div class="form-group">
                        <label>End Date & Time</label>
                        <input type="datetime-local" name="end_at" id="edit_end_at" class="form-control">
                    </div>
                </div>
                <div class="form-grid">
                    <div class="form-group">
                        <label>Duration (Minutes)</label>
                        <input type="number" name="duration" id="edit_duration" class="form-control" min="1" required>
                    </div>
                    <div class="form-group">
                        <label>Question Quota</label>
                        <input type="number" name="question_quota" id="edit_question_quota" class="form-control" min="1">
                    </div>
                </div>
                <div class="form-grid">
                    <div class="form-group">
                        <label>Allowed Attempts</label>
                        <input type="number" name="allowed_attempts" id="edit_allowed_attempts" class="form-control" min="1" required>
                    </div>
                </div>
                <div class="form-options">
                    <label class="checkbox-container">
                        <input type="checkbox" name="randomize" id="edit_randomize" value="1">
                        <span class="checkmark"></span>
                        Randomize Questions
                    </label>
                    <label class="checkbox-container">
                        <input type="checkbox" name="show_result" id="edit_show_result" value="1">
                        <span class="checkmark"></span>
                        Show Result to Student
                    </label>
                </div>
                <div class="actions">
                    <button type="button" class="btn" onclick="closeEditExamModal()">Cancel</button>
                    <button type="submit" name="update_exam" class="btn btn-primary">Save Changes</button>
                </div>
            </form>
        </div>
    </div>
    <div class="modal-backdrop" id="assignBackdrop">
        <div class="modal">
            <header>Assign Students</header>
            <form method="POST" id="assignForm">
                <input type="hidden" name="exam_id" id="assign_exam_id">
                <div class="form-group">
                    <label>Select Class</label>
                    <select name="class_id" id="assign_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="actions">
                    <button type="button" class="btn" onclick="closeAssignModal()">Cancel</button>
                    <button type="submit" name="assign_class_students" class="btn btn-primary">Assign Whole Class</button>
                </div>
            </form>
        </div>
    </div>
    <div class="modal-backdrop" id="generateBackdrop">
        <div class="modal">
            <header>Generate Timetable</header>
            <form method="POST" id="generateForm">
                <input type="hidden" name="exam_id" id="generate_exam_id">
                <p style="color:#475569;">This will distribute unique start times for all assigned students within the exam's Start and End. Students can start up to 15 minutes after their slot.</p>
                <div class="actions">
                    <button type="button" class="btn" onclick="closeGenerateModal()">Cancel</button>
                    <button type="submit" name="generate_timetable" class="btn btn-primary">Generate</button>
                </div>
            </form>
        </div>
    </div>
    <div class="modal-backdrop" id="manageBackdrop">
        <div class="modal">
            <header>Manage Exam</header>
            <div class="tab-nav">
                <div class="tab active" data-tab="overview">Overview</div>
                <div class="tab" data-tab="assign">Assign</div>
                <div class="tab" data-tab="schedule">Schedule</div>
                <div class="tab" data-tab="danger">Danger</div>
            </div>
            <div class="tab-panel active" id="tab-overview">
                <form method="POST" id="manageUpdateForm">
                    <input type="hidden" name="exam_id" id="m_exam_id">
                    <div class="form-group">
                        <label>Title</label>
                        <input type="text" name="title" id="m_title" class="form-control" required>
                    </div>
                    <div class="form-grid">
                        <div class="form-group">
                            <label>Class</label>
                            <select name="class_id" id="m_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>Subject</label>
                            <select name="subject_id" id="m_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']; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="form-grid">
                        <div class="form-group">
                            <label>Session</label>
                            <select name="session" id="m_session" class="form-control">
                                <option value="">Select Session</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" id="m_term" class="form-control">
                                <option value="">Select Term</option>
                                <?php foreach ($terms as $t): ?>
                                    <option value="<?php echo $t; ?>"><?php echo $t; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="form-grid">
                        <div class="form-group">
                            <label>Type</label>
                            <select name="exam_type" id="m_exam_type" class="form-control">
                                <option value="test">Test</option>
                                <option value="exam">Exam</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Total Score</label>
                            <input type="number" name="total_score" id="m_total_score" class="form-control" min="1">
                        </div>
                    </div>
                    <div class="form-grid">
                        <div class="form-group">
                            <label>Start Date & Time</label>
                            <input type="datetime-local" name="start_at" id="m_start_at" class="form-control">
                        </div>
                        <div class="form-group">
                            <label>End Date & Time</label>
                            <input type="datetime-local" name="end_at" id="m_end_at" class="form-control">
                        </div>
                    </div>
                    <div class="form-grid">
                        <div class="form-group">
                            <label>Duration (Minutes)</label>
                            <input type="number" name="duration" id="m_duration" class="form-control" min="1" required>
                        </div>
                        <div class="form-group">
                            <label>Question Quota</label>
                            <input type="number" name="question_quota" id="m_question_quota" class="form-control" min="1">
                        </div>
                    </div>
                    <div class="form-grid">
                        <div class="form-group">
                            <label>Allowed Attempts</label>
                            <input type="number" name="allowed_attempts" id="m_allowed_attempts" class="form-control" min="1" required>
                        </div>
                    </div>
                    <div class="form-options">
                        <label class="checkbox-container">
                            <input type="checkbox" name="randomize" id="m_randomize" value="1">
                            <span class="checkmark"></span>
                            Randomize Questions
                        </label>
                        <label class="checkbox-container">
                            <input type="checkbox" name="show_result" id="m_show_result" value="1">
                            <span class="checkmark"></span>
                            Show Result to Student
                        </label>
                    </div>
                    <div class="actions">
                        <form method="POST" id="toggleForm" style="display:inline;">
                            <input type="hidden" name="exam_id" id="t_exam_id">
                            <input type="hidden" name="current_status" id="t_current_status">
                            <button type="submit" name="toggle_status" class="btn btn-warning" id="t_toggle_btn"></button>
                        </form>
                        <button type="submit" name="update_exam" class="btn btn-primary">Save Changes</button>
                    </div>
                </form>
            </div>
            <div class="tab-panel" id="tab-assign">
                <form method="POST" id="manageAssignForm">
                    <input type="hidden" name="exam_id" id="ma_exam_id">
                    <div class="form-group">
                        <label>Select Class</label>
                        <select name="class_id" id="ma_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="actions">
                        <button type="submit" name="assign_class_students" class="btn btn-primary">Assign Whole Class</button>
                    </div>
                </form>
            </div>
            <div class="tab-panel" id="tab-schedule">
                <form method="POST" id="manageGenerateForm">
                    <input type="hidden" name="exam_id" id="mg_exam_id">
                    <p style="color:#475569;">Generate unique start times for assigned students within the exam window. Students can start within 15 minutes of their slot.</p>
                    <div class="actions">
                        <button type="submit" name="generate_timetable" class="btn btn-primary">Generate Timetable</button>
                    </div>
                </form>
            </div>
            <div class="tab-panel" id="tab-danger">
                <form method="POST" id="manageDeleteForm" onsubmit="return confirm('Delete exam?');">
                    <input type="hidden" name="exam_id" id="md_exam_id">
                    <div class="actions">
                        <button type="submit" name="delete_exam" class="btn btn-danger">Delete Exam</button>
                    </div>
                </form>
            </div>
            <div class="actions">
                <button type="button" class="btn" onclick="closeManageExamModal()">Close</button>
            </div>
        </div>
    </div>
    <script>
        (function(){
            const typeSel = document.getElementById('examType');
            const totalInput = document.getElementById('totalScore');
            if (typeSel && totalInput) {
                const setDefault = () => {
                    if (typeSel.value === 'exam') {
                        if (!totalInput.value || totalInput.value == '20') totalInput.value = 30;
                    } else {
                        if (!totalInput.value || totalInput.value == '30') totalInput.value = 20;
                    }
                };
                typeSel.addEventListener('change', setDefault);
                setDefault();
            }
        })();
        (function(){
            const card = document.getElementById('createExamCard');
            const toggle = document.getElementById('createToggle');
            if (card && toggle) {
                toggle.addEventListener('click', function(){
                    card.classList.toggle('collapsed');
                    toggle.textContent = card.classList.contains('collapsed') ? '▸' : '▾';
                });
            }
        })();
        function openEditExamModal(id) {
            const btn = document.querySelector('button[data-eid="'+id+'"]');
            if (!btn) return;
            const data = JSON.parse(btn.getAttribute('data-exam'));
            const bd = document.getElementById('editExamBackdrop');
            if (!bd) return;
            document.getElementById('edit_exam_id').value = data.exam_id || '';
            document.getElementById('edit_title').value = data.title || '';
            document.getElementById('edit_class_id').value = data.class_id || '';
            document.getElementById('edit_subject_id').value = data.subject_id || '';
            document.getElementById('edit_session').value = data.session || '';
            document.getElementById('edit_term').value = data.term || '';
            document.getElementById('edit_exam_type').value = data.exam_type || 'test';
            document.getElementById('edit_total_score').value = data.total_score || (data.exam_type === 'exam' ? 30 : 20);
            document.getElementById('edit_duration').value = data.duration || '';
            document.getElementById('edit_question_quota').value = data.question_quota || '';
            document.getElementById('edit_allowed_attempts').value = data.allowed_attempts || 1;
            document.getElementById('edit_randomize').checked = !!data.randomize_questions;
            document.getElementById('edit_show_result').checked = !!data.show_result_to_student;
            // Set datetime-local values from SQL datetime (YYYY-MM-DD HH:MM:SS -> YYYY-MM-DDTHH:MM)
            const toLocal = (dt) => {
                if (!dt) return '';
                try {
                    const d = new Date(dt.replace(' ', 'T'));
                    const pad = n => String(n).padStart(2,'0');
                    return d.getFullYear() + '-' + pad(d.getMonth()+1) + '-' + pad(d.getDate()) + 'T' + pad(d.getHours()) + ':' + pad(d.getMinutes());
                } catch(e){ return ''; }
            };
            document.getElementById('edit_start_at').value = toLocal(data.start_at);
            document.getElementById('edit_end_at').value = toLocal(data.end_at);
            bd.classList.add('show');
            document.body.classList.add('modal-open');
        }
        function closeEditExamModal() {
            const bd = document.getElementById('editExamBackdrop');
            if (bd) bd.classList.remove('show');
            document.body.classList.remove('modal-open');
        }
        function openAssignModal(id) {
            const btn = document.querySelector('button[data-exam-id="'+id+'"]');
            if (!btn) return;
            const bd = document.getElementById('assignBackdrop');
            if (!bd) return;
            document.getElementById('assign_exam_id').value = id;
            const defClass = btn.getAttribute('data-class-id') || '';
            document.getElementById('assign_class_id').value = defClass;
            bd.classList.add('show');
            document.body.classList.add('modal-open');
        }
        function closeAssignModal() {
            const bd = document.getElementById('assignBackdrop');
            if (bd) bd.classList.remove('show');
            document.body.classList.remove('modal-open');
        }
        function openGenerateModal(id) {
            const bd = document.getElementById('generateBackdrop');
            if (!bd) return;
            document.getElementById('generate_exam_id').value = id;
            bd.classList.add('show');
            document.body.classList.add('modal-open');
        }
        function closeGenerateModal() {
            const bd = document.getElementById('generateBackdrop');
            if (bd) bd.classList.remove('show');
            document.body.classList.remove('modal-open');
        }
        function openManageExamModal(id) {
            const btn = document.querySelector('button[data-eid="'+id+'"]');
            if (!btn) return;
            const data = JSON.parse(btn.getAttribute('data-exam'));
            const bd = document.getElementById('manageBackdrop');
            if (!bd) return;
            document.getElementById('m_exam_id').value = data.exam_id || '';
            document.getElementById('md_exam_id').value = data.exam_id || '';
            document.getElementById('ma_exam_id').value = data.exam_id || '';
            document.getElementById('mg_exam_id').value = data.exam_id || '';
            document.getElementById('t_exam_id').value = data.exam_id || '';
            document.getElementById('m_title').value = data.title || '';
            document.getElementById('m_class_id').value = data.class_id || '';
            document.getElementById('m_subject_id').value = data.subject_id || '';
            document.getElementById('m_session').value = data.session || '';
            document.getElementById('m_term').value = data.term || '';
            document.getElementById('m_exam_type').value = data.exam_type || 'test';
            document.getElementById('m_total_score').value = data.total_score || (data.exam_type === 'exam' ? 30 : 20);
            const toLocal = (dt) => {
                if (!dt) return '';
                try {
                    const d = new Date(dt.replace(' ', 'T'));
                    const pad = n => String(n).padStart(2,'0');
                    return d.getFullYear() + '-' + pad(d.getMonth()+1) + '-' + pad(d.getDate()) + 'T' + pad(d.getHours()) + ':' + pad(d.getMinutes());
                } catch(e){ return ''; }
            };
            document.getElementById('m_start_at').value = toLocal(data.start_at);
            document.getElementById('m_end_at').value = toLocal(data.end_at);
            document.getElementById('m_duration').value = data.duration || '';
            document.getElementById('m_question_quota').value = data.question_quota || '';
            document.getElementById('m_allowed_attempts').value = data.allowed_attempts || 1;
            document.getElementById('m_randomize').checked = !!data.randomize_questions;
            document.getElementById('m_show_result').checked = !!data.show_result_to_student;
            const togBtn = document.getElementById('t_toggle_btn');
            const cur = data.status || 'inactive';
            document.getElementById('t_current_status').value = cur;
            togBtn.textContent = cur === 'active' ? 'Stop' : 'Start';
            bd.classList.add('show');
            document.body.classList.add('modal-open');
            const tabs = Array.from(bd.querySelectorAll('.tab-nav .tab'));
            const panels = {
                overview: document.getElementById('tab-overview'),
                assign: document.getElementById('tab-assign'),
                schedule: document.getElementById('tab-schedule'),
                danger: document.getElementById('tab-danger')
            };
            tabs.forEach(t=>{
                t.addEventListener('click', ()=>{
                    tabs.forEach(x=>x.classList.remove('active'));
                    t.classList.add('active');
                    Object.values(panels).forEach(p=>p.classList.remove('active'));
                    const key = t.getAttribute('data-tab');
                    panels[key].classList.add('active');
                });
            });
        }
        function closeManageExamModal() {
            const bd = document.getElementById('manageBackdrop');
            if (bd) bd.classList.remove('show');
            document.body.classList.remove('modal-open');
        }
    </script>
</body>
</html>
