<?php
require_once '../core/bootstrap.php';

// --- Authentication & Basic Validation ---
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: fantasy_leagues.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$action = $_POST['action'] ?? '';

// --- Instantiate Models ---
$fantasyModel = new Fantasy();
$seasonModel = new Season();
$fantasyLeagueModel = new FantasyLeague();

// --- Determine League Context from POST ---
$league_id_context = filter_input(INPUT_POST, 'league_id', FILTER_VALIDATE_INT);

// --- Get User's Fantasy Team (Required for all actions) ---
$latest_season = $seasonModel->getAll()[0]->name ?? date('Y') . '/' . (date('Y') + 1);
$user_fantasy_team = $fantasyModel->getTeamByUserIdAndLeague($user_id, $latest_season, $league_id_context);

if (!$user_fantasy_team) {
    // User must have a team to interact with leagues
    header('Location: fantasy.php?league_id=' . $league_id_context . '&notice=create_team_first');
    exit();
}

// --- Process Action ---
switch ($action) {
    case 'create':
        $league_name = trim($_POST['league_name'] ?? '');

        if (empty($league_name)) {
            header('Location: fantasy_leagues.php?error=League name cannot be empty.');
            exit();
        }

        $data = [
            'name' => $league_name,
            'user_id' => $user_id,
            'season' => $latest_season,
            'fantasy_team_id' => $user_fantasy_team->id
        ];

        $new_league = $fantasyLeagueModel->create($data);

        if ($new_league && !empty($new_league->join_code)) {
            header('Location: fantasy_leagues.php?status=success&code=' . urlencode($new_league->join_code));
        } else {
            header('Location: fantasy_leagues.php?error=Could not create league.');
        }
        exit();

    case 'join':
        $join_code = trim($_POST['join_code'] ?? '');

        if (empty($join_code)) {
            header('Location: fantasy_leagues.php?error=Join code cannot be empty.');
            exit();
        }

        $league = $fantasyLeagueModel->findByJoinCode($join_code);

        if (!$league) {
            header('Location: fantasy_leagues.php?error=Invalid join code.');
            exit();
        }

        if ($fantasyLeagueModel->isMember($league->id, $user_fantasy_team->id)) {
            header('Location: fantasy_leagues.php?error=You are already in this league.');
            exit();
        }

        if ($fantasyLeagueModel->addMember($league->id, $user_fantasy_team->id)) {
            header('Location: fantasy_leagues.php?status=joined');
        } else {
            header('Location: fantasy_leagues.php?error=Could not join league.');
        }
        exit();

    default:
        // Invalid action
        header('Location: fantasy_leagues.php');
        exit();
}
?>