<?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', 'team_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 add players.']);
    exit();
}

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

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

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

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

// --- Further Validation ---
// Check if user and team exist
if (!$user->findById($data->user_id)) {
    http_response_code(404);
    echo json_encode(['message' => 'User to be added not found.']);
    exit();
}
if (!$team->findById($data->team_id)) {
    http_response_code(404);
    echo json_encode(['message' => 'Team not found.']);
    exit();
}
// Check if the user is already a player
if ($player->isUserAlreadyPlayer($data->user_id)) {
    http_response_code(409); // Conflict
    echo json_encode(['message' => 'This user is already registered as a player in the system.']);
    exit();
}

$playerData = [
    'user_id' => $data->user_id,
    'team_id' => $data->team_id,
    'position' => htmlspecialchars(strip_tags($data->position)),
    'squad_number' => $data->squad_number
];

// --- Perform the creation and role update ---
$playerCreateSuccess = $player->create($playerData);
$roleUpdateSuccess = $user->updateRole($data->user_id, 'player');

if ($playerCreateSuccess && $roleUpdateSuccess) {
    http_response_code(201); // Created
    echo json_encode(['message' => 'Player added to team successfully and user role updated.']);
} else {
    http_response_code(500);
    echo json_encode(['message' => 'An error occurred while adding the player.']);
}
?>