<?php
require_once('source/session.php');
require_once('source/error.php');
require_once('source/dbconfig.php');
require_once('source/function.php');
require_once('source/restrict_user.php');

// Clear selections if requested
if (isset($_GET['clear'])) {
    unset($_SESSION['exam_subject_id']);
    unset($_SESSION['subject_id']);
    unset($_SESSION['exam_class_ids']);
    header("Location: add_question.php");
    exit();
}

// Fetch available exam-subject combinations
$stmt_exam_subjects = $DBH->query("
    SELECT es.id, e.exam_name, s.subject, es.subject_id 
    FROM tbl_exam_subject es
    JOIN tbl_exam e ON es.exam_id = e.id
    JOIN tbl_subject s ON es.subject_id = s.id
    ORDER BY e.exam_name, s.subject
");
$exam_subjects = $stmt_exam_subjects->fetchAll(PDO::FETCH_ASSOC);

// Fetch available exam-class combinations
$stmt_exam_classes = $DBH->query("
    SELECT ec.id, e.exam_name, ec.class, ec.term, ec.session 
    FROM tbl_exam_class ec
    JOIN tbl_exam e ON ec.exam_id = e.id
    ORDER BY e.exam_name, ec.class, ec.term
");
$exam_classes = $stmt_exam_classes->fetchAll(PDO::FETCH_ASSOC);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['confirm_selection'])) {
        // Handle exam-subject and exam-class selection confirmation
        $exam_subject_id = $_POST['exam_subject_id'];
        $exam_class_ids = $_POST['exam_class_id']; // Now an array

        // Get the subject_id for the selected exam_subject_id
        $stmt = $DBH->prepare("SELECT subject_id FROM tbl_exam_subject WHERE id = :id");
        $stmt->execute(['id' => $exam_subject_id]);
        $subject_data = $stmt->fetch(PDO::FETCH_ASSOC);

        // Store selections in session
        $_SESSION['exam_subject_id'] = $exam_subject_id;
        $_SESSION['subject_id'] = $subject_data['subject_id'];
        $_SESSION['exam_class_ids'] = $exam_class_ids;
        
        header("Location: add_question.php");
        exit();
        
    } elseif (isset($_POST['submit_questions'])) {
        // Handle question submission (both updates and new questions)
        $exam_subject_id = $_SESSION['exam_subject_id'];
        $subject_id = $_SESSION['subject_id'];
        $exam_class_ids = $_SESSION['exam_class_ids'];

        try {
            $DBH->beginTransaction();
            
            // Process deleted questions
            if (isset($_POST['deleted_questions'])) {
                foreach ($_POST['deleted_questions'] as $question_id) {
                    // First get file path to delete the physical file
                    $stmt = $DBH->prepare("SELECT file_path FROM tbl_question WHERE id = :id");
                    $stmt->execute(['id' => $question_id]);
                    $question = $stmt->fetch(PDO::FETCH_ASSOC);
                    
                    if ($question && $question['file_path']) {
                        @unlink($_SERVER['DOCUMENT_ROOT'] . $question['file_path']);
                    }
                    
                    $stmt = $DBH->prepare("DELETE FROM tbl_question WHERE id = :id");
                    $stmt->execute(['id' => $question_id]);
                }
            }
            
            // Process existing questions (updates)
            if (isset($_POST['existing_questions'])) {
                foreach ($_POST['existing_questions'] as $question_id => $question) {
                    // Handle file upload for existing questions
                    $relative_path = null;
                    if (!empty($_FILES['existing_questions']['name'][$question_id]['file'])) {
                        $file = $_FILES['existing_questions']['tmp_name'][$question_id]['file'];
                        $file_name = $_FILES['existing_questions']['name'][$question_id]['file'];
                        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                    
                        $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx'];
                        if (in_array($file_ext, $allowed_extensions)) {
                            $upload_dir = $_SERVER['DOCUMENT_ROOT'] . '/portal/coll_admin/uploads/questions/';
                            if (!is_dir($upload_dir)) {
                                mkdir($upload_dir, 0777, true);
                            }
                    
                            // Generate relative path for database
                            $relative_path = '/portal/coll_admin/uploads/questions/' . uniqid() . '_' . basename($file_name);
                            $full_path = $_SERVER['DOCUMENT_ROOT'] . $relative_path;
                            
                            if (!move_uploaded_file($file, $full_path)) {
                                throw new Exception("Failed to upload file");
                            }
                            
                            // Delete old file if it exists
                            $stmt = $DBH->prepare("SELECT file_path FROM tbl_question WHERE id = :id");
                            $stmt->execute(['id' => $question_id]);
                            $old_question = $stmt->fetch(PDO::FETCH_ASSOC);
                            if ($old_question && $old_question['file_path']) {
                                @unlink($_SERVER['DOCUMENT_ROOT'] . $old_question['file_path']);
                            }
                        } else {
                            throw new Exception("Invalid file type");
                        }
                    } else {
                        // Keep existing relative path if no new file uploaded
                        $stmt = $DBH->prepare("SELECT file_path FROM tbl_question WHERE id = :id");
                        $stmt->execute(['id' => $question_id]);
                        $old_question = $stmt->fetch(PDO::FETCH_ASSOC);
                        $relative_path = $old_question ? $old_question['file_path'] : null;
                    }

                    $stmt = $DBH->prepare("
                        UPDATE tbl_question 
                        SET question_text = :question_text,
                            option_a = :option_a,
                            option_b = :option_b,
                            option_c = :option_c,
                            option_d = :option_d,
                            correct_answer = :correct_answer,
                            file_path = :file_path
                        WHERE id = :id AND exam_subject_id = :exam_subject_id
                    ");
                    $stmt->execute([
                        'id' => $question_id,
                        'exam_subject_id' => $exam_subject_id,
                        'question_text' => $question['question_text'],
                        'option_a' => $question['option_a'],
                        'option_b' => $question['option_b'],
                        'option_c' => $question['option_c'],
                        'option_d' => $question['option_d'],
                        'correct_answer' => $question['correct_answer'],
                        'file_path' => $relative_path
                    ]);
                }
            }
            
            // Process new questions
            if (isset($_POST['new_questions'])) {
                foreach ($_POST['new_questions'] as $index => $question) {
                    // Handle file upload for new questions
                    $relative_path = null;
                    if (!empty($_FILES['new_questions']['name'][$index]['file'])) {
                        $file = $_FILES['new_questions']['tmp_name'][$index]['file'];
                        $file_name = $_FILES['new_questions']['name'][$index]['file'];
                        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                    
                        $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx'];
                        if (in_array($file_ext, $allowed_extensions)) {
                            $upload_dir = $_SERVER['DOCUMENT_ROOT'] . '/portal/coll_admin/uploads/questions/';
                            if (!is_dir($upload_dir)) {
                                mkdir($upload_dir, 0777, true);
                            }
                    
                            // Generate relative path for database
                            $relative_path = '/portal/coll_admin/uploads/questions/' . uniqid() . '_' . basename($file_name);
                            $full_path = $_SERVER['DOCUMENT_ROOT'] . $relative_path;
                            
                            if (!move_uploaded_file($file, $full_path)) {
                                throw new Exception("Failed to upload file");
                            }
                        } else {
                            throw new Exception("Invalid file type");
                        }
                    }

                    // Insert for each selected class
                    foreach ($exam_class_ids as $exam_class_id) {
                        $stmt = $DBH->prepare("
                            INSERT INTO tbl_question 
                            (exam_class_id, exam_subject_id, subject_id, question_text, option_a, option_b, option_c, option_d, correct_answer, file_path) 
                            VALUES 
                            (:exam_class_id, :exam_subject_id, :subject_id, :question_text, :option_a, :option_b, :option_c, :option_d, :correct_answer, :file_path)
                        ");
                        $stmt->execute([
                            'exam_class_id' => $exam_class_id,
                            'exam_subject_id' => $exam_subject_id,
                            'subject_id' => $subject_id,
                            'question_text' => $question['question_text'],
                            'option_a' => $question['option_a'],
                            'option_b' => $question['option_b'],
                            'option_c' => $question['option_c'],
                            'option_d' => $question['option_d'],
                            'correct_answer' => $question['correct_answer'],
                            'file_path' => $relative_path
                        ]);
                    }
                }
            }

            $DBH->commit();
            
            $_SESSION['success'] = "Questions updated successfully for all selected classes!";
            header("Location: add_question.php");
            exit();
            
        } catch (Exception $e) {
            $DBH->rollBack();
            $_SESSION['error'] = "Error: " . $e->getMessage();
            header("Location: add_question.php");
            exit();
        }
    }
}

// Fetch existing questions if selection is made (for the first class only for display purposes)
$existing_questions = [];
if (isset($_SESSION['exam_subject_id']) && isset($_SESSION['exam_class_ids']) && !empty($_SESSION['exam_class_ids'])) {
    $first_class_id = $_SESSION['exam_class_ids'][0];
    $stmt = $DBH->prepare("
        SELECT * FROM tbl_question 
        WHERE exam_subject_id = :exam_subject_id AND exam_class_id = :exam_class_id
        ORDER BY id
    ");
    $stmt->execute([
        'exam_subject_id' => $_SESSION['exam_subject_id'],
        'exam_class_id' => $first_class_id
    ]);
    $existing_questions = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit/Add Questions - VERBUM DEI INT'L COLLEGE CBT Management</title>
    
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Select2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    
    <style>
        :root {
            --light-green: #e8f5e9;
            --primary-green: #2e7d32;
            --dark-green: #1b5e20;
            --accent-red: #A10A3F;
        }
        
        body {
            background-color: var(--light-green);
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .admin-header {
            background-color: white;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .action-card {
            border: none;
            border-radius: 10px;
            box-shadow: 0 2px 15px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
        }
        
        .action-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 20px rgba(0,0,0,0.15);
        }
        
        .btn-exam {
            background-color: var(--primary-green);
            color: white;
        }
        
        .form-control:focus {
            border-color: var(--primary-green);
            box-shadow: 0 0 0 0.25rem rgba(46, 125, 50, 0.25);
        }
        
        .img-fluid {
            width: 100px;
            height: 100px;
        }
        
        .question-group {
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            background-color: white;
        }
        
        .selected-exam {
            background-color: #f8f9fa;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .file-preview {
            width: 200px;
            height: 150px;
            border: 2px dashed #ccc;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            margin: 10px auto;
            background-color: #f9f9f9;
        }
        
        .file-preview img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }
        
        .file-preview embed {
            width: 100%;
            height: 100%;
        }
        
        .file-preview a {
            text-align: center;
            color: #007bff;
            text-decoration: none;
        }
        
        .file-preview a:hover {
            text-decoration: underline;
        }
        
        .selected-classes {
            background-color: #f8f9fa;
            border-radius: 5px;
            padding: 10px;
            margin-bottom: 15px;
        }
        
        .class-badge {
            margin-right: 5px;
            margin-bottom: 5px;
        }
        
        .select2-container--default .select2-selection--multiple {
            min-height: 38px;
            border: 1px solid #ced4da;
        }
        
        .current-file {
            margin-top: 10px;
            font-size: 0.9rem;
        }
    </style>
</head>
<body>
    <!-- Header -->
    <header class="admin-header py-3">
        <div class="container">
            <div class="d-flex justify-content-between align-items-center">
                <div class="d-flex align-items-center">
                    <div class="logo-container me-3">
                        <img src="assets/images/coll_logo.jpg" alt="VDA Logo" class="img-fluid">
                    </div>
                    <div>
                        <h1 class="h4 mb-0">VERBUM DEI INT'L COLLEGE CBT Management</h1>
                        <small class="text-muted">Edit/Add Exam Questions</small>
                    </div>
                </div>
                <div class="dropdown">
                    <button class="btn btn-outline-secondary dropdown-toggle" type="button" id="adminDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="fas fa-user-circle me-1"></i> <?= htmlspecialchars($_SESSION['SESS_FULLNAME_ADMIN']) ?>
                    </button>
                    <ul class="dropdown-menu" aria-labelledby="adminDropdown">
                        <li><a class="dropdown-item" href="cbt_admin_home.php"><i class="fas fa-tachometer-alt me-2"></i> Dashboard</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="../admin/logout.php"><i class="fas fa-sign-out-alt me-2"></i> Logout</a></li>
                    </ul>
                </div>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <div class="container py-4">
        <div class="row justify-content-center">
            <div class="col-md-12">
                <div class="card action-card">
                    <div class="card-header bg-white">
                        <h3 class="mb-0"><i class="fas fa-edit me-2"></i> Edit/Add Questions</h3>
                    </div>
                    <div class="card-body">
                        <?php if (isset($_SESSION['error'])): ?>
                            <div class="alert alert-danger alert-dismissible fade show">
                                <?= $_SESSION['error'] ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                            </div>
                            <?php unset($_SESSION['error']); ?>
                        <?php endif; ?>
                        
                        <?php if (isset($_SESSION['success'])): ?>
                            <div class="alert alert-success alert-dismissible fade show">
                                <?= $_SESSION['success'] ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                            </div>
                            <?php unset($_SESSION['success']); ?>
                        <?php endif; ?>

                        <!-- Selection Section -->
                        <?php if (!isset($_SESSION['exam_subject_id'])): ?>
                            <form method="POST" id="selectionForm">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="exam_subject_id" class="form-label">Select Exam Subject</label>
                                        <select name="exam_subject_id" class="form-select" required>
                                            <option value="">-- Select Exam Subject --</option>
                                            <?php foreach ($exam_subjects as $es): ?>
                                                <option value="<?= $es['id'] ?>"><?= $es['exam_name'] . ' - ' . $es['subject'] ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="exam_class_id" class="form-label">Select Exam-Class(es)</label>
                                        <select name="exam_class_id[]" id="exam_class_select" class="form-select" multiple="multiple" required>
                                            <?php foreach ($exam_classes as $ec): ?>
                                                <option value="<?= $ec['id'] ?>">
                                                    <?= $ec['exam_name'] . ' - ' . $ec['class'] . ' (' . $ec['term'] . ' ' . $ec['session'] . ')' ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <small class="text-muted">Hold CTRL/CMD to select multiple classes or use the dropdown</small>
                                    </div>
                                </div>
                                
                                <div class="d-grid gap-2">
                                    <button type="submit" name="confirm_selection" class="btn btn-exam">
                                        <i class="fas fa-check-circle me-2"></i> Load Existing Questions to Continue
                                    </button>
                                    <a href="cbt_admin_home.php" class="btn btn-outline-secondary">
                                        <i class="fas fa-arrow-left me-2"></i> Back to Dashboard
                                    </a>
                                </div>
                            </form>
                        <?php else: ?>
                            <!-- Question Section -->
                            <form method="POST" id="questionForm" enctype="multipart/form-data">
                                <?php 
                                    $current_es = $exam_subjects[array_search($_SESSION['exam_subject_id'], array_column($exam_subjects, 'id'))];
                                ?>
                                <div class="alert alert-info mb-4">
                                    <strong>Exam Subject:</strong> <?= $current_es['exam_name'] . ' - ' . $current_es['subject'] ?><br><br>
                                    
                                    <strong>Selected Classes:</strong>
                                    <div class="selected-classes mt-2">
                                        <?php foreach ((array)$_SESSION['exam_class_ids'] as $exam_class_id): 
                                            $ec = $exam_classes[array_search($exam_class_id, array_column($exam_classes, 'id'))];
                                        ?>
                                            <span class="badge bg-primary class-badge">
                                                <?= $ec['exam_name'] . ' - ' . $ec['class'] . ' (' . $ec['term'] . ' ' . $ec['session'] . ')' ?>
                                            </span>
                                        <?php endforeach; ?>
                                    </div>
                                    <div class="mt-2">
                                        <a href="add_question.php?clear=1" class="btn btn-sm btn-outline-danger">
                                            <i class="fas fa-times me-1"></i> Change Selection
                                        </a>
                                    </div>
                                </div>
                                
                                <!-- Existing Questions -->
                                <div id="existing-questions">
                                    <h4 class="mb-3">Edit Existing Questions</h4>
                                    <?php if (!empty($existing_questions)): ?>
                                        <?php foreach ($existing_questions as $index => $question): ?>
                                            <div class="question-group mb-4 p-3 border rounded" data-question-id="<?= $question['id'] ?>">
                                                <input type="hidden" name="existing_questions[<?= $question['id'] ?>][id]" value="<?= $question['id'] ?>">
                                                <h5>Question <?= $index + 1 ?></h5>
                                                
                                                <div class="mb-3">
                                                    <label class="form-label">Question Text</label>
                                                    <textarea name="existing_questions[<?= $question['id'] ?>][question_text]" class="form-control" rows="3" required><?= htmlspecialchars($question['question_text']) ?></textarea>
                                                </div>
                                                
                                                <div class="row">
                                                    <div class="col-md-6 mb-3">
                                                        <label class="form-label">Option A</label>
                                                        <input type="text" name="existing_questions[<?= $question['id'] ?>][option_a]" class="form-control" value="<?= htmlspecialchars($question['option_a']) ?>" required>
                                                    </div>
                                                    <div class="col-md-6 mb-3">
                                                        <label class="form-label">Option B</label>
                                                        <input type="text" name="existing_questions[<?= $question['id'] ?>][option_b]" class="form-control" value="<?= htmlspecialchars($question['option_b']) ?>" required>
                                                    </div>
                                                </div>
                                                
                                                <div class="row">
                                                    <div class="col-md-6 mb-3">
                                                        <label class="form-label">Option C</label>
                                                        <input type="text" name="existing_questions[<?= $question['id'] ?>][option_c]" class="form-control" value="<?= htmlspecialchars($question['option_c']) ?>" required>
                                                    </div>
                                                    <div class="col-md-6 mb-3">
                                                        <label class="form-label">Option D</label>
                                                        <input type="text" name="existing_questions[<?= $question['id'] ?>][option_d]" class="form-control" value="<?= htmlspecialchars($question['option_d']) ?>" required>
                                                    </div>
                                                </div>
                                                
                                                <div class="mb-3">
                                                    <label class="form-label">Correct Answer</label>
                                                    <select name="existing_questions[<?= $question['id'] ?>][correct_answer]" class="form-select" required>
                                                        <option value="A" <?= $question['correct_answer'] == 'A' ? 'selected' : '' ?>>A</option>
                                                        <option value="B" <?= $question['correct_answer'] == 'B' ? 'selected' : '' ?>>B</option>
                                                        <option value="C" <?= $question['correct_answer'] == 'C' ? 'selected' : '' ?>>C</option>
                                                        <option value="D" <?= $question['correct_answer'] == 'D' ? 'selected' : '' ?>>D</option>
                                                    </select>
                                                </div>
                                                
                                                <div class="mb-3">
                                                    <label class="form-label">Attach File (Image, PDF, Word)</label>
                                                    <input type="file" name="existing_questions[<?= $question['id'] ?>][file]" class="form-control file-input" onchange="previewFile(this, 'existing-preview-<?= $question['id'] ?>')">
                                                    <div class="file-preview mt-2" id="existing-preview-<?= $question['id'] ?>">
                                                        <?php if ($question['file_path']): ?>
                                                            <?php
                                                                $file_ext = strtolower(pathinfo($question['file_path'], PATHINFO_EXTENSION));
                                                                $file_name = basename($question['file_path']);
                                                            ?>
                                                            <?php if (in_array($file_ext, ['jpg', 'jpeg', 'png', 'gif'])): ?>
                                                                <img src="<?= $question['file_path'] ?>" alt="Question Image">
                                                            <?php elseif ($file_ext == 'pdf'): ?>
                                                                <embed src="<?= $question['file_path'] ?>" type="application/pdf">
                                                                <p class="mt-2"><a href="<?= $question['file_path'] ?>" target="_blank">Open PDF</a></p>
                                                            <?php elseif (in_array($file_ext, ['doc', 'docx'])): ?>
                                                                <p><a href="<?= $question['file_path'] ?>" target="_blank">Download Word Document</a></p>
                                                            <?php else: ?>
                                                                <p>Current file: <?= $file_name ?></p>
                                                            <?php endif; ?>
                                                        <?php endif; ?>
                                                    </div>
                                                    <?php if ($question['file_path']): ?>
                                                        <div class="current-file">
                                                            Current file: <?= basename($question['file_path']) ?>
                                                            <input type="hidden" name="existing_questions[<?= $question['id'] ?>][current_file]" value="<?= $question['file_path'] ?>">
                                                        </div>
                                                    <?php endif; ?>
                                                </div>
                                                
                                                <button type="button" class="btn btn-sm btn-danger" onclick="confirmRemoveQuestion(this, <?= $question['id'] ?>)">
                                                    <i class="fas fa-trash-alt me-1"></i> Remove Question
                                                </button>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <div class="alert alert-warning">No existing questions found for this combination.</div>
                                    <?php endif; ?>
                                </div>

                                <!-- New Questions -->
                                <div id="new-questions" class="mt-5">
                                    <h4 class="mb-3">Add New Questions</h4>
                                    <div id="new-questions-container"></div>
                                    <button type="button" class="btn btn-secondary mt-2" onclick="addNewQuestion()">
                                        <i class="fas fa-plus-circle me-2"></i> Add New Question
                                    </button>
                                </div>

                                <div class="d-grid gap-2 mt-4">
                                    <button type="submit" name="submit_questions" class="btn btn-success">
                                        <i class="fas fa-save me-2"></i> Save All Changes
                                    </button>
                                    <a href="cbt_admin_home.php" class="btn btn-outline-secondary">
                                        <i class="fas fa-arrow-left me-2"></i> Back to Dashboard
                                    </a>
                                </div>
                            </form>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <footer class="footer mt-5">
        <div class="container">
            <div class="row">
                <div class="col-md-8">
                    <p class="mb-1">VERBUM DEI INT'L COLLEGE</p>
                    <p class="mb-0">Powered By <a href="https://dataswift.com.ng" target="_blank" class="text-white">DataSwift</a> 
                    <img src="assets/images/dataswift_logo.png" alt="DataSwift Logo" style="height: 20px; margin-left: 5px;"></p>
                </div>
                <div class="col-md-4 text-md-end">
                    <p class="mb-0">&copy; <?= date('Y') ?> All Rights Reserved</p>
                </div>
            </div>
        </div>
    </footer>

    <!-- JavaScript Libraries -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <script>
        // Initialize Select2 for multi-select
        $(document).ready(function() {
            $('#exam_class_select').select2({
                placeholder: "Select class(es)",
                allowClear: true
            });
        });

        // New question counter
        let newQuestionCounter = 0;
        
        // Add first new question when page loads if in edit mode
        document.addEventListener('DOMContentLoaded', function() {
            <?php if (isset($_SESSION['exam_subject_id'])): ?>
                addNewQuestion();
            <?php endif; ?>
        });

        function addNewQuestion() {
            newQuestionCounter++;
            const container = document.getElementById('new-questions-container');
            const questionHtml = `
                <div class="new-question-group mb-4 p-3 border rounded" data-new-id="${newQuestionCounter}">
                    <h5>New Question ${newQuestionCounter}</h5>
                    <div class="mb-3">
                        <label class="form-label">Question Text</label>
                        <textarea name="new_questions[${newQuestionCounter - 1}][question_text]" class="form-control" rows="3" required></textarea>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Option A</label>
                            <input type="text" name="new_questions[${newQuestionCounter - 1}][option_a]" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Option B</label>
                            <input type="text" name="new_questions[${newQuestionCounter - 1}][option_b]" class="form-control" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Option C</label>
                            <input type="text" name="new_questions[${newQuestionCounter - 1}][option_c]" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Option D</label>
                            <input type="text" name="new_questions[${newQuestionCounter - 1}][option_d]" class="form-control" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Correct Answer</label>
                        <select name="new_questions[${newQuestionCounter - 1}][correct_answer]" class="form-select" required>
                            <option value="A">A</option>
                            <option value="B">B</option>
                            <option value="C">C</option>
                            <option value="D">D</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Attach File (Image, PDF, Word)</label>
                        <input type="file" name="new_questions[${newQuestionCounter - 1}][file]" class="form-control file-input" onchange="previewFile(this, 'new-preview-${newQuestionCounter}')">
                        <div class="file-preview mt-2" id="new-preview-${newQuestionCounter}"></div>
                    </div>
                    <button type="button" class="btn btn-sm btn-danger" onclick="removeNewQuestion(this)">
                        <i class="fas fa-trash-alt me-1"></i> Remove Question
                    </button>
                </div>
            `;
            container.insertAdjacentHTML('beforeend', questionHtml);
        }

        function removeNewQuestion(button) {
            if (confirm('Are you sure you want to remove this new question?')) {
                const questionDiv = button.closest('.new-question-group');
                questionDiv.remove();
                // Renumber remaining new questions
                const questions = document.querySelectorAll('.new-question-group');
                questions.forEach((question, index) => {
                    question.querySelector('h5').textContent = `New Question ${index + 1}`;
                    // Update all the names in the inputs to maintain array order
                    const inputs = question.querySelectorAll('textarea, input, select');
                    inputs.forEach(input => {
                        const name = input.name.replace(/\[\d+\]/, `[${index}]`);
                        input.name = name;
                    });
                });
                newQuestionCounter = questions.length;
            }
        }

        function confirmRemoveQuestion(button, questionId) {
            if (confirm('Are you sure you want to remove this question? This will delete it from the database when you save.')) {
                // Create hidden input to mark question for deletion
                const form = document.getElementById('questionForm');
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'deleted_questions[]';
                input.value = questionId;
                form.appendChild(input);
                
                // Remove the question from display
                button.closest('.question-group').remove();
            }
        }

        function previewFile(input, previewId) {
            const file = input.files[0];
            const previewDiv = document.getElementById(previewId);

            if (file) {
                const reader = new FileReader();
                reader.onload = function (e) {
                    const fileType = file.type;

                    if (fileType.startsWith('image/')) {
                        previewDiv.innerHTML = `<img src="${e.target.result}" alt="File Preview">`;
                    } else if (fileType === 'application/pdf') {
                        previewDiv.innerHTML = `
                            <embed src="${e.target.result}" type="application/pdf">
                            <p class="mt-2"><a href="${e.target.result}" target="_blank">Open PDF</a></p>
                        `;
                    } else if (fileType === 'application/msword' || fileType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
                        previewDiv.innerHTML = `<p><a href="${e.target.result}" target="_blank">Download Word Document</a></p>`;
                    } else {
                        previewDiv.innerHTML = `<p>File: ${file.name}</p>`;
                    }
                };
                reader.readAsDataURL(file);
            } else {
                previewDiv.innerHTML = '';
            }
        }

        // Form validation
        document.getElementById('selectionForm')?.addEventListener('submit', function(e) {
            const examSubject = this.querySelector('[name="exam_subject_id"]');
            const examClass = this.querySelector('[name="exam_class_id[]"]');
            
            if (!examSubject.value) {
                alert('Please select an exam subject');
                e.preventDefault();
            }
            
            if (!examClass.value || examClass.selectedOptions.length === 0) {
                alert('Please select at least one exam class');
                e.preventDefault();
            }
        }); 

        document.getElementById('questionForm')?.addEventListener('submit', function(e) {
            const existingQuestions = document.querySelectorAll('.question-group');
            const newQuestions = document.querySelectorAll('.new-question-group');
            
            if (existingQuestions.length === 0 && newQuestions.length === 0) {
                alert('Please add at least one question');
                e.preventDefault();
            }
        });
    </script>
</body>
</html>