<?php
include 'config.php';

// Handle new category creation
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['create_category'])) {
    $new_category_name = $_POST['new_category_name'];
    if (!empty($new_category_name)) {
        $sql = "INSERT INTO categories (category_name) VALUES (?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("s", $new_category_name);
        if ($stmt->execute()) {
            echo "<div class='alert alert-success'>New category created successfully</div>";
        } else {
            echo "<div class='alert alert-danger'>Error: " . $stmt->error . "</div>";
        }
        $stmt->close();
    } else {
        echo "<div class='alert alert-danger'>Category name cannot be empty</div>";
    }
}

// Handle new topic creation
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['create_topic'])) {
    $new_topic_name = $_POST['new_topic_name'];
    $category_id = $_POST['category_id'];
    if (!empty($new_topic_name) && !empty($category_id)) {
        $sql = "INSERT INTO topics (topic_name, category_id) VALUES (?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("si", $new_topic_name, $category_id);
        if ($stmt->execute()) {
            echo "<div class='alert alert-success'>New topic created successfully</div>";
        } else {
            echo "<div class='alert alert-danger'>Error: " . $stmt->error . "</div>";
        }
        $stmt->close();
    } else {
        echo "<div class='alert alert-danger'>Topic name and category cannot be empty</div>";
    }
}

// Handle question creation
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['create_question'])) {
    $question_text = $_POST['question_text'];
    $options = $_POST['options'];
    $correct_option = $_POST['correct_option'];
    $topic_id = $_POST['topic_id'];

    if (!empty($question_text) && !empty($options) && isset($correct_option) && !empty($topic_id)) {
        $sql = "INSERT INTO questions (question_text, topic_id) VALUES (?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("si", $question_text, $topic_id);

        if ($stmt->execute()) {
            $question_id = $stmt->insert_id;

            foreach ($options as $key => $option_text) {
                $is_correct = ($key == $correct_option) ? 1 : 0;
                $sql = "INSERT INTO options (question_id, option_text, is_correct) VALUES (?, ?, ?)";
                $stmt = $conn->prepare($sql);
                $stmt->bind_param("isi", $question_id, $option_text, $is_correct);
                $stmt->execute();
            }

            echo "<div class='alert alert-success'>New question and options created successfully</div>";
        } else {
            echo "<div class='alert alert-danger'>Error: " . $stmt->error . "</div>";
        }

        $stmt->close();
    } else {
        echo "<div class='alert alert-danger'>All fields are required</div>";
    }
}

$conn->close();
?>
