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

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

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

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

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

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

        try {
            $DBH->beginTransaction();
            
            foreach ($_POST['questions'] as $index => $question) {
                $question_text = $question['question_text'];
                $option_a = $question['option_a'];
                $option_b = $question['option_b'];
                $option_c = $question['option_c'];
                $option_d = $question['option_d'];
                $correct_answer = $question['correct_answer'];

                // Handle file upload (same as before)
                $file_path = null;
                if (!empty($_FILES['questions']['name'][$index]['file'])) {
                    $file = $_FILES['questions']['tmp_name'][$index]['file'];
                    $file_name = $_FILES['questions']['name'][$index]['file'];
                    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                
                    $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx'];
                    if (in_array($file_ext, $allowed_extensions)) {
                        $upload_dir = $_SERVER['DOCUMENT_ROOT'] . '/portal/coll_admin/uploads/questions/';
                        if (!is_dir($upload_dir)) {
                            mkdir($upload_dir, 0777, true);
                        }
                
                        $file_path = $upload_dir . uniqid() . '_' . basename($file_name);
                        if (!move_uploaded_file($file, $file_path)) {
                            throw new Exception("Failed to upload file");
                        }
                    } else {
                        throw new Exception("Invalid file type");
                    }
                }

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

            $DBH->commit();
            
            $_SESSION['success'] = "Questions submitted successfully!";
            unset($_SESSION['exam_subject_id']);
            unset($_SESSION['subject_id']);
            unset($_SESSION['exam_class_ids']);
            
        } catch (Exception $e) {
            $DBH->rollBack();
            $_SESSION['error'] = "Error: " . $e->getMessage();
        }
        
        header("Location: set_questions.php");
        exit();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Set Questions - VERBUM DEI INT'L COLLEGE, OWERRI 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">
    
    <!-- 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;
        }
        
        .action-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 20px rgba(0,0,0,0.15);
        }
        
        .btn-exam {
            background-color: var(--primary-green);
            color: white;
        }
        
        .form-control:focus {
            border-color: var(--primary-green);
            box-shadow: 0 0 0 0.25rem rgba(46, 125, 50, 0.25);
        }
        
        .file-preview {
            width: 200px;
            height: 150px;
            border: 2px dashed #ccc;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            margin: 10px auto;
            background-color: #f9f9f9;
        }

        .file-preview img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }

        .file-preview embed {
            width: 100%;
            height: 100%;
        }

        .file-preview a {
            text-align: center;
            color: #007bff;
            text-decoration: none;
        }

        .file-preview a:hover {
            text-decoration: underline;
        }
        
        .img-fluid {
            width: 100px;
            height: 100px;
        }
        
        .selected-classes {
            background-color: #f8f9fa;
            border-radius: 5px;
            padding: 10px;
            margin-bottom: 15px;
        }
        
        .class-badge {
            margin-right: 5px;
            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="VDA Logo" class="img-fluid">
                    </div>
                    <div>
                        <h1 class="h4 mb-0">VERBUM DEI INT'L COLLEGE, OWERRI CBT Management</h1>
                        <small class="text-muted">Set Exam Questions</small>
                    </div>
                </div>
                <div class="dropdown">
                    <button class="btn btn-outline-secondary dropdown-toggle" type="button" id="adminDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="fas fa-user-circle me-1"></i> <?= htmlspecialchars($_SESSION['SESS_FULLNAME_ADMIN']) ?>
                    </button>
                    <ul class="dropdown-menu" aria-labelledby="adminDropdown">
                        <li><a class="dropdown-item" href="cbt_admin_home.php"><i class="fas fa-tachometer-alt me-2"></i> Dashboard</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="../admin/logout.php"><i class="fas fa-sign-out-alt me-2"></i> Logout</a></li>
                    </ul>
                </div>
            </div>
        </div>
    </header>

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

                        <!-- Selection Section -->
                        <?php if (!isset($_SESSION['exam_subject_id'])): ?>
                            <form method="POST" id="selectionForm">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="exam_subject_id" class="form-label">Select Exam Subject</label>
                                        <select name="exam_subject_id" class="form-select" required>
                                            <option value="">-- Select Exam Subject --</option>
                                            <?php foreach ($exam_subjects as $es): ?>
                                                <option value="<?= $es['id'] ?>"><?= $es['exam_name'] . ' - ' . $es['subject'] ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="exam_class_id" class="form-label">Select Exam-Class(es)</label>
                                        <select name="exam_class_id[]" class="form-select" multiple="multiple" required>
                                            <?php foreach ($exam_classes as $ec): ?>
                                                <option value="<?= $ec['id'] ?>" <?= (isset($_SESSION['exam_class_id']) && in_array($ec['id'], (array)$_SESSION['exam_class_id'])) ? 'selected' : '' ?>>
                                                    <?= $ec['exam_name'] . ' - ' . $ec['class'] . ' (' . $ec['term'] . ' ' . $ec['session'] . ')' ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <small class="text-muted">Hold CTRL/CMD to select multiple classes</small>
                                    </div>
                                </div>
                                
                                <div class="d-grid gap-2">
                                    <button type="submit" name="confirm_selection" class="btn btn-exam">
                                        <i class="fas fa-check-circle me-2"></i> Confirm Selections
                                    </button>
                                    <a href="cbt_admin_home.php" class="btn btn-outline-secondary">
                                        <i class="fas fa-arrow-left me-2"></i> Back to Dashboard
                                    </a>
                                </div>
                            </form>
                        <?php else: ?>
                            <!-- Question Section -->
                            <form method="POST" enctype="multipart/form-data" id="questionForm">
                                <?php 
                                    $current_es = $exam_subjects[array_search($_SESSION['exam_subject_id'], array_column($exam_subjects, 'id'))];
                                ?>
                                <div class="alert alert-info mb-4">
                                    <strong>Exam Subject:</strong> <?= $current_es['exam_name'] . ' - ' . $current_es['subject'] ?><br><br>
                                    
                                    <strong>Selected Classes:</strong>
                                    <div class="selected-classes mt-2">
                                        <?php foreach ((array)$_SESSION['exam_class_ids'] as $exam_class_id): 
                                            $ec = $exam_classes[array_search($exam_class_id, array_column($exam_classes, 'id'))];
                                        ?>
                                            <span class="badge bg-primary class-badge">
                                                <?= $ec['exam_name'] . ' - ' . $ec['class'] . ' (' . $ec['term'] . ' ' . $ec['session'] . ')' ?>
                                            </span>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                
                                <div id="question-section">
                                    <!-- Questions will be dynamically added here -->
                                </div>
                                
                                <div class="d-grid gap-2">
                                    <button type="button" onclick="addQuestion()" class="btn btn-secondary">
                                        <i class="fas fa-plus-circle me-2"></i> Add Question
                                    </button>
                                    <button type="submit" name="submit_questions" class="btn btn-success">
                                        <i class="fas fa-save me-2"></i> Submit All Questions
                                    </button>
                                    <a href="cbt_admin_home.php" class="btn btn-outline-danger">
                                        <i class="fas fa-times-circle me-2"></i> Cancel & Back to Dashboard
                                    </a>
                                </div>
                            </form>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

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

    <!-- JavaScript Libraries -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <script>
        function addQuestion() {
            const questionSection = document.getElementById('question-section');
            const questionCount = questionSection.querySelectorAll('.question-group').length;
            const questionTemplate = `
                <div class="question-group mb-4 p-3 border rounded">
                    <h5 class="mb-3">Question ${questionCount + 1}</h5>
                    <div class="mb-3">
                        <label class="form-label">Question Text</label>
                        <textarea name="questions[${questionCount}][question_text]" class="form-control" rows="3" required></textarea>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Option A</label>
                            <input type="text" name="questions[${questionCount}][option_a]" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Option B</label>
                            <input type="text" name="questions[${questionCount}][option_b]" class="form-control" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Option C</label>
                            <input type="text" name="questions[${questionCount}][option_c]" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Option D</label>
                            <input type="text" name="questions[${questionCount}][option_d]" class="form-control" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Correct Answer</label>
                            <select name="questions[${questionCount}][correct_answer]" class="form-select" required>
                                <option value="A">A</option>
                                <option value="B">B</option>
                                <option value="C">C</option>
                                <option value="D">D</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Upload File (Image, PDF, Word)</label>
                            <input type="file" name="questions[${questionCount}][file]" class="form-control file-input" onchange="previewFile(this)">
                            <div class="file-preview mt-2"></div>
                        </div>
                    </div>
                    <button type="button" class="btn btn-sm btn-danger remove-question" onclick="removeQuestion(this)">
                        <i class="fas fa-trash-alt me-1"></i> Remove Question
                    </button>
                    <hr>
                </div>
            `;
            questionSection.insertAdjacentHTML('beforeend', questionTemplate);
        }
        
        function removeQuestion(button) {
            if (confirm('Are you sure you want to remove this question?')) {
                button.closest('.question-group').remove();
                // Renumber remaining questions
                const questions = document.querySelectorAll('.question-group');
                questions.forEach((question, index) => {
                    question.querySelector('h5').textContent = `Question ${index + 1}`;
                });
            }
        }

        function previewFile(input) {
            const file = input.files[0];
            const previewDiv = input.parentElement.querySelector('.file-preview');

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

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

        // Add first question automatically when in question entry mode
        <?php if (isset($_SESSION['subject_id'])): ?>
            document.addEventListener('DOMContentLoaded', function() {
                addQuestion();
            });
        <?php endif; ?>

        // Form validation
        document.getElementById('selectionForm')?.addEventListener('submit', function(e) {
            const selectedClasses = this.querySelector('[name="exam_class_id[]"]');
            if (selectedClasses.selectedOptions.length === 0) {
                alert('Please select at least one exam-class combination');
                e.preventDefault();
            }
        });

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