<?php
session_start();
include('connection/config.php');

$question_level = $_SESSION['question_level'];
$question_ids = $_SESSION['question_ids'];

$currentIndex = isset($_GET['q_index']) ? intval($_GET['q_index']) : 0;

if (isset($question_ids[$currentIndex])) {
    $question_id = $question_ids[$currentIndex];

    $query = "SELECT * FROM $question_level WHERE id = ?";
    $stmt = $pdo->prepare($query);
    $stmt->execute([$question_id]);
    $question = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($question) {
        // Map the ans ('a', 'b', 'c', 'd') to 'option1', 'option2', etc
        $ans_mapping = [
            'a' => 'option1',
            'b' => 'option2',
            'c' => 'option3',
            'd' => 'option4'
        ];

        $correct_option_key = isset($ans_mapping[strtolower($question['ans'])]) ? $ans_mapping[strtolower($question['ans'])] : null;

        echo json_encode([
            'question_id' => $question['id'],
            'question_text' => $question['qst'],
            'options' => [
                'option1' => $question['opt1'],
                'option2' => $question['opt2'],
                'option3' => $question['opt3'],
                'option4' => $question['opt4']
            ],
            'correct_answer' => $correct_option_key  // mapped key
        ]);
    } else {
        echo json_encode(['error' => 'Question not found.']);
    }
} else {
    echo json_encode(['error' => 'Invalid question index.']);
}
?>
