<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With');

require_once '../../../core/bootstrap.php';
require_once '../middleware/validate_token.php'; // Protect this endpoint

$fantasyModel = new Fantasy();
$fantasyTeamModel = new FantasyTeam(); // Assuming this exists to check ownership

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

if (empty($data->fantasy_team_id) || empty($data->player_out_id) || empty($data->player_in_id)) {
    http_response_code(400);
    echo json_encode(['message' => 'Missing required parameters.']);
    exit();
}

// Security Check: Ensure the logged-in user owns this fantasy team
$team = $fantasyTeamModel->findByIdAndUser($data->fantasy_team_id, $authenticated_user_data->id);
if (!$team) {
    http_response_code(403); // Forbidden
    echo json_encode(['message' => 'You do not have permission to modify this team.']);
    exit();
}

try {
    if ($fantasyModel->makeSubstitution($data->fantasy_team_id, $data->player_out_id, $data->player_in_id)) {
        http_response_code(200);
        echo json_encode(['message' => 'Substitution successful!']);
    } else {
        throw new Exception('Substitution failed. Please try again.');
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['message' => $e->getMessage()]);
}
?>