<?php
require 'config.php';
session_start();

$teacher_id = $_SESSION['teacher_id'] ?? null;
if (!$teacher_id) {
    echo "Unauthorized. Please log in as a teacher.";
    exit;
}

// Validate required fields
$session_id = $_POST['session_id'] ?? null;
$term_id    = $_POST['term_id'] ?? null;
$class_id   = $_POST['class_id'] ?? null;
$subject_id = $_POST['subject_id'] ?? null;
$type       = $_POST['type'] ?? null;
$set_time   = $_POST['set_time_minutes'] ?? null;

if (!$session_id || !$term_id || !$class_id || !$subject_id || !$type) {
    echo "Missing required fields.";
    exit;
}

try {
    $dbh->beginTransaction();

    $stmt = $dbh->prepare("INSERT INTO questions 
        (teacher_id, student_class, term_id, session_id, subject_id, type, question_text, options, correct_answer, set_time_minutes) 
        VALUES (:teacher_id, :class_id, :term_id, :session_id, :subject_id, :type, :question_text, :options, :correct_answer, :set_time)");

    $count = 0;

    foreach ($_POST['question_text'] as $index => $qText) {
        $qText = trim($qText);
        if ($qText === "") continue;

        $options = null;
        $correct = null;

        if ($type === 'objective') {
        // Get the options array for this question index
        $option = $_POST['options'][$index] ?? [];
    
        // Ensure it's always an array (even if user sent a single string)
        if (!is_array($option)) {
            $option = array_map('trim', explode(',', $option)); // split by comma if needed
        }
    
        // Convert to valid JSON format: ["Paris","London","Rome","Berlin"]
        $options = json_encode($option, JSON_UNESCAPED_UNICODE);
    
        // Get the correct answer
        $correct = $_POST['correct_answer'][$index] ?? null;
        } elseif ($type === 'fill') {
            $correct = $_POST['correct_answer_fill'][$index] ?? null;
        } elseif ($type === 'theory') {
            $correct = $_POST['theory_answer'][$index] ?? null;
        }

        $stmt->execute([
            ':teacher_id'   => $teacher_id,
            ':class_id'     => $class_id,
            ':term_id'      => $term_id,
            ':session_id'   => $session_id,
            ':subject_id'   => $subject_id,
            ':type'         => $type,
            ':question_text'=> $qText,
            ':options'      => $options,
            ':correct_answer'=> $correct,
            ':set_time'     => $set_time,
        ]);
        $count++;
    }

    $dbh->commit();
    echo "$count question(s) saved successfully.";
} catch (Exception $e) {
    $dbh->rollBack();
    echo "Error saving questions: " . $e->getMessage();
}
