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

// Fetch available subjects
$stmt_subjects = $DBH->query("SELECT * FROM tbl_subject");
$subjects = $stmt_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);

// Check if exam_class_id is passed via query parameter
if (isset($_GET['exam_class_id'])) {
    $_SESSION['exam_class_id'] = $_GET['exam_class_id'];
}

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

        // Store selections in session for use in the question section
        $_SESSION['subject_id'] = $subject_id;
        $_SESSION['exam_class_id'] = $exam_class_id;
    } elseif (isset($_POST['submit_questions'])) {
        // Handle question submission
        $subject_id = $_SESSION['subject_id'];
        $exam_class_id = $_SESSION['exam_class_id'];

        // Loop through all submitted questions
        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
            $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));
            
                // Validate file type (images, PDFs, Word documents)
                $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);
                    move_uploaded_file($file, $file_path);
                } else {
                    $error = "Invalid file type. Allowed types: JPG, JPEG, PNG, GIF, PDF, DOC, DOCX.";
                    break;
                }
            }

            // Insert question into tbl_question
            $stmt = $DBH->prepare("
                INSERT INTO tbl_question (exam_class_id, subject_id, question_text, option_a, option_b, option_c, option_d, correct_answer, file_path) 
                VALUES (:exam_class_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,
                '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
            ]);
        }

        if (!isset($error)) {
            $success = "Questions submitted successfully!";
            unset($_SESSION['subject_id']);
            unset($_SESSION['exam_class_id']);
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Set Questions - CBT Portal</title>
    <link rel="stylesheet" href="../assets/css/bootstrap.min.css">
<style>
    .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; /* Center the container */
        background-color: #f9f9f9;
    }

    .file-preview img {
        max-width: 100%;
        max-height: 100%;
        object-fit: contain; /* Ensure the image fits within the container */
    }

    .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;
    }
</style>

<script>
    function addQuestion() {
        const questionSection = document.getElementById('question-section');
        const questionTemplate = `
            <div class="question-group mb-4">
                <div class="form-group">
                    <label>Question</label>
                    <textarea name="questions[${questionSection.children.length}][question_text]" class="form-control" rows="3" required></textarea>
                </div>
                <div class="form-group">
                    <label>Option A</label>
                    <input type="text" name="questions[${questionSection.children.length}][option_a]" class="form-control" required>
                </div>
                <div class="form-group">
                    <label>Option B</label>
                    <input type="text" name="questions[${questionSection.children.length}][option_b]" class="form-control" required>
                </div>
                <div class="form-group">
                    <label>Option C</label>
                    <input type="text" name="questions[${questionSection.children.length}][option_c]" class="form-control" required>
                </div>
                <div class="form-group">
                    <label>Option D</label>
                    <input type="text" name="questions[${questionSection.children.length}][option_d]" class="form-control" required>
                </div>
                <div class="form-group">
                    <label>Correct Answer</label>
                    <select name="questions[${questionSection.children.length}][correct_answer]" class="form-control" 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="form-group">
                    <label>Upload File (Image, PDF, Word)</label>
                    <input type="file" name="questions[${questionSection.children.length}][file]" class="form-control file-input" onchange="previewFile(this)">
                    <div class="file-preview mt-2"></div>
                </div>
                <button type="button" class="btn btn-danger btn-sm remove-question" onclick="removeQuestion(this)">Remove Question</button>
                <hr>
            </div>
        `;
        questionSection.insertAdjacentHTML('beforeend', questionTemplate);
    }
    
    function removeQuestion(button) {
        button.closest('.question-group').remove();
    }

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/')) {
                // Display image preview
                previewDiv.innerHTML = `<img src="${e.target.result}" alt="File Preview">`;
            } else if (fileType === 'application/pdf') {
                // Display PDF preview (embed or link)
                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') {
                // Display Word document preview (link)
                previewDiv.innerHTML = `<p><a href="${e.target.result}" target="_blank">Download Word Document</a></p>`;
            } else {
                // Unsupported file type
                previewDiv.innerHTML = `<p class="text-danger">Unsupported file type.</p>`;
            }
        };
        reader.readAsDataURL(file);
    } else {
        previewDiv.innerHTML = '';
    }
}
</script>
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h3 class="text-center">Set Questions</h3>
                    </div>
                    <div class="card-body">
                        <?php if (isset($error)): ?>
                            <div class="alert alert-danger"><?php echo $error; ?></div>
                        <?php endif; ?>
                        <?php if (isset($success)): ?>
                            <div class="alert alert-success"><?php echo $success; ?></div>
                        <?php endif; ?>

                        <!-- Selection Section -->
                        <?php if (!isset($_SESSION['subject_id'])): ?>
                            <form method="POST">
                                <div class="form-group">
                                    <label for="subject_id">Select Subject</label>
                                    <select name="subject_id" class="form-control" required>
                                        <option value="">-- Select Subject --</option>
                                        <?php foreach ($subjects as $subject): ?>
                                            <option value="<?php echo $subject['id']; ?>"><?php echo $subject['subject']; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="exam_class_id">Select Exam-Class</label>
                                    <select name="exam_class_id" class="form-control" required>
                                        <option value="">-- Select Exam-Class --</option>
                                        <?php foreach ($exam_classes as $ec): ?>
                                            <option value="<?php echo $ec['id']; ?>" <?php echo (isset($_SESSION['exam_class_id']) && $_SESSION['exam_class_id'] == $ec['id']) ? 'selected' : ''; ?>>
                                                <?php echo $ec['exam_name'] . ' - ' . $ec['class'] . ' (' . $ec['term'] . ' ' . $ec['session'] . ')'; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <button type="submit" name="confirm_selection" class="btn btn-primary btn-block">Confirm Subject & Class Selections</button>
                            </form>
                        <?php else: ?>
                            <!-- Question Section -->
                            <form method="POST" enctype="multipart/form-data">
                                <div id="question-section">
                                    <!-- Questions will be dynamically added here -->
                                </div>
                                <button type="button" onclick="addQuestion()" class="btn btn-secondary mb-3">Add Question</button>
                                <button type="submit" name="submit_questions" class="btn btn-success btn-block">Submit Questions</button>
                            </form>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>