<?php
require_once '../../config/database.php';
require_once '../../config/auth.php';
require_once '../../config/rbac.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 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();

$page_title = 'Create Question - Mutalex Academy';
include '../../includes/header.php';
?>

<div class="admin-container">
    <div class="admin-sidebar">
        <div class="sidebar-header">
            <h2><i class="fas fa-graduation-cap me-2"></i>Mutalex Academy</h2>
            <p>Instructor Panel</p>
        </div>

        <nav class="sidebar-nav">
            <ul>
                <li><a href="../dashboard.php"><i class="fas fa-tachometer-alt me-2"></i>Dashboard</a></li>
                <li><a href="../courses/"><i class="fas fa-book me-2"></i>My Courses</a></li>
                <li><a href="../courses/new.php"><i class="fas fa-plus me-2"></i>Create Course</a></li>
                <li><a href="index.php" class="active"><i class="fas fa-question-circle me-2"></i>Question Bank</a></li>
                <li><a href="../exams/"><i class="fas fa-file-alt me-2"></i>Exams</a></li>
                <li><a href="../resources.php"><i class="fas fa-folder me-2"></i>Resources</a></li>
                <li><a href="../students.php"><i class="fas fa-users me-2"></i>Students</a></li>
                <li><a href="../assignments.php"><i class="fas fa-tasks me-2"></i>Assignments</a></li>
                <li><a href="/lms/instructor/grading/index.php"><i class="fas fa-chart-line me-2"></i>Grades</a></li>
                <li><a href="../../logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>
            </ul>
        </nav>
    </div>

    <div class="admin-main">
        <div class="admin-header">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h1><i class="fas fa-plus-circle text-success me-3"></i>Create Question</h1>
                    <p class="text-muted mb-0">Build comprehensive assessment questions for your courses</p>
                </div>
                <a href="index.php" class="btn btn-outline-secondary btn-lg">
                    <i class="fas fa-arrow-left me-2"></i>Back to Questions
                </a>
            </div>
        </div>

        <div class="admin-content">

            <form id="questionForm" method="POST" action="save.php">
                <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>Define 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">Multiple Choice (Single Answer)</option>
                                    <option value="mcq_multiple">Multiple Choice (Multiple Answers)</option>
                                    <option value="true_false">True/False</option>
                                    <option value="essay">Essay</option>
                                    <option value="short_answer">Short Answer</option>
                                    <option value="matching">Matching</option>
                                    <option value="code">Code/Syntax</option>
                                    <option value="fill_blanks">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
                                       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 HTML formatting."></textarea>
                                <div class="form-text">Supports HTML formatting for rich text content.</div>
                            </div>

                            <!-- Dynamic Options Section -->
                            <div id="options_section" class="mb-3" style="display: none;">
                                <label class="form-label">Answer Options</label>
                                <div id="options_container">
                                    <!-- Options will be added here dynamically -->
                                </div>
                                <button type="button" class="btn btn-outline-primary btn-sm" id="add_option">
                                    <i class="fas fa-plus me-1"></i>Add Option
                                </button>
                            </div>

                            <!-- Matching Pairs Section -->
                            <div id="matching_section" class="mb-3" style="display: none;">
                                <label class="form-label">Matching Pairs</label>
                                <div id="matching_container">
                                    <!-- Matching pairs will be added here -->
                                </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: 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."></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: 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"></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"></textarea>
                            </div>

                            <!-- Hints -->
                            <div class="mb-3">
                                <label class="form-label">Hints (Optional)</label>
                                <div id="hints_container">
                                    <!-- Hints will be added here -->
                                </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">Easy</option>
                                    <option value="medium" selected>Medium</option>
                                    <option value="hard">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="1" 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"
                                       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 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 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 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">
                                    <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" name="action" value="save_draft" class="btn btn-outline-secondary">
                                    <i class="fas fa-save me-2"></i>Save as Draft
                                </button>
                                <button type="submit" name="action" value="submit_review" class="btn btn-primary">
                                    <i class="fas fa-paper-plane me-2"></i>Submit for Review
                                </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>
    </div>
</div>

<script>
// 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';
            initializeOptions(type === 'mcq_multiple');
            break;
        case 'true_false':
            document.getElementById('options_section').style.display = 'block';
            initializeTrueFalse();
            break;
        case 'matching':
            document.getElementById('matching_section').style.display = 'block';
            initializeMatching();
            break;
        case 'fill_blanks':
            document.getElementById('blanks_section').style.display = 'block';
            break;
        case 'code':
            document.getElementById('code_section').style.display = 'block';
            break;
    }
}

function initializeOptions(multiple = false) {
    const container = document.getElementById('options_container');
    container.innerHTML = '';

    // Add initial 4 options
    for (let i = 0; i < 4; i++) {
        addOption(multiple, i + 1);
    }
}

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 initializeTrueFalse() {
    const container = document.getElementById('options_container');
    container.innerHTML = `
        <div class="mb-2">
            <div class="form-check">
                <input class="form-check-input" type="radio" name="correct_option" value="0" id="true_option">
                <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">
                <label class="form-check-label" for="false_option">
                    False
                </label>
            </div>
        </div>
    `;
}

function initializeMatching() {
    const container = document.getElementById('matching_container');
    container.innerHTML = '';

    // Add initial 3 pairs
    for (let i = 0; i < 3; i++) {
        addMatchingPair();
    }
}

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 removeOption(button) {
    button.closest('.input-group').remove();
}

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 = 0;
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() {
    // Basic preview functionality
    const formData = new FormData(document.getElementById('questionForm'));
    const preview = {
        type: formData.get('question_type'),
        title: formData.get('title'),
        content: formData.get('content'),
        options: formData.getAll('options[]'),
        correct_option: formData.get('correct_option')
    };

    console.log('Question Preview:', preview);
    alert('Preview functionality - check console for question data');
}
</script>

<style>
/* Custom styles for Create Question page */
.admin-container {
    display: flex;
    min-height: 100vh;
    background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
}

.admin-sidebar {
    width: 280px;
    background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
    color: white;
    position: fixed;
    height: 100vh;
    overflow-y: auto;
    box-shadow: 4px 0 15px rgba(0, 0, 0, 0.1);
    z-index: 1000;
}

.sidebar-header {
    padding: 2rem 1.5rem;
    border-bottom: 1px solid #374151;
    text-align: center;
}

.sidebar-header h2 {
    font-size: 1.5rem;
    font-weight: 800;
    margin-bottom: 0.5rem;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
}

.sidebar-nav ul {
    list-style: none;
    padding: 0;
    margin: 0;
}

.sidebar-nav li a {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding: 1rem 1.5rem;
    color: #cbd5e1;
    text-decoration: none;
    transition: all 0.3s ease;
    font-weight: 500;
    border-left: 3px solid transparent;
}

.sidebar-nav li a:hover,
.sidebar-nav li a.active {
    background: linear-gradient(135deg, #374151 0%, #4b5563 100%);
    color: white;
    border-left-color: #3b82f6;
    transform: translateX(5px);
}

.admin-main {
    margin-left: 280px;
    flex: 1;
    min-height: 100vh;
}

.admin-header {
    background: white;
    padding: 2rem;
    border-bottom: 1px solid #e5e7eb;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.admin-header h1 {
    font-size: 2rem;
    font-weight: 800;
    color: #1f2937;
    margin-bottom: 0.5rem;
    display: flex;
    align-items: center;
    gap: 0.75rem;
}

.admin-content {
    padding: 2rem;
}

.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-outline-primary {
    background: transparent;
    border: 2px solid #667eea;
    color: #667eea;
}

.btn-outline-primary:hover {
    background: #667eea;
    color: white;
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(102, 126, 234, 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) {
    .admin-sidebar {
        transform: translateX(-100%);
        transition: transform 0.3s ease;
    }

    .admin-main {
        margin-left: 0;
    }

    .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) {
    .admin-header {
        padding: 1.5rem;
    }

    .admin-header h1 {
        font-size: 1.5rem;
    }

    .admin-content {
        padding: 1rem;
    }

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

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

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

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