<?php
require_once '../../config/database.php';
require_once '../../config/auth.php';
require_once '../../includes/ExamGradingService.php';

header('Content-Type: application/json');

if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Authentication required']);
    exit;
}

$attemptId = intval($_GET['attempt_id'] ?? 0);
if (!$attemptId) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Attempt ID required']);
    exit;
}

try {
    $submission = ExamGradingService::getSubmission(getDB(), $attemptId, (int) $_SESSION['user_id'], $_SESSION['role'] ?? 'student');
    echo json_encode([
        'success' => true,
        'submission' => $submission['attempt'],
        'student' => $submission['student'],
        'questions' => $submission['questions']
    ]);
} catch (Throwable $e) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
