<?php
$pageTitle = 'Global League Standings';
include 'includes/header.php';

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

// --- Instantiate Models ---
$fantasyModel = new Fantasy();
$seasonModel = new Season();
$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;
}
$current_league = $leagueModel->getById($selected_league_id);

// --- Get User's Fantasy Team ---
$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) {
    header('Location: fantasy.php?league_id=' . $selected_league_id . '&notice=create_team_first');
    exit();
}

// --- Pagination ---
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT) ?: 1;
$limit = 50;
$total_teams = $fantasyModel->getTotalTeamsCount($selected_league_id);
$total_pages = ceil($total_teams / $limit);
$offset = ($page - 1) * $limit;

// --- Fetch Standings ---
$standings = $fantasyModel->getGlobalStandingsPaginated($selected_league_id, $limit, $offset);

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

<div class="fantasy-hero-wrapper">
    <div class="fantasy-hero-content">
        <div class="team-identity">
            <div class="team-kit-icon"><i class="fa-solid fa-globe"></i></div>
            <div class="team-text">
                <h1 class="team-name">Global League</h1>
                <span class="manager-name"><?php echo htmlspecialchars($current_league->name ?? 'All Leagues'); ?></span>
            </div>
        </div>
    </div>
</div>

<div class="page-content">
    <div class="back-nav" style="margin-bottom: 20px;">
        <a href="fantasy_lineup.php?tab=leagues&league_id=<?php echo $selected_league_id; ?>" class="btn-text"><i class="fa-solid fa-arrow-left"></i> Back to My Leagues</a>
    </div>

    <div class="dashboard-section">
        <h2 class="dashboard-title">Overall Standings</h2>
        <?php if (!empty($standings)): ?>
            <div class="table-wrapper">
                <table class="styled-table">
                    <thead>
                        <tr>
                            <th>Rank</th>
                            <th>Team</th>
                            <th>Manager</th>
                            <th>GW Pts</th>
                            <th>Total Pts</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($standings as $index => $team): ?>
                            <?php 
                                $rank = $offset + $index + 1;
                                $is_user = ($team->fantasy_team_id == $user_fantasy_team->id);
                                $rank_class = '';
                                if ($rank === 1) $rank_class = 'rank-1';
                                elseif ($rank === 2) $rank_class = 'rank-2';
                                elseif ($rank === 3) $rank_class = 'rank-3';
                            ?>
                            <tr class="<?php echo $is_user ? 'highlighted-row' : ''; ?>">
                                <td>
                                    <div class="rank-badge <?php echo $rank_class; ?>"><?php echo $rank; ?></div>
                                </td>
                                <td>
                                    <div class="team-cell">
                                        <div class="team-icon-sm"><i class="fa-solid fa-shirt"></i></div>
                                        <strong><?php echo htmlspecialchars($team->team_name); ?></strong>
                                    </div>
                                </td>
                                <td>
                                    <div class="manager-cell">
                                        <span><?php echo htmlspecialchars($team->manager_name); ?></span>
                                    </div>
                                </td>
                                <td><?php echo $team->gameweek_points; ?></td>
                                <td><strong class="total-points"><?php echo $team->total_points; ?></strong></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
                <div class="pagination-controls" style="margin-top: 20px; text-align: center;">
                    <?php if ($page > 1): ?>
                        <a href="?league_id=<?php echo $selected_league_id; ?>&page=<?php echo $page - 1; ?>" class="btn-sm btn-secondary">Previous</a>
                    <?php endif; ?>
                    <span style="margin: 0 10px;">Page <?php echo $page; ?> of <?php echo $total_pages; ?></span>
                    <?php if ($page < $total_pages): ?>
                        <a href="?league_id=<?php echo $selected_league_id; ?>&page=<?php echo $page + 1; ?>" class="btn-sm btn-secondary">Next</a>
                    <?php endif; ?>
                </div>
            <?php endif; ?>

        <?php else: ?>
            <p class="no-data-msg">No teams found for this league yet.</p>
        <?php endif; ?>
    </div>
</div>

<style>
/* Styles from fantasy_league_view.php */
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; }
.team-identity { display: flex; align-items: center; gap: 15px; }
.team-kit-icon { font-size: 2.5rem; background: rgba(255,255,255,0.1); width: 60px; height: 60px; display: flex; align-items: center; justify-content: center; border-radius: 50%; }
.team-text h1 { margin: 0; font-size: 1.8rem; font-weight: 800; }
.manager-name { opacity: 0.8; font-size: 0.9rem; }
.btn-text { color: #555; text-decoration: none; font-weight: 600; display: inline-flex; align-items: center; gap: 5px; }
.btn-text:hover { color: var(--primary-color); }
.rank-badge { width: 30px; height: 30px; display: flex; align-items: center; justify-content: center; border-radius: 50%; font-weight: bold; background: #f0f2f5; color: #555; }
.rank-1 { background: #f1c40f; color: #fff; box-shadow: 0 2px 5px rgba(241, 196, 15, 0.4); }
.rank-2 { background: #95a5a6; color: #fff; }
.rank-3 { background: #cd7f32; color: #fff; }
.team-cell { display: flex; align-items: center; gap: 10px; }
.team-icon-sm { width: 30px; height: 30px; background: var(--hero-gradient); color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 0.8rem; }
.highlighted-row { background-color: rgba(52, 152, 219, 0.05) !important; border-left: 3px solid var(--primary-color); }
.total-points { font-size: 1.1rem; color: var(--primary-color); }
</style>

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