<?php
// Set headers for JSON response
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: PUT');

// Bootstrap the application
require_once '../../../core/bootstrap.php';

// Protect this action
require_once '../middleware/validate_token.php';

// Check user role
$allowed_roles = ['admin', 'super_admin', 'league_manager'];
if (!in_array($authenticated_user_data->role, $allowed_roles)) {
    http_response_code(403); // Forbidden
    echo json_encode(['message' => 'Access Denied. You do not have permission to assign officials.']);
    exit();
}

// Instantiate models
$fixture = new Fixture();
$user = new User();

// Get raw posted data
$data = json_decode(file_get_contents("php://input"));

// Validation
$errors = [];
if (empty($data->fixture_id) || !is_numeric($data->fixture_id)) $errors[] = 'A numeric fixture_id is required.';
if (empty($data->referee_id) || !is_numeric($data->referee_id)) $errors[] = 'A numeric referee_id is required.';
if (empty($data->commissioner_id) || !is_numeric($data->commissioner_id)) $errors[] = 'A numeric commissioner_id is required.';

if (!empty($errors)) {
    http_response_code(400); // Bad Request
    echo json_encode(['errors' => $errors]);
    exit();
}

// --- Further Validation ---
// Check if fixture exists
if (!$fixture->findById($data->fixture_id)) {
    http_response_code(404);
    echo json_encode(['message' => 'Fixture not found.']);
    exit();
}

// Check if the assigned users exist and have the correct roles
$refereeUser = $user->findById($data->referee_id);
if (!$refereeUser || $refereeUser->role !== 'referee') {
    http_response_code(400);
    echo json_encode(['message' => 'Invalid referee_id or user is not a referee.']);
    exit();
}

$commissionerUser = $user->findById($data->commissioner_id);
if (!$commissionerUser || $commissionerUser->role !== 'commissioner') {
    http_response_code(400);
    echo json_encode(['message' => 'Invalid commissioner_id or user is not a commissioner.']);
    exit();
}

$assignmentData = [
    'fixture_id' => $data->fixture_id,
    'referee_id' => $data->referee_id,
    'commissioner_id' => $data->commissioner_id
];

if ($fixture->assignOfficials($assignmentData)) {
    http_response_code(200); // OK
    echo json_encode(['message' => 'Officials assigned to fixture successfully.']);
} else {
    http_response_code(500);
    echo json_encode(['message' => 'An error occurred while assigning officials.']);
}
?>