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

// 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', 'club_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 managers.']);
    exit();
}

// Instantiate models
$team = new Team();
$user = new User();

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

// Validation
$errors = [];
if (empty($data->team_id) || !is_numeric($data->team_id)) {
    $errors[] = 'A numeric team_id is required.';
}
if (empty($data->user_id) || !is_numeric($data->user_id)) {
    $errors[] = 'A numeric user_id is required.';
}

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

// Verify that the team and user exist
$teamToUpdate = $team->findById($data->team_id);
if (!$teamToUpdate) {
    http_response_code(404); // Not Found
    echo json_encode(['message' => 'Team not found.']);
    exit();
}

$userToAssign = $user->findById($data->user_id);
if (!$userToAssign) {
    http_response_code(404); // Not Found
    echo json_encode(['message' => 'User not found.']);
    exit();
}

// --- Perform the assignment ---
// We can wrap these in a transaction in a real-world app
$assignmentSuccess = $team->assignManager($data->team_id, $data->user_id);
$roleUpdateSuccess = $user->updateRole($data->user_id, 'team_manager');

if ($assignmentSuccess && $roleUpdateSuccess) {
    http_response_code(200); // OK
    echo json_encode(['message' => 'Team manager assigned successfully. User role updated.']);
} else {
    http_response_code(500);
    echo json_encode(['message' => 'An error occurred during the assignment process.']);
}
?>