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

// Instantiate models
$leagueModel = new League();
$fixtureModel = new Fixture();
$seasonModel = new Season();
$statsModel = new Stat();
$teamModel = new Team();
$eventModel = new MatchEvent();
$playerModel = new Player();
$sponsorModel = new Sponsorship();

// --- Determine the selected view, league, gameweek, and table type ---

// Main view tab ('matches', 'table', 'stats')
$view = $_GET['view'] ?? 'matches';

// Get all seasons for the season selector
$all_seasons = $seasonModel->getAll();

// Determine the selected season, or default to the latest one
$selected_season = $_GET['season'] ?? ($all_seasons[0]->name ?? null);

// Get leagues for the selected season
$leagues_in_season = [];
if ($selected_season) {
    $leagues_in_season = $leagueModel->getAllBySeason($selected_season);
}

// Get league_id from URL, or default to the first league if not set
$selected_league_id = filter_input(INPUT_GET, 'league_id', FILTER_VALIDATE_INT);
if (!$selected_league_id && !empty($leagues_in_season)) { // Default to first league in the selected season
    $selected_league_id = $leagues_in_season[0]->id;
}

// Determine current league name for display
$current_league_name = 'Matches';
foreach ($leagues_in_season as $l) {
    if ($l->id == $selected_league_id) {
        $current_league_name = $l->name;
        break;
    }
}

$league_id = $selected_league_id; // Set context for header branding
$pageTitle = $current_league_name;
include 'includes/header.php';

// --- Logic specific to each view ---
if ($view === 'matches') {
    // Determine the current/default gameweek
    $current_gameweek = 1;
    $next_fixture = $fixtureModel->getNextUpcomingFixture($selected_league_id);
    if ($next_fixture) {
        $current_gameweek = $next_fixture->gameweek;
    }
    // Get gameweek from URL, or use the calculated current gameweek
    $selected_gameweek = filter_input(INPUT_GET, 'gameweek', FILTER_VALIDATE_INT) ?: $current_gameweek;
    // Fetch fixtures for the selected gameweek
    $fixtures = $fixtureModel->getFixturesByGameweek($selected_league_id, $selected_gameweek);
    
    // Filter out fixtures involving suspended clubs
    if (!empty($fixtures)) {
        $fixtures = array_filter($fixtures, function($match) use ($teamModel) {
            $home_team = $teamModel->findById($match->home_team_id);
            $away_team = $teamModel->findById($match->away_team_id);
            if ($home_team && !$teamModel->checkRegistrationStatus($home_team->club_id)) return false;
            if ($away_team && !$teamModel->checkRegistrationStatus($away_team->club_id)) return false;
            return true;
        });
    }
} elseif ($view === 'table') {
    $table_type = $_GET['table_type'] ?? 'long'; // 'short', 'long', 'home', 'away', 'form'
    $location = 'all';
    if ($table_type === 'home') $location = 'home';
    if ($table_type === 'away') $location = 'away';
    $table_data = $leagueModel->getTable($selected_league_id, $location);
    $table_data = array_filter($table_data, function($row) use ($teamModel) {
        $team = $teamModel->findById($row->team_id);
        return $team && $teamModel->checkRegistrationStatus($team->club_id);
    });
} elseif ($view === 'stats') {
    $stats_type = $_GET['stats_type'] ?? 'player'; // 'player' or 'team'
    
    $player_stat_filter = $_GET['stat'] ?? 'goals';
    $team_stat_filter = $_GET['stat'] ?? 'goals_scored';

    $stats_data = [];
    $stat_label = '';

    if ($stats_type === 'player') {
        switch ($player_stat_filter) {
            case 'goals': $stats_data = $statsModel->getTopScorers($selected_league_id); $stat_label = 'Goals'; break;
            case 'assists': $stats_data = $statsModel->getTopAssists($selected_league_id); $stat_label = 'Assists'; break;
            case 'shots': $stats_data = $statsModel->getMostShots($selected_league_id); $stat_label = 'Shots'; break;
            case 'shots_on_target': $stats_data = $statsModel->getMostShotsOnTarget($selected_league_id); $stat_label = 'Shots on Target'; break;
            case 'fouls': $stats_data = $statsModel->getMostFouls($selected_league_id); $stat_label = 'Fouls'; break;
            case 'yellow_cards': $stats_data = $statsModel->getMostYellowCards($selected_league_id); $stat_label = 'Yellow Cards'; break;
            case 'red_cards': $stats_data = $statsModel->getMostRedCards($selected_league_id); $stat_label = 'Red Cards'; break;
            case 'appearances': $stats_data = $statsModel->getMostAppearances($selected_league_id); $stat_label = 'Appearances'; break;
            case 'minutes': $stats_data = $statsModel->getMostMinutesPlayed($selected_league_id); $stat_label = 'Minutes'; break;
            default: $stats_data = $statsModel->getTopScorers($selected_league_id); $stat_label = 'Goals'; break;
        }
    } elseif ($stats_type === 'team') {
        // Fetch all team stats and filter/sort in PHP
        $all_team_stats = $statsModel->getTeamStatsByLeague($selected_league_id);
        
        // Map filter to object property
        $prop_map = [
            'goals_scored' => 'goals_for',
            'goals_conceded' => 'goals_against',
            'clean_sheets' => 'clean_sheets',
            'shots' => 'shots',
            'shots_on_target' => 'shots_on_target',
            'corners' => 'corners',
            'fouls' => 'fouls_committed',
            'yellow_cards' => 'yellow_cards',
            'red_cards' => 'red_cards'
        ];
        
        $prop = $prop_map[$team_stat_filter] ?? 'goals_for';
        
        // Filter out 0 values and sort
        $stats_data = array_filter($all_team_stats, fn($t) => ($t->$prop ?? 0) > 0);
        usort($stats_data, fn($a, $b) => ($b->$prop ?? 0) <=> ($a->$prop ?? 0));
        
        // Normalize structure for display loop
        foreach ($stats_data as $team) {
            $team->stat_value = $team->$prop;
        }

        switch ($team_stat_filter) {
            case 'goals_scored': $stat_label = 'Goals Scored'; break;
            case 'goals_conceded': $stat_label = 'Goals Conceded'; break;
            case 'clean_sheets': $stat_label = 'Clean Sheets'; break;
            case 'shots': $stat_label = 'Shots'; break;
            case 'shots_on_target': $stat_label = 'Shots on Target'; break;
            case 'corners': $stat_label = 'Corners Won'; break;
            case 'fouls': $stat_label = 'Fouls Committed'; break;
            case 'yellow_cards': $stat_label = 'Yellow Cards'; break;
            case 'red_cards': $stat_label = 'Red Cards'; break;
            default: $stat_label = 'Goals Scored'; break;
        }
    }
}

// Fetch General Product Ads
$productAds = $sponsorModel->getActiveAds(1);
?>

    <div class="matches-hero">
        <h1><?php echo htmlspecialchars($current_league_name); ?></h1>
        <!-- League Selector Form -->
        <form action="matches.php" method="GET" class="selectors-form">
            <input type="hidden" name="view" value="<?php echo htmlspecialchars($view); ?>">
            <select name="season" onchange="this.form.submit()">
                <?php foreach ($all_seasons as $season): ?>
                    <option value="<?php echo htmlspecialchars($season->name); ?>" <?php echo ($season->name == $selected_season) ? 'selected' : ''; ?>>
                        Season <?php echo htmlspecialchars($season->name); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <select name="league_id" onchange="this.form.submit()">
                <?php foreach ($leagues_in_season as $league): ?>
                    <option value="<?php echo $league->id; ?>" <?php echo ($league->id == $selected_league_id) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($league->name); ?>
                    </option>
                <?php endforeach; ?>
                <?php if (empty($leagues_in_season)): ?>
                    <option>No leagues for this season</option>
                <?php endif; ?>
            </select>
        </form>
    </div>

<div class="page-content">
    <!-- Main View Tabs -->
    <div class="main-tabs">
        <a href="?view=matches&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>" class="tab-link <?php echo ($view === 'matches') ? 'active' : ''; ?>">Matches</a>
        <a href="?view=table&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>" class="tab-link <?php echo ($view === 'table') ? 'active' : ''; ?>">Table</a>
        <a href="?view=stats&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>" class="tab-link <?php echo ($view === 'stats') ? 'active' : ''; ?>">Stats</a>
    </div>
    <?php if ($view === 'stats'): ?>
        <a href="compare_players.php" class="btn btn-secondary" style="display: block; text-align: center; margin-bottom: 1rem;"><i class="fa-solid fa-users"></i> Compare Players</a>
    <?php endif; ?>

    <!-- == MATCHES VIEW == -->
    <?php if ($view === 'matches'): ?>
        <div class="gameweek-nav">
            <a href="?view=matches&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&gameweek=<?php echo $selected_gameweek - 1; ?>" class="btn-sm">&laquo; Previous</a>
            <span class="gameweek-display">Gameweek <?php echo $selected_gameweek; ?></span>
            <a href="?view=matches&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&gameweek=<?php echo $selected_gameweek + 1; ?>" class="btn-sm">Next &raquo;</a>
        </div>
        <div class="fixture-list dashboard-section">
            <?php if (!empty($fixtures)): ?>
                <?php foreach ($fixtures as $match): ?>
                    <?php
                    // Fetch scorers if match is active or finished
                    $home_scorers = [];
                    $away_scorers = [];
                    if (in_array($match->status, ['live', 'half_time', 'finished'])) {
                        $events = $eventModel->getEventsForFixture($match->id);
                        $p_names = $playerModel->getPlayerNamesForFixture($match->id);
                        foreach ($events as $event) {
                            if (in_array($event->event_type, ['goal', 'penalty_scored', 'own_goal'])) {
                                $name = $p_names[$event->player_id] ?? 'Unknown';
                                $time = $event->minute . "'";
                                $str = $name . " " . $time;
                                if ($event->event_type === 'own_goal') $str .= " (OG)";
                                if ($event->event_type === 'penalty_scored') $str .= " (P)";
                                
                                if ($event->team_id == $match->home_team_id) $home_scorers[] = $str;
                                else $away_scorers[] = $str;
                            }
                        }
                    }

                    // Use DB Elapsed Time
                    $elapsed_1st = max(0, (int)($match->elapsed_1st ?? 0));
                    $elapsed_2nd = max(0, (int)($match->elapsed_2nd ?? 0));
                    ?>
                    <a href="fixture.php?id=<?php echo $match->id; ?>" class="fixture-item">
                        <div class="match-main-row">
                            <div class="team home-team">
                                <span class="team-name"><?php echo htmlspecialchars($match->home_team_name); ?></span>
                                <img src="<?php echo htmlspecialchars($match->home_team_logo); ?>" alt="" class="team-logo">
                            </div>
                            <?php if ($match->status === 'finished' || $match->status === 'live' || $match->status === 'half_time' || $match->status === 'full_time'): ?>
                                <div class="score-box <?php echo $match->status; ?>">
                                    <span class="score"><?php echo $match->home_team_score ?? 0; ?> - <?php echo $match->away_team_score ?? 0; ?></span>
                                    <?php if ($match->status === 'live' || $match->status === 'half_time' || $match->status === 'full_time'): ?>
                                        <div class="live-timer" 
                                             data-status="<?php echo $match->status; ?>" 
                                             data-first-half-start="<?php echo $match->first_half_start_time ?? ''; ?>" 
                                             data-second-half-start="<?php echo $match->second_half_start_time ?? ''; ?>"
                                             data-first-half-end="<?php echo $match->first_half_end_time ?? ''; ?>"
                                             data-elapsed-first="<?php echo $elapsed_1st; ?>"
                                             data-elapsed-second="<?php echo $elapsed_2nd; ?>"
                                             data-full-time-duration="<?php echo (int)($settings['full_time_duration'] ?? 90); ?>"
                                        >Live</div>
                                    <?php endif; ?>
                                </div>
                            <?php else: ?>
                                <div class="score-box time-box">
                                    <span class="time"><?php echo date('H:i', strtotime($match->match_datetime)); ?></span>
                                    <span class="date"><?php echo date('d M', strtotime($match->match_datetime)); ?></span>
                                </div>
                            <?php endif; ?>
                            <div class="team away-team">
                                <img src="<?php echo htmlspecialchars($match->away_team_logo); ?>" alt="" class="team-logo">
                                <span class="team-name"><?php echo htmlspecialchars($match->away_team_name); ?></span>
                            </div>
                        </div>
                        <?php if (!empty($home_scorers) || !empty($away_scorers)): ?>
                            <div class="match-scorers">
                                <div class="home-scorers">
                                    <?php foreach($home_scorers as $s) echo "<div class='scorer-row'>{$s}</div>"; ?>
                                </div>
                                <div class="away-scorers">
                                    <?php foreach($away_scorers as $s) echo "<div class='scorer-row'>{$s}</div>"; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                    </a>
                <?php endforeach; ?>
            <?php else: ?>
                <p class="no-data-msg">No matches found for this gameweek.</p>
            <?php endif; ?>
        </div>
        <?php if (!empty($productAds)): ?>
            <div class="dashboard-section ad-section" style="text-align: center;">
                <small style="display: block; color: #999; font-size: 0.7rem; margin-bottom: 10px; text-transform: uppercase;">Sponsored</small>
                <?php foreach ($productAds as $ad): ?>
                    <?php
                    $tag = !empty($ad->target_url) ? 'a' : 'div';
                    $href = !empty($ad->target_url) ? 'href="' . htmlspecialchars($ad->target_url) . '" target="_blank"' : '';
                    ?>
                    <<?php echo $tag; ?> <?php echo $href; ?> class="sponsor-ad" data-campaign-id="<?php echo $ad->id; ?>" style="display: inline-block; cursor: pointer;">
                        <?php if ($ad->ad_type === 'video'): ?>
                            <video src="<?php echo htmlspecialchars($ad->ad_content); ?>" autoplay muted loop playsinline style="max-width: 100%; border-radius: 8px;"></video>
                        <?php else: ?>
                            <img src="<?php echo htmlspecialchars($ad->ad_content); ?>" alt="Sponsored" style="max-width: 100%; border-radius: 8px;">
                        <?php endif; ?>
                    </<?php echo $tag; ?>>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    <?php endif; ?>

    <!-- == TABLE VIEW == -->
    <?php if ($view === 'table'): ?>
        <div class="sub-tabs">
            <a href="?view=table&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&table_type=short" class="sub-tab-link <?php echo ($table_type === 'short') ? 'active' : ''; ?>">Short</a>
            <a href="?view=table&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&table_type=long" class="sub-tab-link <?php echo ($table_type === 'long') ? 'active' : ''; ?>">Overall</a>
            <a href="?view=table&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&table_type=home" class="sub-tab-link <?php echo ($table_type === 'home') ? 'active' : ''; ?>">Home</a>
            <a href="?view=table&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&table_type=away" class="sub-tab-link <?php echo ($table_type === 'away') ? 'active' : ''; ?>">Away</a>
            <a href="?view=table&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&table_type=form" class="sub-tab-link <?php echo ($table_type === 'form') ? 'active' : ''; ?>">Form</a>
        </div>
        <div class="table-wrapper card-shadow">
            <table class="styled-table">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Club</th>
                        <?php if ($table_type !== 'form'): ?>
                            <th>P</th>
                            <?php if ($table_type !== 'short'): ?>
                                <th>W</th><th>D</th><th>L</th><th>GF</th><th>GA</th><th>GD</th>
                            <?php endif; ?>
                            <th>Pts</th>
                        <?php else: ?>
                            <th class="form-header">Last 5</th>
                        <?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($table_data as $index => $team): 
                        $rank_class = '';
                        if ($index < 4) $rank_class = 'rank-ucl';
                        elseif ($index < 5) $rank_class = 'rank-uel';
                        elseif ($index >= count($table_data) - 3) $rank_class = 'rank-rel';
                    ?>
                        <tr class="<?php echo $rank_class; ?>">
                            <td><?php echo $index + 1; ?></td>
                            <td class="team-name-cell"><img src="<?php echo htmlspecialchars($team->logo); ?>" alt="" class="table-logo"> <?php echo htmlspecialchars($team->team_name); ?></td>
                            <?php if ($table_type !== 'form'): ?>
                                <td><?php echo $team->played; ?></td>
                                <?php if ($table_type !== 'short'): ?>
                                    <td><?php echo $team->wins; ?></td>
                                    <td><?php echo $team->draws; ?></td>
                                    <td><?php echo $team->losses; ?></td>
                                    <td><?php echo $team->goals_for; ?></td>
                                    <td><?php echo $team->goals_against; ?></td>
                                    <td><?php echo $team->goal_difference; ?></td>
                                <?php endif; ?>
                                <td><strong><?php echo $team->points; ?></strong></td>
                            <?php else: ?>
                                <td class="form-cell">
                                    <?php $last_five = array_slice($team->form, -5); ?>
                                    <?php foreach ($last_five as $result): ?>
                                        <span class="form-bubble form-<?php echo strtolower($result); ?>"><?php echo $result; ?></span>
                                    <?php endforeach; ?>
                                </td>
                            <?php endif; ?>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>

    <!-- == STATS VIEW == -->
    <?php if ($view === 'stats'): ?>
        <div class="sub-tabs">
            <a href="?view=stats&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&stats_type=player" class="sub-tab-link <?php echo ($stats_type === 'player') ? 'active' : ''; ?>">Player Stats</a>
            <a href="?view=stats&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&stats_type=team" class="sub-tab-link <?php echo ($stats_type === 'team') ? 'active' : ''; ?>">Team Stats</a>
        </div>

        <?php if ($stats_type === 'player'): ?>
            <div class="sub-tabs" style="margin-top: 10px;">
                <a href="?view=stats&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&stats_type=player&stat=goals" class="sub-tab-link <?php echo ($player_stat_filter === 'goals') ? 'active' : ''; ?>">Goals</a>
                <a href="?view=stats&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&stats_type=player&stat=assists" class="sub-tab-link <?php echo ($player_stat_filter === 'assists') ? 'active' : ''; ?>">Assists</a>
                <a href="?view=stats&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&stats_type=player&stat=shots" class="sub-tab-link <?php echo ($player_stat_filter === 'shots') ? 'active' : ''; ?>">Shots</a>
                <a href="?view=stats&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&stats_type=player&stat=shots_on_target" class="sub-tab-link <?php echo ($player_stat_filter === 'shots_on_target') ? 'active' : ''; ?>">On Target</a>
                <a href="?view=stats&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&stats_type=player&stat=fouls" class="sub-tab-link <?php echo ($player_stat_filter === 'fouls') ? 'active' : ''; ?>">Fouls</a>
                <a href="?view=stats&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&stats_type=player&stat=yellow_cards" class="sub-tab-link <?php echo ($player_stat_filter === 'yellow_cards') ? 'active' : ''; ?>">Yellow Cards</a>
                <a href="?view=stats&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&stats_type=player&stat=red_cards" class="sub-tab-link <?php echo ($player_stat_filter === 'red_cards') ? 'active' : ''; ?>">Red Cards</a>
                <a href="?view=stats&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&stats_type=player&stat=appearances" class="sub-tab-link <?php echo ($player_stat_filter === 'appearances') ? 'active' : ''; ?>">Appearances</a>
                <a href="?view=stats&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&stats_type=player&stat=minutes" class="sub-tab-link <?php echo ($player_stat_filter === 'minutes') ? 'active' : ''; ?>">Minutes</a>
            </div>

            <div class="stats-container">
                <div class="stats-section">
                    <h3><?php echo $stat_label; ?></h3>
                    <?php if (!empty($stats_data)): ?>
                        <?php foreach ($stats_data as $index => $player): 
                            // Determine the value property based on the filter
                            $val = $player->{$player_stat_filter} ?? ($player->stat_value ?? 0);
                            // Fallback for specific named properties from Stat.php methods
                            if ($player_stat_filter == 'shots_on_target') $val = $player->shots_on_target;
                            if ($player_stat_filter == 'yellow_cards') $val = $player->yellow_cards;
                            if ($player_stat_filter == 'red_cards') $val = $player->red_cards;
                        ?>
                            <div class="stats-row">
                                <span class="rank"><?php echo $index + 1; ?></span>
                                <div class="player-info">
                                    <img src="<?php echo htmlspecialchars($player->profile_picture ?? $player->club_logo); ?>" alt="" class="player-avatar-sm">
                                    <div class="player-details">
                                        <a href="player.php?id=<?php echo $player->player_id; ?>" class="player-name"><?php echo htmlspecialchars($player->first_name . ' ' . $player->last_name); ?></a>
                                        <span class="player-club"><img src="<?php echo htmlspecialchars($player->club_logo); ?>" alt="" class="club-logo-xs"> <?php echo htmlspecialchars($player->club_name); ?></span>
                                    </div>
                                </div>
                                <span class="stat-value"><?php echo $val; ?></span>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <p class="no-data-msg">No stats available for this category.</p>
                    <?php endif; ?>
                </div>
            </div>
            <?php if (!empty($productAds)): ?>
                <div class="dashboard-section ad-section" style="text-align: center; margin-top: 20px;">
                    <small style="display: block; color: #999; font-size: 0.7rem; margin-bottom: 10px; text-transform: uppercase;">Sponsored</small>
                    <?php foreach ($productAds as $ad): ?>
                    <?php
                    $tag = !empty($ad->target_url) ? 'a' : 'div';
                    $href = !empty($ad->target_url) ? 'href="' . htmlspecialchars($ad->target_url) . '" target="_blank"' : '';
                    ?>
                    <<?php echo $tag; ?> <?php echo $href; ?> class="sponsor-ad" data-campaign-id="<?php echo $ad->id; ?>" style="display: inline-block; cursor: pointer;">
                            <?php if ($ad->ad_type === 'video'): ?>
                                <video src="<?php echo htmlspecialchars($ad->ad_content); ?>" autoplay muted loop playsinline style="max-width: 100%; border-radius: 8px;"></video>
                            <?php else: ?>
                                <img src="<?php echo htmlspecialchars($ad->ad_content); ?>" alt="Sponsored" style="max-width: 100%; border-radius: 8px;">
                            <?php endif; ?>
                    </<?php echo $tag; ?>>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        <?php elseif ($stats_type === 'team'): ?>
            <div class="sub-tabs" style="margin-top: 10px;">
                <a href="?view=stats&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&stats_type=team&stat=goals_scored" class="sub-tab-link <?php echo ($team_stat_filter === 'goals_scored') ? 'active' : ''; ?>">Goals Scored</a>
                <a href="?view=stats&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&stats_type=team&stat=goals_conceded" class="sub-tab-link <?php echo ($team_stat_filter === 'goals_conceded') ? 'active' : ''; ?>">Goals Conceded</a>
                <a href="?view=stats&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&stats_type=team&stat=clean_sheets" class="sub-tab-link <?php echo ($team_stat_filter === 'clean_sheets') ? 'active' : ''; ?>">Clean Sheets</a>
                <a href="?view=stats&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&stats_type=team&stat=shots" class="sub-tab-link <?php echo ($team_stat_filter === 'shots') ? 'active' : ''; ?>">Shots</a>
                <a href="?view=stats&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&stats_type=team&stat=shots_on_target" class="sub-tab-link <?php echo ($team_stat_filter === 'shots_on_target') ? 'active' : ''; ?>">On Target</a>
                <a href="?view=stats&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&stats_type=team&stat=corners" class="sub-tab-link <?php echo ($team_stat_filter === 'corners') ? 'active' : ''; ?>">Corners</a>
                <a href="?view=stats&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&stats_type=team&stat=fouls" class="sub-tab-link <?php echo ($team_stat_filter === 'fouls') ? 'active' : ''; ?>">Fouls</a>
                <a href="?view=stats&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&stats_type=team&stat=yellow_cards" class="sub-tab-link <?php echo ($team_stat_filter === 'yellow_cards') ? 'active' : ''; ?>">Yellow Cards</a>
                <a href="?view=stats&season=<?php echo $selected_season; ?>&league_id=<?php echo $selected_league_id; ?>&stats_type=team&stat=red_cards" class="sub-tab-link <?php echo ($team_stat_filter === 'red_cards') ? 'active' : ''; ?>">Red Cards</a>
            </div>

            <div class="stats-container">
                <div class="stats-section">
                    <h3><?php echo $stat_label; ?></h3>
                    <?php if (!empty($stats_data)): ?>
                        <?php foreach ($stats_data as $index => $team): ?>
                            <div class="stats-row">
                                <span class="rank"><?php echo $index + 1; ?></span>
                                <div class="player-info">
                                    <img src="<?php echo htmlspecialchars($team->club_logo); ?>" alt="" class="table-logo">
                                    <span class="player-name"><?php echo htmlspecialchars($team->team_name); ?></span>
                                </div>
                                <span class="stat-value"><?php echo $team->stat_value; ?></span>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <p class="no-data-msg">No stats available for this category.</p>
                    <?php endif; ?>
                </div>
            </div>
            <?php if (!empty($productAds)): ?>
                <div class="dashboard-section ad-section" style="text-align: center; margin-top: 20px;">
                    <small style="display: block; color: #999; font-size: 0.7rem; margin-bottom: 10px; text-transform: uppercase;">Sponsored</small>
                    <?php foreach ($productAds as $ad): ?>
                        <?php
                        $tag = !empty($ad->target_url) ? 'a' : 'div';
                        $href = !empty($ad->target_url) ? 'href="' . htmlspecialchars($ad->target_url) . '" target="_blank"' : '';
                        ?>
                        <<?php echo $tag; ?> <?php echo $href; ?> class="sponsor-ad" data-campaign-id="<?php echo $ad->id; ?>" style="display: inline-block; cursor: pointer;">
                            <?php if ($ad->ad_type === 'video'): ?>
                                <video src="<?php echo htmlspecialchars($ad->ad_content); ?>" autoplay muted loop playsinline style="max-width: 100%; border-radius: 8px;"></video>
                            <?php else: ?>
                                <img src="<?php echo htmlspecialchars($ad->ad_content); ?>" alt="Sponsored" style="max-width: 100%; border-radius: 8px;">
                            <?php endif; ?>
                        </<?php echo $tag; ?>>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    <?php endif; ?>

</div>
<style>
/* Modern Matches Styling */
.matches-hero {
    background: var(--primary-color); /* Fallback for older browsers */
    background: var(--hero-gradient);
    color: white;
    padding: 25px;
    border-radius: 0 0 20px 20px;
    margin-bottom: 20px;
    box-shadow: 0 4px 15px rgba(0,0,0,0.15);
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 15px;
}
.matches-hero h1 { margin: 0; font-size: 2rem; font-weight: 700; }

.selectors-form { display: flex; gap: 10px; }
.selectors-form select {
    padding: 8px 15px;
    border-radius: 20px;
    border: none;
    background: rgba(255,255,255,0.2);
    color: white;
    font-weight: 600;
    cursor: pointer;
    outline: none;
}
.selectors-form select option { background: #37003c; color: white; }

/* Tabs */
.main-tabs {
    display: flex;
    overflow-x: auto;
    background: #fff;
    position: sticky;
    top: 0;
    z-index: 100;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    padding: 0 10px;
    margin-bottom: 20px;
    border-radius: 8px;
}
.tab-link {
    flex: 0 0 auto;
    padding: 15px 20px;
    color: #64748b;
    font-weight: 600;
    text-decoration: none;
    border-bottom: 3px solid transparent;
    transition: all 0.2s;
}
.tab-link.active { color: #e90052; border-bottom-color: #e90052; }

/* Gameweek Nav */
.gameweek-nav {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #fff;
    padding: 15px;
    border-radius: 12px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.gameweek-display { font-weight: 800; font-size: 1.1rem; color: #37003c; }
.btn-sm {
    background: #f0f4f8;
    color: #333;
    padding: 5px 12px;
    border-radius: 15px;
    text-decoration: none;
    font-size: 0.85rem;
    font-weight: 600;
    transition: background 0.2s;
}
.btn-sm:hover { background: #e2e8f0; }

/* Fixture List */
.fixture-list { display: flex; flex-direction: column; gap: 12px; }
.fixture-item {
    display: block; /* Changed from flex to block to allow stacking of scorers */
    background: #fff;
    padding: 15px 20px;
    border-radius: 12px;
    text-decoration: none;
    color: inherit;
    box-shadow: 0 2px 5px rgba(0,0,0,0.03);
    transition: transform 0.2s, box-shadow 0.2s;
    border: 1px solid #f1f5f9;
}
.fixture-item:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0,0,0,0.08); border-color: #e90052; }

.match-main-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
}

.match-scorers {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
    padding-top: 8px;
    border-top: 1px solid #f1f5f9;
    font-size: 0.75rem;
    color: #64748b;
    line-height: 1.4;
    align-items: flex-start;
}
.home-scorers { text-align: right; flex: 1; padding-right: 10px; }
.away-scorers { text-align: left; flex: 1; padding-left: 10px; }

.team { flex: 1; display: flex; align-items: center; gap: 12px; font-weight: 600; font-size: 1rem; color: #1e293b; }
.home-team { justify-content: flex-end; text-align: right; }
.away-team { justify-content: flex-start; text-align: left; }
.team-logo { width: 32px; height: 32px; object-fit: contain; }
.team-name {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 150px; /* Prevent long names from breaking layout */
}

.score-box {
    background: #f8fafc;
    padding: 5px 15px;
    border-radius: 8px;
    text-align: center;
    min-width: 80px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    flex-shrink: 0; /* Prevent score box from shrinking */
    white-space: nowrap;
}
.score-box.live { background: #fff0f3; border: 1px solid #ffccd5; }
.score { font-size: 1.4rem; font-weight: 800; color: #37003c; line-height: 1; }
.time { font-size: 1.1rem; font-weight: 700; color: #333; }
.date { font-size: 0.75rem; color: #888; text-transform: uppercase; margin-top: 2px; }
.live-timer { font-size: 0.75rem; color: #e90052; font-weight: bold; margin-top: 2px; animation: pulse 2s infinite; }

@keyframes pulse { 0% { opacity: 1; } 50% { opacity: 0.6; } 100% { opacity: 1; } }

/* Stats & Table Overrides */
.sub-tabs { display: flex; gap: 10px; margin-bottom: 15px; overflow-x: auto; padding-bottom: 5px; }
.sub-tab-link { padding: 6px 12px; background: #f1f5f9; border-radius: 15px; text-decoration: none; color: #555; font-size: 0.85rem; font-weight: 600; white-space: nowrap; }
.sub-tab-link.active { background: #37003c; color: white; }

.card-shadow {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
    overflow: hidden;
    border: 1px solid #f1f5f9;
}

.table-wrapper {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

.styled-table { width: 100%; border-collapse: collapse; font-size: 0.9rem; }
.styled-table thead tr { background-color: #f8fafc; color: #64748b; text-align: left; font-weight: 600; text-transform: uppercase; font-size: 0.75rem; letter-spacing: 0.5px; }
.styled-table th, .styled-table td { padding: 12px 15px; }
.styled-table tbody tr { border-bottom: 1px solid #f1f5f9; transition: background 0.1s; }
.styled-table tbody tr:last-of-type { border-bottom: none; }
.styled-table tbody tr:hover { background-color: #f8fafc; }

/* Rank Indicators */
.rank-ucl { border-left: 4px solid #2ecc71; }
.rank-uel { border-left: 4px solid #3498db; }
.rank-rel { border-left: 4px solid #e74c3c; }

.form-bubble { display: inline-block; width: 20px; height: 20px; line-height: 20px; text-align: center; border-radius: 50%; color: white; font-size: 0.7rem; font-weight: bold; margin-right: 2px; }
.form-w { background: #00ff85; color: #37003c; }
.form-d { background: #bdc3c7; color: #333; }
.form-l { background: #e90052; }
.stats-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 2rem;
}
.stats-section {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
    border: 1px solid #f1f5f9;
}
.stats-section h3 {
    margin-top: 0;
    border-bottom: 1px solid #e2e8f0;
    padding-bottom: 10px;
    margin-bottom: 15px;
}
.stats-row {
    display: flex;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #f1f5f9;
}
.stats-row:last-child {
    border-bottom: none;
}
.stats-row .rank {
    font-weight: bold;
    color: #888;
    width: 30px;
}
.stats-row .player-info {
    flex-grow: 1;
    display: flex;
    align-items: center;
    gap: 10px;
}
.stats-row .stat-value {
    font-weight: bold;
    font-size: 1.1rem;
}
.player-avatar-sm { width: 40px; height: 40px; border-radius: 50%; object-fit: cover; border: 1px solid #eee; }
.player-details { display: flex; flex-direction: column; justify-content: center; }
.player-details .player-name { font-weight: 600; font-size: 0.95rem; color: #eeededff; }
.player-details .player-name:hover { text-decoration: underline; }
.player-details .player-club { font-size: 0.75rem; color: #777; display: flex; align-items: center; gap: 4px; }
.club-logo-xs { width: 16px; height: 16px; object-fit: contain; }

@media (max-width: 768px) {
    .matches-hero { flex-direction: column; align-items: stretch; text-align: center; }
    .selectors-form { justify-content: center; }
    .team-name { display: block; font-size: 0.9rem; }
}
</style>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // --- Live Timer Logic for Matches Page ---
        function formatTime(seconds) {
            const mins = Math.floor(seconds / 60);
            const secs = seconds % 60;
            return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
        }

        function startTimer(element, initialElapsed, offsetMinutes) {
            const localStartTimestamp = Date.now();
            const fullTimeDuration = parseInt(element.dataset.fullTimeDuration || 90);
            const halfTimeMark = fullTimeDuration / 2;

            const interval = setInterval(() => {
                const now = Date.now();
                const delta = Math.floor((now - localStartTimestamp) / 1000);
                const totalElapsedSeconds = initialElapsed + delta;
                let displayMinutes = offsetMinutes + Math.floor(totalElapsedSeconds / 60);

                if (displayMinutes >= halfTimeMark && offsetMinutes < halfTimeMark) {
                    const stoppageMinutes = displayMinutes - halfTimeMark;
                    element.innerHTML = `${halfTimeMark}+${stoppageMinutes + 1}'`;
                } else if (displayMinutes >= fullTimeDuration) {
                    const stoppageMinutes = displayMinutes - fullTimeDuration;
                    element.innerHTML = `${fullTimeDuration}+${stoppageMinutes + 1}'`;
                } else {
                    element.innerHTML = `${displayMinutes + 1}'`;
                }
            }, 1000);
        }

        document.querySelectorAll('.live-timer').forEach(timerElement => {
            const firstHalfStart = timerElement.dataset.firstHalfStart;
            const secondHalfStart = timerElement.dataset.secondHalfStart;
                const firstHalfEnd = timerElement.dataset.firstHalfEnd;
                let status = timerElement.dataset.status;

                // Robust check for Half Time
                const isFirstHalfEnded = firstHalfEnd && firstHalfEnd !== '0000-00-00 00:00:00';
                const isSecondHalfStarted = secondHalfStart && secondHalfStart !== '0000-00-00 00:00:00';
                
                if ((status === 'live' || status === '') && isFirstHalfEnded && !isSecondHalfStarted) {
                    status = 'half_time';
                }

            if (status === 'half_time') {
                timerElement.innerHTML = 'HT';
            } else if (status === 'full_time') {
                timerElement.innerHTML = 'FT';
            } else if (status === 'live' && secondHalfStart && secondHalfStart !== '0000-00-00 00:00:00') {
                startTimer(timerElement, parseInt(timerElement.dataset.elapsedSecond), (parseInt(timerElement.dataset.fullTimeDuration || 90) / 2));
            } else if (status === 'live' && firstHalfStart && firstHalfStart !== '0000-00-00 00:00:00') {
                startTimer(timerElement, parseInt(timerElement.dataset.elapsedFirst), 0);
            } else {
                // Fallback if time is not set but status is live
                timerElement.innerHTML = 'Live';
            }
        });
    });
</script>

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