<?php
require_once '../../config/config.php';

// Get parameters
$examSubjectId = isset($_POST['exam_subject_id']) ? (int)$_POST['exam_subject_id'] : 0;
$roomId = isset($_POST['room_id']) ? (int)$_POST['room_id'] : 0;
$valuatorId = isset($_POST['valuator_id']) ? (int)$_POST['valuator_id'] : 0;
$numScripts = isset($_POST['num_scripts']) ? (int)$_POST['num_scripts'] : 0;
$numScriptsCompleted = isset($_POST['num_scripts_completed']) ? (int)$_POST['num_scripts_completed'] : 0;

if ($examSubjectId <= 0 || $roomId <= 0 || $valuatorId <= 0 || $numScripts <= 0) {
    echo json_encode([
        'status' => 'error',
        'message' => 'All required fields must be provided'
    ]);
    exit;
}

try {
    // Check if allocation already exists for this exam subject
    $checkSql = "SELECT allocation_id FROM valuator_allocation WHERE exam_subject_id = ?";
    $checkStmt = $pdo->prepare($checkSql);
    $checkStmt->execute([$examSubjectId]);
    
    if ($checkStmt->fetch()) {
        throw new Exception('Allocation already exists for this exam subject');
    }

    // Insert new allocation
    $insertSql = "INSERT INTO valuator_allocation 
                 (exam_subject_id, valuator_id, room_id, num_scripts, num_scripts_completed) 
                 VALUES (?, ?, ?, ?, ?)";
    
    $insertStmt = $pdo->prepare($insertSql);
    $insertStmt->execute([
        $examSubjectId,
        $valuatorId,
        $roomId,
        $numScripts,
        $numScriptsCompleted
    ]);

    echo json_encode([
        'status' => 'success',
        'message' => 'Valuation allocation created successfully'
    ]);

} catch (Exception $e) {
    error_log('Create Valuation Allocation Error: ' . $e->getMessage());
    
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage()
    ]);
}
?>
