<?php
include 'db.php'; // Database connection

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $question_text = $_POST['question_text'];
    $topic_id = $_POST['topic_id'];

    // Insert question
    $stmt = $pdo->prepare("INSERT INTO questions (question_text, topic_id) VALUES (?, ?)");
    if ($stmt->execute([$question_text, $topic_id])) {
        $question_id = $pdo->lastInsertId();

        // Insert options
        foreach ($_POST['options'] as $index => $option_text) {
            $is_correct = ($index == $_POST['correct_option']) ? 1 : 0;
            $stmt = $pdo->prepare("INSERT INTO options (question_id, option_text, is_correct) VALUES (?, ?, ?)");
            $stmt->execute([$question_id, $option_text, $is_correct]);
        }
        echo "Question and options added successfully!";
    } else {
        echo "Error adding question.";
    }
}

// Fetch topics for the dropdown
$topics = $pdo->query("SELECT * FROM topics")->fetchAll();
?>

<form method="POST">
    <label>Question: <input type="text" name="question_text" required></label><br>
    <label>Topic:
        <select name="topic_id">
            <?php foreach ($topics as $topic): ?>
                <option value="<?= $topic['id'] ?>"><?= $topic['name'] ?></option>
            <?php endforeach; ?>
        </select>
    </label><br>

    <label>Options:</label><br>
    <input type="text" name="options[]" required> <br>
    <input type="text" name="options[]" required> <br>
    <input type="text" name="options[]" required> <br>
    <input type="text" name="options[]" required> <br>

    <label>Correct Option (Enter index 0-3): <input type="number" name="correct_option" min="0" max="3" required></label><br>
    <input type="submit" value="Add Question">
</form>
