<?php
include 'config.php';

// Handle new category creation
$category_message = "";
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()) {
            $category_message = "<div class='alert alert-success'>New category created successfully</div>";
        } else {
            $category_message = "<div class='alert alert-danger'>Error: " . $stmt->error . "</div>";
        }
        $stmt->close();
    } else {
        $category_message = "<div class='alert alert-danger'>Category name cannot be empty</div>";
    }
}

// Fetch categories
$sql_categories = "SELECT category_id, category_name FROM categories";
$result_categories = $conn->query($sql_categories);
$categories = [];
while ($row = $result_categories->fetch_assoc()) {
    $categories[] = $row;
}

// Handle new topic creation
$topic_message = "";
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()) {
            $topic_message = "<div class='alert alert-success'>New topic created successfully</div>";
        } else {
            $topic_message = "<div class='alert alert-danger'>Error: " . $stmt->error . "</div>";
        }
        $stmt->close();
    } else {
        $topic_message = "<div class='alert alert-danger'>Topic name and category cannot be empty</div>";
    }
}

// Fetch topics
$sql_topics = "SELECT topic_id, topic_name, category_id FROM topics";
$result_topics = $conn->query($sql_topics);
$topics = [];
while ($row = $result_topics->fetch_assoc()) {
    $topics[] = $row;
}

// Handle question creation
$question_message = "";
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();
            }

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

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

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Create Question</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script>
        $(document).ready(function() {
            const topics = <?= json_encode($topics); ?>;
            $('#category_id_question').change(function() {
                const categoryId = $(this).val();
                const filteredTopics = topics.filter(topic => topic.category_id == categoryId);
                $('#topic_id').empty().append('<option value="">Select Topic</option>');
                filteredTopics.forEach(topic => {
                    $('#topic_id').append(`<option value="${topic.topic_id}">${topic.topic_name}</option>`);
                });
            });
        });
    </script>
</head>
<body>
<div class="container mt-5">
    <h1>Create Question</h1>

    <!-- Create Category Section -->
    <?= $category_message ?>
    <div class="form-section">
        <h2>Create Category</h2>
        <form method="post" action="">
            <div class="form-group">
                <label for="new_category_name">New Category Name:</label>
                <input type="text" id="new_category_name" name="new_category_name" class="form-control" required>
            </div>
            <button type="submit" name="create_category" class="btn btn-primary">Create Category</button>
        </form>
    </div>

    <hr>

    <!-- Create Topic Section -->
    <?= $topic_message ?>
    <div class="form-section">
        <h2>Create Topic</h2>
        <form method="post" action="">
            <div class="form-group">
                <label for="new_topic_name">New Topic Name:</label>
                <input type="text" id="new_topic_name" name="new_topic_name" class="form-control" required>
            </div>
            <div class="form-group">
                <label for="category_id">Select Category:</label>
                <select id="category_id" name="category_id" class="form-control" required>
                    <option value="">Select Category</option>
                    <?php foreach ($categories as $category): ?>
                        <option value="<?= $category['category_id']; ?>">
                            <?= htmlspecialchars($category['category_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <button type="submit" name="create_topic" class="btn btn-primary">Create Topic</button>
        </form>
    </div>

    <hr>

    <!-- Create Question Section -->
    <?= $question_message ?>
    <div class="form-section">
        <h2>Create Question</h2>
        <form method="post" action="">
            <div class="form-group">
                <label for="question_text">Question:</label>
                <input type="text" id="question_text" name="question_text" class="form-control" required>
            </div>
            <div class="form-group">
                <label for="category_id_question">Select Category:</label>
                <select id="category_id_question" name="category_id_question" class="form-control" required>
                    <option value="">Select Category</option>
                    <?php foreach ($categories as $category): ?>
                        <option value="<?= $category['category_id']; ?>">
                            <?= htmlspecialchars($category['category_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label for="topic_id">Select Topic:</label>
                <select id="topic_id" name="topic_id" class="form-control" required>
                    <option value="">Select Topic</option>
                </select>
            </div>
            <div class="form-group">
                <label>Options:</label>
                <div class="input-group mb-2">
                    <input type="text" name="options[]" class="form-control" required>
                    <div class="input-group-append">
                        <div class="input-group-text">
                            <input type="radio" name="correct_option" value="0" required>
                        </div>
                    </div>
                </div>
                <div class="input-group mb-2">
                    <input type="text" name="options[]" class="form-control" required>
                    <div class="input-group-append">
                        <div class="input-group-text">
                            <input type="radio" name="correct_option" value="1" required>
                        </div>
                    </div>
                </div>
                <div class="input-group mb-2">
                    <input type="text" name="options[]" class="form-control" required>
                    <div class="input-group-append">
                        <div class="input-group-text">
                            <input type="radio" name="correct_option" value="2" required>
                        </div>
                    </div>
                </div>
                <div class="input-group mb-2">
                    <input type="text" name="options[]" class="form-control" required>
                    <div class="input-group-append">
                        <div class="input-group-text">
                            <input type="radio" name="correct_option" value="3" required>
                        </div>
                    </div>
                </div>
            </div>
            <button type="submit" name="create_question" class="btn btn-primary">Create Question</button>
        </form>
    </div>
</div>
</body>
</html>
