<?php
$pageTitle = 'Fantasy Leagues';
include 'includes/header.php';

// Protect this page: redirect to login if user is not logged in.
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}
$user_id = $_SESSION['user_id'];

// Instantiate models
$fantasyModel = new Fantasy();
$seasonModel = new Season();
$fantasyLeagueModel = new FantasyLeague();
$leagueModel = new League();

// --- Determine League Context ---
$leagues = $leagueModel->getAll();
$selected_league_id = filter_input(INPUT_GET, 'league_id', FILTER_VALIDATE_INT);
if (!$selected_league_id && !empty($leagues)) {
    $selected_league_id = $leagues[0]->id;
}

// --- Get User's Fantasy Team ---
// A user must have a fantasy team for the current season to join/create leagues.
$latest_season = $seasonModel->getAll()[0]->name ?? date('Y') . '/' . (date('Y') + 1);
$user_fantasy_team = $fantasyModel->getTeamByUserIdAndLeague($user_id, $latest_season, $selected_league_id);

if (!$user_fantasy_team) {
    // If user has no team, they can't manage leagues. Redirect them.
    header('Location: fantasy.php?league_id=' . $selected_league_id . '&notice=create_team_first');
    exit();
}

// --- Get Colors from Settings ---
$settings = (new Setting())->getAll();
$primary_color = $settings['primary_color'] ?? '#37003c';
$secondary_color = $settings['secondary_color'] ?? '#580a66';

// --- Fetch Leagues for the User ---
$my_leagues = $fantasyLeagueModel->getLeaguesForUser($user_fantasy_team->id);

?>

<div class="fantasy-hero-wrapper">
    <div class="fantasy-hero-content">
        <div class="hero-text">
            <h1>Fantasy Leagues</h1>
            <p>Join public leagues or create private ones to compete with friends.</p>
        </div>
        <div class="hero-icon"><i class="fa-solid fa-trophy"></i></div>
    </div>
</div>

<div class="page-content">
    <div class="dashboard-section" style="background: #fff; padding: 20px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">
        <form action="fantasy_leagues.php" method="GET" class="selectors-form">
            <label for="league_id_select" style="font-weight: bold; margin-right: 10px; font-size: 1.1rem;">Select League Context:</label>
            <select name="league_id" id="league_id_select" onchange="this.form.submit()" style="flex: 1; padding: 10px; border-radius: 6px; border: 1px solid #ddd; font-size: 1rem;">
                <?php foreach ($leagues as $league): ?>
                    <option value="<?php echo $league->id; ?>" <?php echo ($league->id == $selected_league_id) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($league->name); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </form>
        <small>Your fantasy leagues are associated with a real-world league. Select one to see your private leagues.</small>
    </div>

    <!-- Display any success or error messages -->
    <?php if (isset($_GET['status'])): ?>
        <div class="status-message <?php echo $_GET['status'] === 'success' ? 'success' : 'error'; ?>">
            <?php
            if ($_GET['status'] === 'success' && isset($_GET['code'])) {
                echo 'League created! Your join code is: <strong>' . htmlspecialchars($_GET['code']) . '</strong>';
            } elseif ($_GET['status'] === 'joined') {
                echo 'Successfully joined the league!';
            } elseif (isset($_GET['error'])) {
                echo 'Error: ' . htmlspecialchars($_GET['error']);
            }
            ?>
        </div>
    <?php endif; ?>

    <!-- Section to Join or Create Leagues -->
    <div class="dashboard-section">
        <div class="league-actions-grid">
            <!-- Join League Form -->
            <div class="league-action-card join-card">
                <div class="card-icon"><i class="fa-solid fa-door-open"></i></div>
                <h3>Join a League</h3>
                <p>Enter an invite code to join an existing league.</p>
                <form action="fantasy_league_process.php" method="POST">
                    <input type="hidden" name="league_id" value="<?php echo $selected_league_id; ?>">
                    <input type="hidden" name="action" value="join">
                    <input type="text" name="join_code" placeholder="Enter Join Code" required>
                    <button type="submit">Join League</button>
                </form>
            </div>

            <!-- Create League Form -->
            <div class="league-action-card create-card">
                <div class="card-icon"><i class="fa-solid fa-plus-circle"></i></div>
                <h3>Create a League</h3>
                <p>Start a new private league and invite your friends.</p>
                <form action="fantasy_league_process.php" method="POST">
                    <input type="hidden" name="league_id" value="<?php echo $selected_league_id; ?>">
                    <input type="hidden" name="action" value="create">
                    <input type="text" name="league_name" placeholder="Enter League Name" required>
                    <button type="submit">Create League</button>
                </form>
            </div>
        </div>
    </div>

    <!-- Display User's Leagues -->
    <div class="dashboard-section">
        <h2 class="dashboard-title">My Leagues</h2>
        <?php if (!empty($my_leagues)): ?>
            <div class="my-leagues-grid">
                <?php foreach ($my_leagues as $league): ?>
                    <a href="fantasy_league_view.php?id=<?php echo $league->id; ?>" class="my-league-card">
                        <div class="league-card-icon"><i class="fa-solid fa-users"></i></div>
                        <div class="league-info">
                            <h4><?php echo htmlspecialchars($league->name); ?></h4>
                            <div class="league-stats">
                                <span class="stat-badge"><i class="fa-solid fa-user-group"></i> <?php echo $league->member_count; ?></span>
                                <span class="stat-badge code-badge"><i class="fa-solid fa-key"></i> <?php echo htmlspecialchars($league->join_code); ?></span>
                            </div>
                        </div>
                        <div class="card-arrow"><i class="fa-solid fa-chevron-right"></i></div>
                    </a>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <p class="no-data-msg">You haven't joined any leagues yet. Join or create one above!</p>
        <?php endif; ?>
    </div>


</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const urlParams = new URLSearchParams(window.location.search);
    const mode = urlParams.get('mode');
    
    if (mode === 'create') {
        const input = document.querySelector('input[name="league_name"]');
        if(input) {
            input.focus();
            input.closest('.league-action-card').scrollIntoView({behavior: 'smooth'});
        }
    } else if (mode === 'join') {
        const input = document.querySelector('input[name="join_code"]');
        if(input) {
            input.focus();
            input.closest('.league-action-card').scrollIntoView({behavior: 'smooth'});
        }
    }
});
</script>

<style>
/* Transparent Header Override */
header {
    background: transparent !important;
    box-shadow: none !important;
    position: absolute !important;
    width: 100%;
    top: 0;
    z-index: 1000;
}

:root {
    --hero-gradient: linear-gradient(135deg, <?php echo $primary_color; ?> 0%, <?php echo $secondary_color; ?> 100%);
}

.fantasy-hero-wrapper {
    background: var(--hero-gradient);
    color: white;
    padding: 6rem 20px 3rem 20px;
    border-radius: 0 0 30px 30px;
    margin-bottom: 2rem;
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.fantasy-hero-content {
    max-width: 1200px;
    margin: 0 auto;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.hero-text h1 { margin: 0 0 10px 0; font-size: 2.5rem; font-weight: 800; }
.hero-text p { margin: 0; font-size: 1.1rem; opacity: 0.9; }
.hero-icon { font-size: 4rem; opacity: 0.2; }

.league-actions-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
    margin-bottom: 2rem;
}

.league-action-card {
    background: #fff;
    padding: 25px;
    border-radius: 12px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    text-align: center;
    border: 1px solid #eee;
    transition: transform 0.2s;
}
.league-action-card:hover { transform: translateY(-5px); }

.card-icon {
    width: 60px;
    height: 60px;
    background: #f0f2f5;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
    color: var(--primary-color);
    margin: 0 auto 15px auto;
}

.league-action-card h3 { margin: 0 0 10px 0; }
.league-action-card p { color: #666; margin-bottom: 20px; font-size: 0.9rem; }

.league-action-card input {
    width: 100%;
    padding: 12px;
    border: 1px solid #ddd;
    border-radius: 8px;
    margin-bottom: 10px;
    box-sizing: border-box;
}

.my-leagues-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 15px;
}

.my-league-card {
    display: flex;
    align-items: center;
    background: #fff;
    padding: 20px;
    border-radius: 12px;
    text-decoration: none;
    color: inherit;
    box-shadow: 0 2px 5px rgba(0,0,0,0.05);
    border: 1px solid #eee;
    transition: all 0.2s;
}
.my-league-card:hover {
    border-color: var(--primary-color);
    transform: translateX(5px);
}

.league-card-icon {
    width: 50px;
    height: 50px;
    background: var(--hero-gradient);
    color: white;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.2rem;
    margin-right: 15px;
}

.league-info { flex: 1; }
.league-info h4 { margin: 0 0 5px 0; font-size: 1.1rem; }
.league-stats { display: flex; gap: 10px; font-size: 0.85rem; color: #666; }

.stat-badge {
    background: #f0f2f5;
    padding: 2px 8px;
    border-radius: 4px;
    font-weight: 600;
}
.code-badge { font-family: monospace; letter-spacing: 1px; }

.card-arrow { color: #ccc; }
</style>

<?php
include 'includes/footer.php';
?>