<?php
require_once '../includes/db.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header('Location: /dashboard.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    check_csrf();
    $quiz_id = $_POST['quiz_id'];
    $course_id = $_POST['course_id'];
    $question_text = $_POST['question_text'];
    $options = $_POST['options'];
    $correct_option_index = $_POST['correct_option'];

    try {
        // 1. Masukkan pertanyaan
        $stmt_q = $pdo->prepare("INSERT INTO questions (quiz_id, question_text) VALUES (?, ?)");
        $stmt_q->execute([$quiz_id, $question_text]);
        $question_id = $pdo->lastInsertId();

        // 2. Masukkan opsi-opsinya
        $stmt_o = $pdo->prepare("INSERT INTO options (question_id, option_text, is_correct) VALUES (?, ?, ?)");
        foreach ($options as $index => $option_text) {
            $is_correct = ($index == $correct_option_index) ? 1 : 0;
            $stmt_o->execute([$question_id, $option_text, $is_correct]);
        }

    } catch (PDOException $e) {
        // Handle error
    }
    
    header("Location: manage_quiz.php?course_id=$course_id");
    exit;
}