<?php
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

require_once '../config.php';
require_once '../lib/exam_utils.php';

function buildFallbackQuestion($sectionType, $subjectName, $seedText, $marks, $number) {
    $base = trim($seedText) !== '' ? $seedText : ('core ' . $subjectName . ' concept');
    if ($sectionType === 'objective') {
        return [
            'number' => $number,
            'text' => 'Which option best matches ' . $base . '?',
            'marks' => $marks,
            'options' => [
                'A' => 'The best matching answer for ' . $base,
                'B' => 'A related but incomplete answer',
                'C' => 'A common misunderstanding',
                'D' => 'An incorrect answer'
            ]
        ];
    }
    return [
        'number' => $number,
        'text' => 'Explain ' . $base . ' with clear examples.',
        'marks' => $marks
    ];
}

$examId = (int) ($_POST['exam_id'] ?? 0);
$mode = trim((string) ($_POST['mode'] ?? 'question'));
$sectionIndex = (int) ($_POST['section_index'] ?? -1);
$questionIndex = (int) ($_POST['question_index'] ?? -1);

$exam = loadExamRecord($examId);
if (!$exam) {
    echo json_encode(['success' => false, 'message' => 'Exam not found.']);
    exit;
}

$examData = is_array($exam['exam_data'] ?? null) ? $exam['exam_data'] : [];
if (!isset($examData['sections'][$sectionIndex])) {
    echo json_encode(['success' => false, 'message' => 'Section not found.']);
    exit;
}

$section = $examData['sections'][$sectionIndex];
$sectionType = $section['type'] ?? 'subjective';
$bankItems = getQuestionBankItems($exam['class_name'], (int) $exam['subject_id'], $sectionType, 20);
$bankCursor = 0;

$takeBankQuestion = function () use (&$bankItems, &$bankCursor, $sectionType, $exam) {
    while (isset($bankItems[$bankCursor])) {
        $item = $bankItems[$bankCursor++];
        if (($item['question_type'] ?? '') !== $sectionType) {
            continue;
        }
        markQuestionBankUsage((int) $item['id']);
        $question = [
            'text' => $item['question_text'],
            'marks' => (int) $item['marks']
        ];
        if ($sectionType === 'objective') {
            $question['options'] = $item['options'] ?: [
                'A' => 'Option A',
                'B' => 'Option B',
                'C' => 'Option C',
                'D' => 'Option D'
            ];
        }
        return $question;
    }
    return null;
};

if ($mode === 'question') {
    if (!isset($section['questions'][$questionIndex])) {
        echo json_encode(['success' => false, 'message' => 'Question not found.']);
        exit;
    }
    $currentQuestion = $section['questions'][$questionIndex];
    $replacement = $takeBankQuestion();
    if (!$replacement) {
        $replacement = buildFallbackQuestion($sectionType, $exam['subject_name'], $currentQuestion['text'] ?? '', (int) ($currentQuestion['marks'] ?? 2), (int) ($currentQuestion['number'] ?? ($questionIndex + 1)));
    }
    $replacement['number'] = (int) ($currentQuestion['number'] ?? ($questionIndex + 1));
    $examData['sections'][$sectionIndex]['questions'][$questionIndex] = $replacement;
    $message = 'Question regenerated.';
} else {
    foreach (($section['questions'] ?? []) as $index => $question) {
        $replacement = $takeBankQuestion();
        if (!$replacement) {
            $replacement = buildFallbackQuestion($sectionType, $exam['subject_name'], $question['text'] ?? '', (int) ($question['marks'] ?? 2), (int) ($question['number'] ?? ($index + 1)));
        }
        $replacement['number'] = (int) ($question['number'] ?? ($index + 1));
        $examData['sections'][$sectionIndex]['questions'][$index] = $replacement;
    }
    $message = 'Section regenerated.';
}

$examData = normalizeExamData($examData, [
    'exam_title' => $exam['title'],
    'subject_name' => $exam['subject_name'],
    'class_name' => $exam['class_name'],
    'duration' => $exam['duration_minutes'],
    'total_marks' => $exam['total_marks']
]);

echo json_encode([
    'success' => true,
    'message' => $message,
    'exam_data' => $examData
]);

