<?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_admin.php');

// Check if question ID is provided
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    $_SESSION['error'] = "Invalid question ID.";
    header("Location: manage_questions.php");
    exit();
}

$question_id = $_GET['id'];

// Fetch question details
try {
    $stmt = $DBH->prepare("
        SELECT q.*, ec.class, ec.term, ec.session, e.exam_name, s.subject 
        FROM tbl_question q
        JOIN tbl_exam_class ec ON q.exam_class_id = ec.id
        JOIN tbl_exam e ON ec.exam_id = e.id
        JOIN tbl_subject s ON q.subject_id = s.id
        WHERE q.id = :id
    ");
    $stmt->execute(['id' => $question_id]);
    $question = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$question) {
        $_SESSION['error'] = "Question not found.";
        header("Location: manage_questions.php");
        exit();
    }
} catch (PDOException $e) {
    $_SESSION['error'] = "Database error: " . $e->getMessage();
    header("Location: manage_questions.php");
    exit();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $question_text = trim($_POST['question_text']);
    $option_a = trim($_POST['option_a']);
    $option_b = trim($_POST['option_b']);
    $option_c = trim($_POST['option_c']);
    $option_d = trim($_POST['option_d']);
    $correct_answer = $_POST['correct_answer'];
    $instructions = trim($_POST['instructions']);

    // Validate required fields
    if (empty($question_text) || empty($option_a) || empty($option_b) || empty($correct_answer)) {
        $_SESSION['error'] = "Question text, options A, B, and correct answer are required.";
    } else {
        try {
            $update_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,
                    instructions = :instructions
                WHERE id = :id
            ");

            $update_stmt->execute([
                'question_text' => $question_text,
                'option_a' => $option_a,
                'option_b' => $option_b,
                'option_c' => $option_c,
                'option_d' => $option_d,
                'correct_answer' => $correct_answer,
                'instructions' => $instructions,
                'id' => $question_id
            ]);

            $_SESSION['success'] = "Question updated successfully!";
            header("Location: manage_questions.php");
            exit();
        } catch (PDOException $e) {
            $_SESSION['error'] = "Database error: " . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Question - VICTORY GROUP OF SCHOOLS 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">
    
    <!-- Quill.js CSS -->
    <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
    
    <!-- Custom CSS -->
    <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;
        }
        
        .btn-primary {
            background-color: var(--primary-green);
            border-color: var(--primary-green);
        }
        
        .btn-primary:hover {
            background-color: var(--dark-green);
            border-color: var(--dark-green);
        }
        
        .form-control:focus, .form-select: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-info {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .ql-editor {
            min-height: 100px;
            font-size: 14px;
        }
        
        .ql-container {
            border-radius: 0 0 5px 5px;
        }
        
        .ql-toolbar {
            border-radius: 5px 5px 0 0;
        }
        
        .editor-container {
            margin-bottom: 15px;
        }
        
        .option-editor {
            margin-bottom: 15px;
        }
        
        .option-label {
            font-weight: bold;
            color: var(--primary-green);
            margin-bottom: 5px;
        }
    </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="VICTORY Logo" class="img-fluid">
                    </div>
                    <div>
                        <h1 class="h4 mb-0">VICTORY GROUP OF SCHOOLS CBT Management</h1>
                        <small class="text-muted">Edit Question</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><a class="dropdown-item" href="manage_questions.php"><i class="fas fa-arrow-left me-2"></i> Back to Questions</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 Question</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; ?>

                        <!-- Question Information -->
                        <div class="question-info">
                            <h5>Question Details</h5>
                            <div class="row">
                                <div class="col-md-3"><strong>Exam:</strong> <?= $question['exam_name'] ?></div>
                                <div class="col-md-3"><strong>Subject:</strong> <?= $question['subject'] ?></div>
                                <div class="col-md-2"><strong>Class:</strong> <?= $question['class'] ?></div>
                                <div class="col-md-2"><strong>Term:</strong> <?= $question['term'] ?></div>
                                <div class="col-md-2"><strong>Session:</strong> <?= $question['session'] ?></div>
                            </div>
                        </div>

                        <form method="POST" id="questionForm">
                            <!-- Question Text Editor -->
                            <div class="editor-container">
                                <label class="form-label">Question Text</label>
                                <div id="question_editor" style="height: 150px;"><?= $question['question_text'] ?></div>
                                <input type="hidden" name="question_text" id="question_input">
                            </div>

                            <!-- Options Editors -->
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="option-editor">
                                        <div class="option-label">Option A</div>
                                        <div id="option_a_editor" style="height: 100px;"><?= $question['option_a'] ?></div>
                                        <input type="hidden" name="option_a" id="option_a_input">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="option-editor">
                                        <div class="option-label">Option B</div>
                                        <div id="option_b_editor" style="height: 100px;"><?= $question['option_b'] ?></div>
                                        <input type="hidden" name="option_b" id="option_b_input">
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="option-editor">
                                        <div class="option-label">Option C</div>
                                        <div id="option_c_editor" style="height: 100px;"><?= $question['option_c'] ?></div>
                                        <input type="hidden" name="option_c" id="option_c_input">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="option-editor">
                                        <div class="option-label">Option D</div>
                                        <div id="option_d_editor" style="height: 100px;"><?= $question['option_d'] ?></div>
                                        <input type="hidden" name="option_d" id="option_d_input">
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="correct_answer" class="form-label">Correct Answer</label>
                                    <select name="correct_answer" id="correct_answer" class="form-select" required>
                                        <option value="A" <?= $question['correct_answer'] == 'A' ? 'selected' : '' ?>>Option A</option>
                                        <option value="B" <?= $question['correct_answer'] == 'B' ? 'selected' : '' ?>>Option B</option>
                                        <option value="C" <?= $question['correct_answer'] == 'C' ? 'selected' : '' ?>>Option C</option>
                                        <option value="D" <?= $question['correct_answer'] == 'D' ? 'selected' : '' ?>>Option D</option>
                                    </select>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="instructions" class="form-label">Instructions (Optional)</label>
                                    <textarea name="instructions" id="instructions" class="form-control" rows="3"><?= htmlspecialchars($question['instructions'] ?? '') ?></textarea>
                                </div>
                            </div>

                            <!-- Current File Preview -->
                            <?php if (!empty($question['file_path'])): ?>
                                <div class="mb-4">
                                    <label class="form-label">Current Attached File</label>
                                    <div class="alert alert-info">
                                        <i class="fas fa-paperclip me-2"></i>
                                        <strong>Current File:</strong> 
                                        <a href="<?= $question['file_path'] ?>" target="_blank" class="alert-link">
                                            View Attached File
                                        </a>
                                        <br>
                                        <small class="text-muted">To change the file, you'll need to delete and re-create the question with the new file.</small>
                                    </div>
                                </div>
                            <?php endif; ?>

                            <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                                <a href="manage_questions.php" class="btn btn-outline-secondary me-md-2">
                                    <i class="fas fa-arrow-left me-2"></i> Cancel
                                </a>
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save me-2"></i> Update Question
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <footer class="footer mt-5 py-3 bg-dark text-white">
        <div class="container">
            <div class="row">
                <div class="col-md-8">
                    <p class="mb-1">VICTORY GROUP OF SCHOOLS, ABA</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>
    
    <!-- Quill.js -->
    <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
    
    <script>
        // Initialize Quill editors
        const quillConfig = {
            modules: {
                toolbar: [
                    ['bold', 'italic', 'underline', 'strike'],
                    [{ 'color': [] }, { 'background': [] }],
                    [{ 'size': ['small', false, 'large', 'huge'] }],
                    [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                    [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                    [{ 'align': [] }],
                    ['blockquote', 'code-block'],
                    ['clean']
                ]
            },
            theme: 'snow'
        };

        // Initialize question editor
        const questionEditor = new Quill('#question_editor', quillConfig);
        
        // Initialize option editors
        const optionAEditor = new Quill('#option_a_editor', quillConfig);
        const optionBEditor = new Quill('#option_b_editor', quillConfig);
        const optionCEditor = new Quill('#option_c_editor', quillConfig);
        const optionDEditor = new Quill('#option_d_editor', quillConfig);

        // Handle form submission - update hidden inputs with Quill content
        document.getElementById('questionForm').addEventListener('submit', function(e) {
            // Update hidden inputs with Quill content
            document.getElementById('question_input').value = questionEditor.root.innerHTML;
            document.getElementById('option_a_input').value = optionAEditor.root.innerHTML;
            document.getElementById('option_b_input').value = optionBEditor.root.innerHTML;
            document.getElementById('option_c_input').value = optionCEditor.root.innerHTML;
            document.getElementById('option_d_input').value = optionDEditor.root.innerHTML;

            // Validate required fields
            const questionText = questionEditor.getText().trim();
            const optionAText = optionAEditor.getText().trim();
            const optionBText = optionBEditor.getText().trim();
            
            if (!questionText) {
                alert('Question text is required');
                e.preventDefault();
                return;
            }
            
            if (!optionAText) {
                alert('Option A is required');
                e.preventDefault();
                return;
            }
            
            if (!optionBText) {
                alert('Option B is required');
                e.preventDefault();
                return;
            }
        });

        // Format the existing content to display properly in Quill
        document.addEventListener('DOMContentLoaded', function() {
            // The content is already set in the HTML, Quill will render it automatically
        });
    </script>
</body>
</html>