<?php
require_once '../../config/database.php';
require_once '../../config/auth.php';
require_once '../../config/rbac.php';
$lms_config = require '../../config/lms.php';
require_once '../../includes/functions.php';
require_once '../../includes/middleware.php';

// Check if user is instructor or admin
anyRoleMiddleware(['instructor', 'admin']);

$user = getUserContext();
$db = getDB();
$userId = $_SESSION['user_id'];

// Get question ID from URL
$questionId = $_GET['id'] ?? null;
if (!$questionId) {
    header('Location: index.php');
    exit;
}

// Get question data
$stmt = $db->prepare("
    SELECT q.*, GROUP_CONCAT(DISTINCT qt.name) as tag_names
    FROM questions q
    LEFT JOIN question_tag_assignments qta ON q.id = qta.question_id
    LEFT JOIN question_tags qt ON qta.tag_id = qt.id
    WHERE q.id = ? AND (q.instructor_id = ? OR q.is_shared = TRUE)
    GROUP BY q.id
");
$stmt->execute([$questionId, $userId]);
$question = $stmt->fetch();

if (!$question) {
    $_SESSION['error_message'] = 'Question not found or access denied';
    header('Location: index.php');
    exit;
}

// Get question options if applicable
$options = [];
if (in_array($question['question_type'], ['mcq_single', 'mcq_multiple', 'true_false', 'matching'])) {
    $stmt = $db->prepare("SELECT * FROM question_options WHERE question_id = ? ORDER BY sort_order");
    $stmt->execute([$questionId]);
    $options = $stmt->fetchAll();
}

// Get categories and courses for dropdowns
$categories = $db->query("SELECT id, name FROM question_categories WHERE is_active = TRUE ORDER BY name")->fetchAll();
$courses = $db->prepare("SELECT id, title FROM courses WHERE instructor_id = ? ORDER BY title", [$userId])->fetchAll();
$tags = $db->query("SELECT id, name FROM question_tags ORDER BY name")->fetchAll();

// Decode JSON fields
$question['tags'] = $question['tag_names'] ? explode(',', $question['tag_names']) : [];
$question['hints'] = json_decode($question['hints'], true) ?: [];
$question['metadata'] = json_decode($question['metadata'], true) ?: [];

$page_title = 'Edit Question - ' . $lms_config['lms']['site_name'];
$active_link = 'questions';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?></title>
    <!-- Load Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Set up Tailwind configuration for Inter font and a professional color palette -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'primary-blue': '#1E3A8A', // Deep Indigo/Navy
                        'background-light': '#F8FAFC', // Slate 50
                        'text-dark': '#1F2937', // Gray 800
                        'accent-subtle': '#E5E7EB', // Gray 200
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <!-- Font Awesome for icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <!-- Summernote -->
    <link href="../../vendor/summernote-0.9.0-dist/summernote-lite.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="../../vendor/summernote-0.9.0-dist/summernote-lite.min.js"></script>
</head>
<body class="bg-background-light font-sans text-text-dark min-h-screen">

<div id="sidebar-overlay" class="sidebar-overlay"></div>

<!-- Toast Notification Container -->
<div id="toast-container"></div>

<div class="flex">
    <?php include '../includes/sidebar.php'; ?>

    <!-- Top Bar (Mobile/Desktop Header) -->
    <header class="bg-white shadow-sm fixed top-0 left-0 right-0 z-10 border-b border-accent-subtle">
        <div class="px-4 sm:px-6 lg:px-8 py-4 flex justify-between items-center">
            <div class="flex items-center space-x-3">
                <img src="../../assets/images/logo_1757657555.jpg" alt="Instructor Panel Logo" class="h-10 w-10">
                <div>
                    <h1 class="text-xl font-bold text-primary-blue"><?php echo htmlspecialchars($lms_config['lms']['site_name']); ?></h1>
                    <p class="text-sm text-gray-600"><?php echo htmlspecialchars($page_title); ?></p>
                </div>
            </div>

            <div class="flex items-center space-x-4">
                <span class="text-sm font-medium hidden sm:inline"><?php echo htmlspecialchars($user['username']); ?></span>
                <img class="h-10 w-10 rounded-full border-2 border-primary-blue object-cover" src="https://placehold.co/100x100/1E3A8A/ffffff?text=<?php echo substr(htmlspecialchars($user['username'] ?? 'I'), 0, 1); ?>" alt="User Avatar">
                <!-- Mobile Menu Button (Hamburger) -->
                <button class="lg:hidden p-2 rounded-lg text-text-dark hover:bg-accent-subtle ml-4" id="mobileMenuButton">
                    <span class="text-xl">☰</span>
                </button>
            </div>
        </div>
    </header>

        <!-- Flash Messages -->
        <?php if (isset($_SESSION['success_message'])): ?>
            <script>
                document.addEventListener('DOMContentLoaded', function() {
                    showToast('<?php echo addslashes($_SESSION['success_message']); ?>', 'success');
                });
            </script>
            <?php unset($_SESSION['success_message']); ?>
        <?php endif; ?>

        <?php if (isset($_SESSION['error_message'])): ?>
            <script>
                document.addEventListener('DOMContentLoaded', function() {
                    showToast('<?php echo addslashes($_SESSION['error_message']); ?>', 'error');
                });
            </script>
            <?php unset($_SESSION['error_message']); ?>
        <?php endif; ?>

        <!-- Main Content Area -->
        <main class="flex-1 overflow-y-auto pt-16">

            <?php include '../includes/mobile_menu.php'; ?>

            <form id="questionForm" method="POST" action="update.php">
                <input type="hidden" name="question_id" value="<?php echo $question['id']; ?>">
                <div class="question-form-layout">
                    <!-- Main Question Form -->
                    <div class="question-main-form">
                        <div class="form-card">
                            <div class="form-card-header">
                                <h3><i class="fas fa-file-alt me-2"></i>Question Details</h3>
                                <p>Modify the core elements of your assessment question</p>
                            </div>
                            <div class="form-card-body">
                            <!-- Question Type -->
                            <div class="mb-3">
                                <label for="question_type" class="form-label">Question Type <span class="text-danger">*</span></label>
                                <select class="form-select" id="question_type" name="question_type" required>
                                    <option value="">Select question type</option>
                                    <option value="mcq_single" <?php echo $question['question_type'] === 'mcq_single' ? 'selected' : ''; ?>>Multiple Choice (Single Answer)</option>
                                    <option value="mcq_multiple" <?php echo $question['question_type'] === 'mcq_multiple' ? 'selected' : ''; ?>>Multiple Choice (Multiple Answers)</option>
                                    <option value="true_false" <?php echo $question['question_type'] === 'true_false' ? 'selected' : ''; ?>>True/False</option>
                                    <option value="essay" <?php echo $question['question_type'] === 'essay' ? 'selected' : ''; ?>>Essay</option>
                                    <option value="short_answer" <?php echo $question['question_type'] === 'short_answer' ? 'selected' : ''; ?>>Short Answer</option>
                                    <option value="matching" <?php echo $question['question_type'] === 'matching' ? 'selected' : ''; ?>>Matching</option>
                                    <option value="code" <?php echo $question['question_type'] === 'code' ? 'selected' : ''; ?>>Code/Syntax</option>
                                    <option value="fill_blanks" <?php echo $question['question_type'] === 'fill_blanks' ? 'selected' : ''; ?>>Fill in the Blanks</option>
                                </select>
                            </div>

                            <!-- Question Title -->
                            <div class="mb-3">
                                <label for="title" class="form-label">Question Title <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="title" name="title" required
                                       value="<?php echo htmlspecialchars($question['title']); ?>"
                                       placeholder="Enter a brief title for this question">
                            </div>

                            <!-- Question Content -->
                            <div class="mb-3">
                                <label for="content" class="form-label">Question Content <span class="text-danger">*</span></label>
                                <textarea class="form-control" id="content" name="content" rows="4" required
                                          placeholder="Enter the full question text. You can use rich text formatting."><?php echo $question['content']; ?></textarea>
                                <div class="form-text">Supports rich text formatting.</div>
                            </div>

                            <!-- Dynamic Options Section -->
                            <div id="options_section" class="mb-3" style="display: <?php echo in_array($question['question_type'], ['mcq_single', 'mcq_multiple', 'true_false']) ? 'block' : 'none'; ?>;">
                                <label class="form-label">Answer Options</label>
                                <div id="options_container">
                                    <?php if ($question['question_type'] === 'true_false'): ?>
                                        <div class="mb-2">
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" name="correct_option" value="0" id="true_option"
                                                       <?php echo (isset($options[0]['is_correct']) && $options[0]['is_correct']) ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="true_option">True</label>
                                            </div>
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" name="correct_option" value="1" id="false_option"
                                                       <?php echo (isset($options[1]['is_correct']) && $options[1]['is_correct']) ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="false_option">False</label>
                                            </div>
                                        </div>
                                    <?php else: ?>
                                        <?php foreach ($options as $index => $option): ?>
                                            <div class="input-group mb-2">
                                                <span class="input-group-text"><?php echo chr(65 + $index); ?></span>
                                                <input type="text" class="form-control" name="options[]" placeholder="Option <?php echo $index + 1; ?>" required
                                                       value="<?php echo htmlspecialchars($option['option_text']); ?>">
                                                <?php if ($question['question_type'] === 'mcq_single'): ?>
                                                    <div class="input-group-text">
                                                        <input class="form-check-input mt-0" type="radio" name="correct_option" value="<?php echo $index; ?>"
                                                               <?php echo $option['is_correct'] ? 'checked' : ''; ?>>
                                                    </div>
                                                <?php elseif ($question['question_type'] === 'mcq_multiple'): ?>
                                                    <div class="input-group-text">
                                                        <input class="form-check-input mt-0" type="checkbox" name="correct_options[]" value="<?php echo $index; ?>"
                                                               <?php echo $option['is_correct'] ? 'checked' : ''; ?>>
                                                    </div>
                                                <?php endif; ?>
                                                <button class="btn btn-outline-danger" type="button" onclick="removeOption(this)">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </div>
                                <?php if ($question['question_type'] !== 'true_false'): ?>
                                    <button type="button" class="btn btn-outline-primary btn-sm" id="add_option">
                                        <i class="fas fa-plus me-1"></i>Add Option
                                    </button>
                                <?php endif; ?>
                            </div>

                            <!-- Matching Pairs Section -->
                            <div id="matching_section" class="mb-3" style="display: <?php echo $question['question_type'] === 'matching' ? 'block' : 'none'; ?>;">
                                <label class="form-label">Matching Pairs</label>
                                <div id="matching_container">
                                    <?php foreach ($options as $index => $option): ?>
                                        <div class="row mb-2">
                                            <div class="col-md-5">
                                                <input type="text" class="form-control" name="matching_left[]" placeholder="Left side" required
                                                       value="<?php echo htmlspecialchars($option['option_text']); ?>">
                                            </div>
                                            <div class="col-md-5">
                                                <input type="text" class="form-control" name="matching_right[]" placeholder="Right side" required
                                                       value="<?php echo htmlspecialchars($option['option_value']); ?>">
                                            </div>
                                            <div class="col-md-2">
                                                <button class="btn btn-outline-danger w-100" type="button" onclick="removeMatchingPair(this)">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                                <button type="button" class="btn btn-outline-primary btn-sm" id="add_matching_pair">
                                    <i class="fas fa-plus me-1"></i>Add Matching Pair
                                </button>
                            </div>

                            <!-- Fill in Blanks Section -->
                            <div id="blanks_section" class="mb-3" style="display: <?php echo $question['question_type'] === 'fill_blanks' ? 'block' : 'none'; ?>;">
                                <label class="form-label">Fill in the Blanks Template</label>
                                <textarea class="form-control" id="blanks_template" name="blanks_template" rows="3"
                                          placeholder="Use [blank] placeholders in your text. Example: The capital of [blank] is Paris."><?php echo htmlspecialchars($question['metadata']['blanks_template'] ?? ''); ?></textarea>
                                <div class="form-text">Use [blank] to indicate where students should fill in answers.</div>
                            </div>

                            <!-- Code Section -->
                            <div id="code_section" class="mb-3" style="display: <?php echo $question['question_type'] === 'code' ? 'block' : 'none'; ?>;">
                                <label class="form-label">Code Template (Optional)</label>
                                <textarea class="form-control font-monospace" id="code_template" name="code_template" rows="6"
                                          placeholder="Provide starter code or template for the coding question"><?php echo htmlspecialchars($question['metadata']['code_template'] ?? ''); ?></textarea>
                                <div class="form-text">Students will see this code and can modify it.</div>
                            </div>

                            <!-- Explanation -->
                            <div class="mb-3">
                                <label for="explanation" class="form-label">Explanation (Optional)</label>
                                <textarea class="form-control" id="explanation" name="explanation" rows="3"
                                          placeholder="Provide an explanation for the correct answer"><?php echo $question['explanation']; ?></textarea>
                            </div>

                            <!-- Hints -->
                            <div class="mb-3">
                                <label class="form-label">Hints (Optional)</label>
                                <div id="hints_container">
                                    <?php foreach ($question['hints'] as $hint): ?>
                                        <div class="input-group mb-2">
                                            <input type="text" class="form-control" name="hints[]" placeholder="Hint" required
                                                   value="<?php echo htmlspecialchars($hint); ?>">
                                            <button class="btn btn-outline-danger" type="button" onclick="removeHint(this)">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                                <button type="button" class="btn btn-outline-secondary btn-sm" id="add_hint">
                                    <i class="fas fa-plus me-1"></i>Add Hint
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                    <!-- Settings Sidebar -->
                    <div class="question-settings-sidebar">
                        <div class="form-card">
                            <div class="form-card-header">
                                <h3><i class="fas fa-cogs me-2"></i>Question Settings</h3>
                                <p>Configure question parameters and metadata</p>
                            </div>
                            <div class="form-card-body">
                            <!-- Difficulty -->
                            <div class="mb-3">
                                <label for="difficulty" class="form-label">Difficulty</label>
                                <select class="form-select" id="difficulty" name="difficulty">
                                    <option value="easy" <?php echo $question['difficulty'] === 'easy' ? 'selected' : ''; ?>>Easy</option>
                                    <option value="medium" <?php echo $question['difficulty'] === 'medium' ? 'selected' : ''; ?>>Medium</option>
                                    <option value="hard" <?php echo $question['difficulty'] === 'hard' ? 'selected' : ''; ?>>Hard</option>
                                </select>
                            </div>

                            <!-- Points -->
                            <div class="mb-3">
                                <label for="points" class="form-label">Points</label>
                                <input type="number" class="form-control" id="points" name="points" value="<?php echo $question['points']; ?>" min="0" step="0.5">
                            </div>

                            <!-- Time Limit -->
                            <div class="mb-3">
                                <label for="time_limit" class="form-label">Time Limit (seconds)</label>
                                <input type="number" class="form-control" id="time_limit" name="time_limit" min="0"
                                       value="<?php echo $question['time_limit'] ?? ''; ?>"
                                       placeholder="Leave empty for no limit">
                                <div class="form-text">Time limit for answering this question</div>
                            </div>

                            <!-- Category -->
                            <div class="mb-3">
                                <label for="category_id" class="form-label">Category</label>
                                <select class="form-select" id="category_id" name="category_id">
                                    <option value="">Select category</option>
                                    <?php foreach ($categories as $category): ?>
                                        <option value="<?php echo $category['id']; ?>" <?php echo $question['category_id'] == $category['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($category['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <!-- Course (Optional) -->
                            <div class="mb-3">
                                <label for="course_id" class="form-label">Course (Optional)</label>
                                <select class="form-select" id="course_id" name="course_id">
                                    <option value="">General question (available to all)</option>
                                    <?php foreach ($courses as $course): ?>
                                        <option value="<?php echo $course['id']; ?>" <?php echo $question['course_id'] == $course['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($course['title']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="form-text">Leave empty for global questions</div>
                            </div>

                            <!-- Tags -->
                            <div class="mb-3">
                                <label class="form-label">Tags</label>
                                <select class="form-select" id="tags" name="tags[]" multiple>
                                    <?php foreach ($tags as $tag): ?>
                                        <option value="<?php echo $tag['id']; ?>" <?php echo in_array($tag['name'], $question['tags']) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($tag['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="form-text">Select multiple tags using Ctrl+Click</div>
                            </div>

                            <!-- Sharing -->
                            <div class="mb-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="is_shared" name="is_shared" <?php echo $question['is_shared'] ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="is_shared">
                                        Share with other instructors
                                    </label>
                                </div>
                                <div class="form-text">Allow other instructors to use this question</div>
                                </div>
                            </div>
                        </div>
                    </div>

                        <!-- Action Buttons -->
                        <div class="form-actions-card">
                            <div class="form-actions">
                                <button type="submit" id="updateButton" name="action" value="update" class="btn btn-primary">
                                    <i class="fas fa-save me-2"></i>Update Question
                                </button>
                                <button type="button" class="btn btn-outline-info" onclick="previewQuestion()">
                                    <i class="fas fa-eye me-2"></i>Preview Question
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </main>
    </div>

<!-- Custom Confirmation Modal (Hidden by default) -->
<div id="confirmation-modal" class="fixed inset-0 bg-gray-900 bg-opacity-50 hidden items-center justify-center z-50">
    <div class="bg-white p-6 rounded-lg shadow-2xl max-w-sm w-full transform transition-all">
        <h3 class="text-xl font-bold text-gray-800 mb-4" id="modal-title">Confirm Action</h3>
        <p class="text-gray-600 mb-6" id="modal-message">Are you sure you want to perform this action?</p>
        <div class="flex justify-end space-x-3">
            <button id="modal-cancel" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 transition">Cancel</button>
            <button id="modal-confirm" class="px-4 py-2 text-white rounded-md transition"></button>
        </div>
    </div>
</div>

<!-- Question Preview Modal -->
<div id="preview-modal" class="fixed inset-0 bg-gray-900 bg-opacity-50 hidden items-center justify-center z-50">
    <div class="bg-white p-6 rounded-lg shadow-2xl max-w-4xl w-full max-h-[90vh] overflow-y-auto">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-xl font-bold text-gray-800">Question Preview</h3>
            <button id="close-preview-modal" class="text-gray-500 hover:text-gray-700 text-2xl">&times;</button>
        </div>
        <div id="preview-content"></div>
    </div>
</div>

<script>
    // --- UI/Utility Functions ---

    // Function to show a dismissible toast notification
    function showToast(message, type = 'success') {
        const container = document.getElementById('toast-container');
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`; // Note: 'show' added below
        toast.innerHTML = `<i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-triangle'} mr-2"></i>${message}`;
        container.appendChild(toast);

        // Force repaint to start transition
        setTimeout(() => toast.classList.add('show'), 10);

        // Auto-dismiss after 4 seconds
        setTimeout(() => {
            toast.classList.remove('show');
            // Remove from DOM after transition finishes
            setTimeout(() => toast.remove(), 300);
        }, 4000);
    }

    // Function to handle the custom confirmation modal (replacing window.confirm)
    function showConfirmationModal(action, reviewId) {
        const modal = document.getElementById('confirmation-modal');
        const title = document.getElementById('modal-title');
        const message = document.getElementById('modal-message');
        const confirmButton = document.getElementById('modal-confirm');
        const cancelButton = document.getElementById('modal-cancel');

        const isApprove = action === 'approve';
        const actionText = isApprove ? 'Approve' : 'Reject';

        // Placeholder function to simulate the PHP action
        const performAction = () => {
            // In a real application, this would be an AJAX call:
            // fetch('api/review_action.php', { method: 'POST', body: JSON.stringify({ action: action, review_id: reviewId }) })
            // .then(response => response.json()).then(data => { ... })
            fetch('../api/reviews.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: action,
                    review_id: reviewId
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast(`Review ${actionText.toLowerCase()}d successfully.`, 'success');
                    modal.classList.add('hidden');
                    modal.classList.remove('flex');
                    // Reload or remove the review item from the UI
                    location.reload();
                } else {
                    showToast('Error: ' + data.error, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('An error occurred. Please try again.', 'error');
            });
        };

        // Set modal content
        title.textContent = `Confirm ${actionText}`;
        message.textContent = `Are you sure you want to ${actionText.toLowerCase()} this review? This action cannot be undone. (Review ID: ${reviewId})`;
        confirmButton.textContent = actionText;
        confirmButton.className = `px-4 py-2 text-white rounded-md transition ${isApprove ? 'bg-green-500 hover:bg-green-600' : 'bg-red-500 hover:bg-red-600'}`;

        // Show modal
        modal.classList.remove('hidden');
        modal.classList.add('flex');

        // Set listeners
        confirmButton.onclick = performAction;
        cancelButton.onclick = () => {
            modal.classList.add('hidden');
            modal.classList.remove('flex');
        };

        // Allow clicking the overlay to close
        document.getElementById('sidebar-overlay').onclick = () => {
            modal.classList.add('hidden');
            modal.classList.remove('flex');
        };
    }

    // Mobile Menu Functionality
    const mobileMenuButton = document.getElementById('mobileMenuButton');
    const closeMobileMenu = document.getElementById('closeMobileMenu');
    const mobileMenu = document.getElementById('mobileMenu');

    if (mobileMenuButton && closeMobileMenu && mobileMenu) {
        mobileMenuButton.addEventListener('click', () => {
            mobileMenu.classList.remove('-translate-x-full');
        });

        closeMobileMenu.addEventListener('click', () => {
            mobileMenu.classList.add('-translate-x-full');
        });

        // Close menu when a link is clicked
        mobileMenu.querySelectorAll('a').forEach(link => {
            link.addEventListener('click', () => {
                mobileMenu.classList.add('-translate-x-full');
            });
        });
    }

    // Question type change handler
    document.getElementById('question_type').addEventListener('change', function() {
        const type = this.value;
        toggleSections(type);
    });

    function toggleSections(type) {
        // Hide all sections first
        document.getElementById('options_section').style.display = 'none';
        document.getElementById('matching_section').style.display = 'none';
        document.getElementById('blanks_section').style.display = 'none';
        document.getElementById('code_section').style.display = 'none';

        // Show relevant sections based on type
        switch(type) {
            case 'mcq_single':
            case 'mcq_multiple':
                document.getElementById('options_section').style.display = 'block';
                break;
            case 'true_false':
                document.getElementById('options_section').style.display = 'block';
                break;
            case 'matching':
                document.getElementById('matching_section').style.display = 'block';
                break;
            case 'fill_blanks':
                document.getElementById('blanks_section').style.display = 'block';
                break;
            case 'code':
                document.getElementById('code_section').style.display = 'block';
                break;
        }
    }

    function addOption(multiple = false, number = null) {
        const container = document.getElementById('options_container');
        const optionDiv = document.createElement('div');
        optionDiv.className = 'input-group mb-2';

        const optionCount = container.children.length + 1;
        const optionNumber = number || optionCount;

        optionDiv.innerHTML = `
            <span class="input-group-text">${String.fromCharCode(64 + optionNumber)}</span>
            <input type="text" class="form-control" name="options[]" placeholder="Option ${optionNumber}" required>
            ${multiple ?
                `<div class="input-group-text">
                    <input class="form-check-input mt-0" type="checkbox" name="correct_options[]" value="${optionNumber - 1}">
                 </div>` :
                `<div class="input-group-text">
                    <input class="form-check-input mt-0" type="radio" name="correct_option" value="${optionNumber - 1}">
                 </div>`
            }
            <button class="btn btn-outline-danger" type="button" onclick="removeOption(this)">
                <i class="fas fa-trash"></i>
            </button>
        `;

        container.appendChild(optionDiv);
    }

    function removeOption(button) {
        button.closest('.input-group').remove();
    }

    function addMatchingPair() {
        const container = document.getElementById('matching_container');
        const pairDiv = document.createElement('div');
        pairDiv.className = 'row mb-2';

        pairDiv.innerHTML = `
            <div class="col-md-5">
                <input type="text" class="form-control" name="matching_left[]" placeholder="Left side" required>
            </div>
            <div class="col-md-5">
                <input type="text" class="form-control" name="matching_right[]" placeholder="Right side" required>
            </div>
            <div class="col-md-2">
                <button class="btn btn-outline-danger w-100" type="button" onclick="removeMatchingPair(this)">
                    <i class="fas fa-trash"></i>
                </button>
            </div>
        `;

        container.appendChild(pairDiv);
    }

    function removeMatchingPair(button) {
        button.closest('.row').remove();
    }

    // Add option button handler
    document.getElementById('add_option')?.addEventListener('click', function() {
        const type = document.getElementById('question_type').value;
        addOption(type === 'mcq_multiple');
    });

    // Add matching pair button handler
    document.getElementById('add_matching_pair')?.addEventListener('click', addMatchingPair);

    // Add hint functionality
    let hintCount = document.querySelectorAll('#hints_container .input-group').length;
    document.getElementById('add_hint').addEventListener('click', function() {
        hintCount++;
        const container = document.getElementById('hints_container');
        const hintDiv = document.createElement('div');
        hintDiv.className = 'input-group mb-2';

        hintDiv.innerHTML = `
            <input type="text" class="form-control" name="hints[]" placeholder="Hint ${hintCount}" required>
            <button class="btn btn-outline-danger" type="button" onclick="removeHint(this)">
                <i class="fas fa-trash"></i>
            </button>
        `;

        container.appendChild(hintDiv);
    });

    function removeHint(button) {
        button.closest('.input-group').remove();
    }

    function previewQuestion() {
        const form = document.getElementById('questionForm');
        const formData = new FormData(form);
        const type = formData.get('question_type');
        const title = formData.get('title');
        const content = formData.get('content');
        const explanation = formData.get('explanation');
        const hints = formData.getAll('hints[]');

        let html = `<h4 class="font-bold text-lg mb-4">${title}</h4>`;
        html += `<div class="mb-4">${content}</div>`;

        switch(type) {
            case 'mcq_single':
            case 'mcq_multiple':
                const options = formData.getAll('options[]');
                const correctOption = formData.get('correct_option');
                const correctOptions = formData.getAll('correct_options[]');
                html += '<div class="mb-4">';
                options.forEach((option, index) => {
                    const letter = String.fromCharCode(65 + index);
                    let checked = '';
                    if (type === 'mcq_single' && correctOption == index) checked = ' <span class="text-green-600">(Correct)</span>';
                    if (type === 'mcq_multiple' && correctOptions.includes(index.toString())) checked = ' <span class="text-green-600">(Correct)</span>';
                    html += `<div class="mb-2"><strong>${letter}.</strong> ${option}${checked}</div>`;
                });
                html += '</div>';
                break;
            case 'true_false':
                const trueChecked = formData.get('correct_option') == 0 ? ' <span class="text-green-600">(Correct)</span>' : '';
                const falseChecked = formData.get('correct_option') == 1 ? ' <span class="text-green-600">(Correct)</span>' : '';
                html += '<div class="mb-4">';
                html += `<div class="mb-2"><strong>True</strong>${trueChecked}</div>`;
                html += `<div class="mb-2"><strong>False</strong>${falseChecked}</div>`;
                html += '</div>';
                break;
            case 'essay':
                html += '<div class="mb-4"><textarea class="w-full p-2 border rounded" rows="6" placeholder="Student answer here..." disabled></textarea></div>';
                break;
            case 'short_answer':
                html += '<div class="mb-4"><input type="text" class="w-full p-2 border rounded" placeholder="Student answer here..." disabled></div>';
                break;
            case 'matching':
                const left = formData.getAll('matching_left[]');
                const right = formData.getAll('matching_right[]');
                html += '<div class="mb-4 grid grid-cols-2 gap-4">';
                html += '<div><h5 class="font-semibold">Left Side</h5>';
                left.forEach(item => html += `<div class="mb-1">${item}</div>`);
                html += '</div>';
                html += '<div><h5 class="font-semibold">Right Side</h5>';
                right.forEach(item => html += `<div class="mb-1">${item}</div>`);
                html += '</div>';
                html += '</div>';
                break;
            case 'fill_blanks':
                const blanksTemplate = formData.get('blanks_template');
                html += `<div class="mb-4">${blanksTemplate.replace(/\[blank\]/g, '_____')}</div>`;
                break;
            case 'code':
                const codeTemplate = formData.get('code_template');
                html += '<div class="mb-4"><pre class="bg-gray-100 p-4 rounded"><code>' + codeTemplate + '</code></pre></div>';
                break;
        }

        if (explanation) {
            html += `<div class="mb-4"><strong>Explanation:</strong> ${explanation}</div>`;
        }

        if (hints.length > 0) {
            html += '<div class="mb-4"><strong>Hints:</strong><ul class="list-disc pl-5">';
            hints.forEach(hint => html += `<li>${hint}</li>`);
            html += '</ul></div>';
        }

        document.getElementById('preview-content').innerHTML = html;
        document.getElementById('preview-modal').classList.remove('hidden');
        document.getElementById('preview-modal').classList.add('flex');
    }

    // Preview modal close functionality
    document.getElementById('close-preview-modal').addEventListener('click', () => {
        document.getElementById('preview-modal').classList.add('hidden');
        document.getElementById('preview-modal').classList.remove('flex');
    });

    // Close preview modal on overlay click
    document.getElementById('preview-modal').addEventListener('click', (e) => {
        if (e.target === document.getElementById('preview-modal')) {
            document.getElementById('preview-modal').classList.add('hidden');
            document.getElementById('preview-modal').classList.remove('flex');
        }
    });

    // Initialize Summernote for Question Content and Explanation
    $(document).ready(function() {
        $('#content').summernote({
            height: 200,
            toolbar: [
                ['style', ['bold', 'italic', 'underline', 'clear']],
                ['font', ['strikethrough']],
                ['para', ['ul', 'ol', 'paragraph']],
                ['insert', ['link']],
                ['view', ['fullscreen', 'codeview']]
            ]
        });
        $('#explanation').summernote({
            height: 150,
            toolbar: [
                ['style', ['bold', 'italic', 'underline', 'clear']],
                ['font', ['strikethrough']],
                ['para', ['ul', 'ol', 'paragraph']],
                ['insert', ['link']],
                ['view', ['fullscreen', 'codeview']]
            ]
        });
    });

    // Handle update button click to submit form via AJAX
    document.getElementById('updateButton').addEventListener('click', function(e) {
        e.preventDefault(); // Prevent default form submission

        const form = document.getElementById('questionForm');
        const formData = new FormData(form);

        // Show loading state
        const button = this;
        const originalText = button.innerHTML;
        button.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Updating...';
        button.disabled = true;

        fetch('update.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.text()) // Get response as text first
        .then(text => {
            // Check if it's a redirect (update.php redirects on success/error)
            if (text.includes('Location: edit.php')) {
                // Success - check for success message in session
                showToast('Question updated successfully!', 'success');
                // Optionally reload to show updated data
                setTimeout(() => location.reload(), 1000);
            } else if (text.includes('Error updating question')) {
                // Error
                showToast('Error updating question. Please try again.', 'error');
            } else {
                // Unexpected response
                showToast('Unexpected response. Please check the form and try again.', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('An error occurred. Please try again.', 'error');
        })
        .finally(() => {
            // Restore button state
            button.innerHTML = originalText;
            button.disabled = false;
        });
    });
</script>

    <style>
        /* Ensuring full page height and scrolling */
        html, body {
            height: 100%;
        }
        /* Custom scrollbar for a cleaner look */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        ::-webkit-scrollbar-thumb {
            background-color: #D1D5DB; /* Gray 300 */
            border-radius: 4px;
        }
        ::-webkit-scrollbar-track {
            background-color: transparent;
        }

        /* Custom Styles for Dashboard Layout */
        .admin-sidebar {
            transition: transform 0.3s ease-in-out;
            min-width: 250px;
            /* Using min-h-screen utility class */
        }
        @media (max-width: 1024px) {
            .admin-sidebar {
                position: fixed;
                top: 0;
                left: 0; /* Always positioned at 0, use transform to hide */
                transform: translateX(-100%); /* Hidden by default on mobile */
                z-index: 50;
                height: 100%;
            }
            .admin-container.sidebar-open .admin-sidebar {
                transform: translateX(0); /* Show on mobile */
            }
            .admin-container.sidebar-open .sidebar-overlay {
                display: block;
            }
        }

        /* Sidebar Overlay for Mobile */
        .sidebar-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 40;
            display: none;
            transition: opacity 0.3s ease;
        }

        /* Toast Notification Styles */
        #toast-container {
            position: fixed;
            top: 1.5rem;
            right: 1.5rem;
            z-index: 100;
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
            max-width: 350px;
        }

        .toast {
            padding: 1rem 1.5rem;
            border-radius: 0.5rem;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            color: white;
            opacity: 0;
            transform: translateX(100%);
            transition: opacity 0.3s ease-out, transform 0.3s ease-out;
        }

        .toast.show {
            opacity: 1;
            transform: translateX(0);
        }

        .toast-success { background-color: #10b981; }
        .toast-error { background-color: #ef4444; }

        /* Rating Stars */
        .rating .fas.fa-star {
            color: #ddd; /* Unfilled */
        }
        .rating .fas.fa-star.filled {
            color: #ffc107; /* Filled (Yellow/Gold) */
        }

        /* Form Styles */
        .question-form-layout {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 2rem;
            align-items: start;
        }

        .question-main-form {
            display: flex;
            flex-direction: column;
            gap: 2rem;
        }

        .question-settings-sidebar {
            position: sticky;
            top: 2rem;
        }

        .form-card {
            background: white;
            border-radius: 1rem;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.8);
            overflow: hidden;
        }

        .form-card-header {
            padding: 2rem;
            background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
            border-bottom: 1px solid #e5e7eb;
        }

        .form-card-header h3 {
            font-size: 1.25rem;
            font-weight: 700;
            color: #1f2937;
            margin-bottom: 0.5rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .form-card-header p {
            color: #64748b;
            margin: 0;
            font-size: 0.9rem;
        }

        .form-card-body {
            padding: 2rem;
        }

        .form-group {
            margin-bottom: 1.5rem;
        }

        .form-group label {
            display: block;
            font-weight: 600;
            color: #374151;
            margin-bottom: 0.5rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .form-control, .form-select {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 2px solid #e5e7eb;
            border-radius: 0.75rem;
            font-size: 0.875rem;
            transition: all 0.3s ease;
            background: white;
        }

        .form-control:focus, .form-select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .form-text {
            color: #64748b;
            font-size: 0.875rem;
            margin-top: 0.25rem;
        }

        .input-group {
            display: flex;
            align-items: stretch;
        }

        .input-group-text {
            background: #f8fafc;
            border: 2px solid #e5e7eb;
            border-right: none;
            padding: 0.75rem 1rem;
            color: #64748b;
            font-weight: 600;
            display: flex;
            align-items: center;
        }

        .input-group .form-control {
            border-left: none;
            border-radius: 0 0.75rem 0.75rem 0;
        }

        .input-group .form-control:focus {
            border-left: 2px solid #667eea;
        }

        .btn {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.75rem 1.5rem;
            font-weight: 600;
            text-decoration: none;
            border-radius: 0.75rem;
            border: none;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 0.875rem;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
            background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);
        }

        .btn-outline-secondary {
            background: transparent;
            border: 2px solid #6b7280;
            color: #6b7280;
        }

        .btn-outline-secondary:hover {
            background: #6b7280;
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(107, 114, 128, 0.3);
        }

        .btn-outline-info {
            background: transparent;
            border: 2px solid #3b82f6;
            color: #3b82f6;
        }

        .btn-outline-info:hover {
            background: #3b82f6;
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(59, 130, 246, 0.3);
        }

        .btn-lg {
            padding: 0.875rem 2rem;
            font-size: 1rem;
        }

        .form-check {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            margin-bottom: 1rem;
        }

        .form-check-input {
            width: 1.25rem;
            height: 1.25rem;
            border: 2px solid #e5e7eb;
            border-radius: 0.375rem;
            background: white;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .form-check-input:checked {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-color: #667eea;
        }

        .form-check-label {
            color: #374151;
            font-weight: 500;
            cursor: pointer;
        }

        .form-actions-card {
            background: white;
            border-radius: 1rem;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.8);
            overflow: hidden;
        }

        .form-actions {
            padding: 2rem;
            display: flex;
            gap: 1rem;
            justify-content: center;
            flex-wrap: wrap;
        }

        .btn-sm {
            padding: 0.5rem 1rem;
            font-size: 0.8rem;
        }

        .text-danger {
            color: #dc2626 !important;
        }

        .text-muted {
            color: #64748b !important;
        }

        /* Dynamic sections */
        #options_section, #matching_section, #blanks_section, #code_section {
            margin-top: 1.5rem;
            padding: 1.5rem;
            background: #f8fafc;
            border-radius: 0.75rem;
            border: 1px solid #e5e7eb;
        }

        #options_container, #matching_container {
            margin-top: 1rem;
        }

        .mb-3 {
            margin-bottom: 1rem;
        }

        /* Responsive Design */
        @media (max-width: 1024px) {
            .question-form-layout {
                grid-template-columns: 1fr;
                gap: 1.5rem;
            }

            .question-settings-sidebar {
                position: static;
            }

            .form-card-body {
                padding: 1.5rem;
            }

            .form-actions {
                flex-direction: column;
            }

            .btn {
                justify-content: center;
            }
        }

        @media (max-width: 768px) {
            .form-card-header {
                padding: 1.5rem;
            }

            .form-card-body {
                padding: 1.5rem;
            }

            .form-actions {
                padding: 1.5rem;
            }
        }
    </style>
</body>
</html>