<?php
session_start();
include 'includes/database.php';
include 'includes/functions.php';
$conn= new Functions();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $exam_id = $_POST['exam_id'];
        $question_type = $_POST['question_type'];
        $question_text = trim($_POST['question_text']);

        // Set the correct answer based on the question type
        if ($question_type === 'fill_blank') {
            $correct_answer = $_POST['fill_blank_text'] ?? null;
        } elseif ($question_type === 'true_false') {
            $correct_answer = $_POST['true_false_answer'] ?? null;
        } else {
            $correct_answer = null;
        }

        if (empty($question_text)) {
            throw new Exception("Question text cannot be empty.");
        }

        // Prevent duplicate question text
        $conn->query("SELECT COUNT(*) FROM cbt_questions WHERE exam_id = :exam_id AND question_text = :question_text");
        $conn->bind(':exam_id', $exam_id);
        $conn->bind(':question_text', $question_text);
        $count = $conn->fetchColumn();
        if ($count > 0) {
            throw new Exception("Duplicate question detected. Question already exists.");
        }

        // Validate answers before inserting
        if ($question_type === 'fill_blank' && empty($correct_answer)) {
            throw new Exception("Fill-in-the-blank answer is required.");
        }
        if ($question_type === 'true_false' && empty($correct_answer)) {
            throw new Exception("Please select True or False.");
        }

        // Handle image upload
        $image_path = null;
        if (!empty($_FILES['question_image']['name'])) {
            $image_name = time() . '_' . $_FILES['question_image']['name'];
            $target_dir = "upload/questions/";
            $target_file = $target_dir . basename($image_name);

            if (move_uploaded_file($_FILES['question_image']['tmp_name'], $target_file)) {
                $image_path = $target_file;
            }
        }

        // Insert question into `cbt_questions`
        $sql = "INSERT INTO cbt_questions (exam_id, question_type, question_text, question_image) 
                VALUES (:exam_id, :question_type, :question_text, :question_image)";
        $conn->query($sql);
        $conn->bind(':exam_id', $exam_id);
        $conn->bind(':question_type', $question_type);
        $conn->bind(':question_text', $question_text);
        $conn->bind(':question_image', $image_path);
        $conn->execute();

        $question_id = $conn->lastInserted();

        // Handle MCQ options
        if ($question_type === 'mcq') {
            if (empty($_POST['options'])) {
                throw new Exception("MCQ must have options.");
            }
            if (!isset($_POST['correct_option'])) {
                throw new Exception("Please select a correct answer for MCQ.");
            }

            foreach ($_POST['options'] as $index => $option_text) {
                $is_correct = ($_POST['correct_option'] == $index) ? 1 : 0;

                $sql = "INSERT INTO cbt_options (question_id, option_text, is_correct) 
                        VALUES (:question_id, :option_text, :is_correct)";
                $conn->query($sql);
                $conn->bind(':question_id', $question_id);
                $conn->bind(':option_text', $option_text);
                $conn->bind(':is_correct', $is_correct);
                $conn->execute();
            }
        }

        // Insert Fill-in-the-Blank Answer
        if ($question_type === 'fill_blank') {
            $sql = "INSERT INTO cbt_options (question_id, option_text, is_correct) 
                    VALUES (:question_id, :option_text, 1)";
            $conn->query($sql);
            $conn->bind(':question_id', $question_id);
            $conn->bind(':option_text', $correct_answer);
            $conn->execute();
        }

        // Insert True/False Answer
        if ($question_type === 'true_false') {
            $sql = "INSERT INTO cbt_options (question_id, option_text, is_correct) 
                    VALUES (:question_id, :option_text, 1)";
            $conn->query($sql);
            $conn->bind(':question_id', $question_id);
            $conn->bind(':option_text', $correct_answer);
            $conn->execute();
        }

        echo json_encode(['status' => 'success', 'message' => 'Question added successfully']);
    } catch (Exception $e) {
        if ($e->getCode() === '23000') { // Unique constraint violation
            echo json_encode(['status' => 'error', 'message' => 'Duplicate question detected by DB.']);
        } else {
            echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
        }
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
}