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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

$examId = (int) ($_POST['exam_id'] ?? 0);
$action = trim((string) ($_POST['workflow_action'] ?? ''));
$note = trim((string) ($_POST['note'] ?? ''));

if (!$examId || $action === '') {
    echo json_encode(['success' => false, 'message' => 'Missing workflow payload.']);
    exit;
}

$result = transitionExamWorkflow($examId, $action, $note, [
    'user_id' => (int) $_SESSION['user_id'],
    'role' => $_SESSION['role'] ?? ''
]);

if (empty($result['success'])) {
    echo json_encode($result);
    exit;
}

$exam = loadExamRecord($examId);
echo json_encode([
    'success' => true,
    'message' => $result['message'],
    'status' => $exam['status'] ?? 'draft',
    'status_label' => getStatusLabel($exam['status'] ?? 'draft'),
    'preview' => generateExamPreviewHtml($exam),
    'workflow_html' => generateWorkflowSummaryHtml($exam, [
        'user_id' => (int) $_SESSION['user_id'],
        'role' => $_SESSION['role'] ?? ''
    ])
]);

