<?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';

$examId = (int) ($_POST['exam_id'] ?? 0);
if ($examId <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid exam id.']);
    exit;
}

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

$decoded = json_decode((string) ($_POST['exam_data'] ?? ''), true);
if (!is_array($decoded)) {
    echo json_encode(['success' => false, 'message' => 'Invalid exam data provided.']);
    exit;
}

$requestData = [
    'exam_title' => trim((string) ($_POST['exam_title'] ?? $existing['title'])),
    'class_name' => $existing['class_name'],
    'subject_id' => (int) $existing['subject_id'],
    'subject_name' => $existing['subject_name'],
    'exam_type' => $existing['exam_type'],
    'term' => $existing['term'],
    'duration' => (int) ($_POST['duration'] ?? $existing['duration_minutes']),
    'total_marks' => (int) ($_POST['total_marks'] ?? $existing['total_marks'])
];

$normalized = normalizeExamData($decoded, $requestData);
$normalized = enrichExamAssessmentData($normalized, $requestData);
$validation = validateExamData($normalized, $requestData);
if (!$validation['valid']) {
    echo json_encode([
        'success' => false,
        'message' => 'Exam changes failed validation.',
        'details' => $validation['errors']
    ]);
    exit;
}

saveExamToDatabase($requestData, $normalized, (int) $_SESSION['user_id'], $examId, [
    'warnings' => $validation['warnings']
]);
$examRecord = loadExamRecord($examId);

echo json_encode([
    'success' => true,
    'message' => 'Exam saved successfully.',
    'exam_id' => $examId,
    'status' => $examRecord['status'] ?? 'draft',
    'preview' => generateExamPreviewHtml($examRecord),
    'workflow_html' => generateWorkflowSummaryHtml($examRecord, [
        'user_id' => (int) $_SESSION['user_id'],
        'role' => $_SESSION['role'] ?? ''
    ]),
    'exam_data' => $examRecord['exam_data'],
    'warnings' => $validation['warnings']
]);

