<?php
require_once '../../config/config.php';

// Ensure $pdo is accessible
global $pdo;

header('Content-Type: application/json');

function respond($ok, $msg, $extra = []) {
    echo json_encode(($ok ? ['status' => 'success'] : ['status' => 'error']) + ['message' => $msg] + $extra);
    exit;
}

try {
    $examId = (int)($_GET['exam_id'] ?? 0);
    
    if ($examId <= 0) {
        respond(false, 'Exam ID is required');
    }

    // Get valuation allocations for the given exam
    $allocationsStmt = $pdo->prepare("
        SELECT vae.allocation_id, vae.num_scripts, vae.status,
               vs.session_name, vs.start_date, vs.end_date,
               s.subject_code, s.subject_name,
               vre.room_name, vre.room_code,
               CONCAT(sv.first_name, ' ', sv.last_name) as valuator_name,
               CONCAT(ss.first_name, ' ', ss.last_name) as supervisor_name
        FROM valuator_allocations_enhanced vae
        JOIN valuation_sessions vs ON vae.session_id = vs.session_id
        JOIN exam_subjects es ON vae.exam_subject_id = es.exam_subject_id
        JOIN subjects s ON es.subject_id = s.subject_id
        JOIN valuation_rooms_enhanced vre ON vae.room_id = vre.room_id
        JOIN staff sv ON vae.valuator_id = sv.staff_id
        JOIN staff ss ON vae.supervisor_id = ss.staff_id
        WHERE vs.exam_id = ?
        ORDER BY vae.allocation_date DESC
    ");
    $allocationsStmt->execute([$examId]);
    $allocations = $allocationsStmt->fetchAll(PDO::FETCH_ASSOC);

    respond(true, 'Allocations retrieved successfully', ['data' => $allocations]);

} catch (Throwable $e) {
    http_response_code(500);
    respond(false, $e->getMessage());
}
?>

