<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST');
require_once '../../../core/bootstrap.php';
require_once '../middleware/validate_token.php';

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

if (empty($data->invite_code)) {
    http_response_code(400);
    echo json_encode(['message' => 'Invite code is required.']);
    exit();
}

$league = $fantasyLeagueModel->findByInviteCode($data->invite_code);
if (!$league) {
    http_response_code(404);
    echo json_encode(['message' => 'League not found with that invite code.']);
    exit();
}

try {
    if ($fantasyLeagueModel->addMember($league->id, $authenticated_user_data->id)) {
        http_response_code(200);
        echo json_encode(['message' => 'Successfully joined league!']);
    }
} catch (Exception $e) {
    http_response_code(409); // Conflict, likely already a member
    echo json_encode(['message' => 'You are already a member of this league.']);
}
?>