<?php
require_once '../core/bootstrap.php';
 
// --- Get IDs and View from URL ---
$fixture_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
$view = $_GET['view'] ?? 'summary'; // Default to summary view

if (!$fixture_id) {
    include 'includes/header.php';
    echo "<p class='error-msg'>Invalid fixture ID.</p>";
    include 'includes/footer.php';
    exit();
}

// --- Instantiate Models and Fetch Data ---
$fixtureModel = new Fixture();
$leagueModel = new League();
$eventModel = new MatchEvent();
$playerModel = new Player();
$lineupModel = new Lineup();
$statsModel = new Stats();
$teamModel = new Team();
$sponsorModel = new Sponsorship(); // Add Sponsor Model
$predictionService = new PredictionService();

// Fetch the main fixture details (teams, score, etc.)
$fixture = $fixtureModel->findById($fixture_id);

if (!$fixture) {
    include 'includes/header.php';
    echo "<p class='error-msg'>Fixture not found.</p>";
    include 'includes/footer.php';
    exit();
}

// --- Set Context for Header & Display ---
$league_id = $fixture->league_id;
$league = $leagueModel->getById($league_id);
$league_name = $league ? $league->name : '';
$pageTitle = $fixture->home_team_name . ' vs ' . $fixture->away_team_name;
include 'includes/header.php';

// --- Check Registration Status ---
$home_team = $teamModel->findById($fixture->home_team_id);
$away_team = $teamModel->findById($fixture->away_team_id);

if (($home_team && !$teamModel->checkRegistrationStatus($home_team->club_id)) || 
    ($away_team && !$teamModel->checkRegistrationStatus($away_team->club_id))) {
    echo "<div class='page-content'><div class='alert alert-danger' style='background:#f8d7da; color:#721c24; padding:15px; border-radius:5px; margin-bottom:20px;'>One or both teams in this fixture have outstanding registration fees and are currently suspended.</div></div>";
    include 'includes/footer.php';
    exit();
}

// --- Fetch Data for Each Tab ---
$match_events = [];
$player_names = [];
$player_details = [];
$home_lineup = null;
$away_lineup = null;
$match_stats = null;
$prediction = null;

// Always fetch events and player names for the hero section if match is active/finished
if (in_array($fixture->status, ['live', 'half_time', 'finished'])) {
    $match_events = $eventModel->getEventsForFixture($fixture_id);
    $player_names = $playerModel->getPlayerNamesForFixture($fixture_id);
}

if ($view === 'summary' && $fixture->status === 'scheduled') {
    $prediction = $predictionService->generatePrediction($fixture->home_team_id, $fixture->away_team_id, $fixture->league_id);
} elseif ($view === 'lineups') {
    // Fetch unavailable players for both teams
    $home_unavailable = ['injured' => [], 'suspended' => []];
    $away_unavailable = ['injured' => [], 'suspended' => []];

    try {
        $home_unavailable['injured'] = $playerModel->getInjuredPlayersByTeamId($fixture->home_team_id);
    } catch (PDOException $e) {
        // Gracefully handle if 'injuries' table doesn't exist yet
    }
    try {
        $home_unavailable['suspended'] = $playerModel->getSuspendedPlayersByTeamId($fixture->home_team_id);
    } catch (PDOException $e) {
        // Gracefully handle if 'suspensions' table doesn't exist yet
    }

    try {
        $away_unavailable['injured'] = $playerModel->getInjuredPlayersByTeamId($fixture->away_team_id);
    } catch (PDOException $e) {
        // Gracefully handle if 'injuries' table doesn't exist yet
    }
    try {
        $away_unavailable['suspended'] = $playerModel->getSuspendedPlayersByTeamId($fixture->away_team_id);
    } catch (PDOException $e) {
        // Gracefully handle if 'suspensions' table doesn't exist yet
    }

    $home_lineup = $lineupModel->getLineupForFixture($fixture_id, $fixture->home_team_id);
    $away_lineup = $lineupModel->getLineupForFixture($fixture_id, $fixture->away_team_id);
    // Fetch player names involved in the fixture for easy lookup
    $player_names = $playerModel->getPlayerNamesForFixture($fixture_id);
    // Fetch full player details for position info
    $player_details = $playerModel->getPlayerDetailsForFixture($fixture_id);
    
    if (!function_exists('organize_by_position')) {
        // Helper function to organize starters by position
        function organize_by_position($starters_with_pos, $player_details) {
            $organized = ['Goalkeeper' => [], 'Defender' => [], 'Midfielder' => [], 'Forward' => []];
            foreach ($starters_with_pos as $player_id => $played_position) {
                if (isset($player_details[$player_id])) {
                    $player = $player_details[$player_id];
                    // Use the played_position from the lineup data, not the player's natural position
                    $organized[$played_position][] = $player;
                }
            }
            return $organized;
        }
    }
} elseif ($view === 'stats') {
    $match_stats = $statsModel->getStatsForFixture($fixture_id);

} elseif ($view === 'table') {
    $table_type = $_GET['table_type'] ?? 'long'; // 'long' or 'form'
    $live_table = $leagueModel->getLiveTable($fixture_id);
    
    // Fetch base table (finished matches only) to calculate live rank changes
    $base_table = $leagueModel->getTable($fixture->league_id);
    $prev_ranks = [];
    foreach ($base_table as $ix => $row) {
        $prev_ranks[$row->team_id] = $ix + 1;
    }
} elseif ($view === 'h2h') {
    $h2h_matches = $fixtureModel->getHeadToHead($fixture->home_team_id, $fixture->away_team_id);
    
    $home_wins = 0;
    $away_wins = 0;
    $draws = 0;

    foreach ($h2h_matches as $match) {
        if ($match->home_team_score > $match->away_team_score) {
            if ($match->home_team_id == $fixture->home_team_id) $home_wins++;
            else $away_wins++;
        } elseif ($match->away_team_score > $match->home_team_score) {
            if ($match->away_team_id == $fixture->away_team_id) $away_wins++;
            else $home_wins++;
        } else {
            $draws++;
        }
    }
}

// Fetch Match Day Sponsors
$matchSponsors = $sponsorModel->getMatchSponsors($fixture_id);

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

?>

<?php
// Prepare scorers for Hero
$hero_home_scorers = [];
$hero_away_scorers = [];
if (!empty($match_events)) {
    foreach ($match_events as $event) {
        if (in_array($event->event_type, ['goal', 'penalty_scored', 'own_goal'])) {
            $pName = $player_names[$event->player_id] ?? 'Unknown';
            
            // Format time for hero (simplified)
            $time = $event->minute . "'";
            
            $str = $pName . " " . $time;
            if ($event->event_type === 'own_goal') $str .= " (OG)";
            if ($event->event_type === 'penalty_scored') $str .= " (P)";
            
            if ($event->team_id == $fixture->home_team_id) $hero_home_scorers[] = $str;
            else $hero_away_scorers[] = $str;
        }
    }
}
?>

<!-- Match Hero Section -->
<div class="match-hero">
    <?php if ($league_name): ?>
        <div class="league-badge-overlay"><?php echo htmlspecialchars($league_name); ?></div>
    <?php endif; ?>
    <div class="hero-team home">
        <img src="<?php echo htmlspecialchars($fixture->home_team_logo); ?>" alt="<?php echo htmlspecialchars($fixture->home_team_name); ?>" class="hero-logo">
        <span class="hero-team-name"><?php echo htmlspecialchars($fixture->home_team_name); ?></span>
    </div>
    <div class="hero-score">
        <div class="score"><?php echo (int)$fixture->home_team_score; ?> - <?php echo (int)$fixture->away_team_score; ?></div>
        <div class="match-status" 
             id="fixture-timer-display"
             data-status="<?php echo $fixture->status; ?>"
             data-first-half-start="<?php echo $fixture->first_half_start_time; ?>"
             data-second-half-start="<?php echo $fixture->second_half_start_time; ?>"
             data-first-half-end="<?php echo $fixture->first_half_end_time; ?>"
             data-full-time-duration="<?php echo (int)($settings['full_time_duration'] ?? 90); ?>"><?php echo htmlspecialchars(ucfirst($fixture->status)); ?></div>
        
        <?php if (!empty($hero_home_scorers) || !empty($hero_away_scorers)): ?>
            <div class="hero-scorers">
                <div class="h-scorers"><?php echo implode('<br>', $hero_home_scorers); ?></div>
                <div class="a-scorers"><?php echo implode('<br>', $hero_away_scorers); ?></div>
            </div>
        <?php endif; ?>
    </div>
    <div class="hero-team away">
        <img src="<?php echo htmlspecialchars($fixture->away_team_logo); ?>" alt="<?php echo htmlspecialchars($fixture->away_team_name); ?>" class="hero-logo">
        <span class="hero-team-name"><?php echo htmlspecialchars($fixture->away_team_name); ?></span>
    </div>
</div>

<!-- Match Day Sponsors -->
<?php if (!empty($matchSponsors)): ?>
<div class="match-sponsors" style="text-align: center; padding: 10px; background: #fff; border-bottom: 1px solid #eee;">
    <small style="text-transform: uppercase; color: #999; font-size: 0.7rem;">Match Day Sponsors</small>
    <div style="display: flex; justify-content: center; gap: 20px; margin-top: 5px;">
        <?php foreach ($matchSponsors as $sp): ?>
            <img src="<?php echo htmlspecialchars($sp->ad_content); ?>" alt="Sponsor" class="sponsor-ad" data-campaign-id="<?php echo $sp->id; ?>" style="height: 40px; object-fit: contain; cursor: pointer;">
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

<!-- Main View Tabs -->
<div class="main-tabs">
    <a href="?id=<?php echo $fixture_id; ?>&view=summary" class="tab-link <?php echo ($view === 'summary') ? 'active' : ''; ?>">Summary</a>
    <a href="?id=<?php echo $fixture_id; ?>&view=events" class="tab-link <?php echo ($view === 'events') ? 'active' : ''; ?>">Events</a>
    <a href="?id=<?php echo $fixture_id; ?>&view=lineups" class="tab-link <?php echo ($view === 'lineups') ? 'active' : ''; ?>">Lineups</a>
    <a href="?id=<?php echo $fixture_id; ?>&view=stats" class="tab-link <?php echo ($view === 'stats') ? 'active' : ''; ?>">Stats</a>
    <a href="?id=<?php echo $fixture_id; ?>&view=table" class="tab-link <?php echo ($view === 'table') ? 'active' : ''; ?>">Table</a>
    <a href="?id=<?php echo $fixture_id; ?>&view=h2h" class="tab-link <?php echo ($view === 'h2h') ? 'active' : ''; ?>">H2H</a>
</div>

<?php if ($fixture->status === 'finished'): ?>
    <div class="report-link-container">
        <a href="match_report.php?id=<?php echo $fixture_id; ?>" class="btn"><i class="fa-solid fa-file-alt"></i> View Match Report</a>
    </div>
<?php endif; ?>


<div class="page-content" style="padding-top: 0;">
    <!-- == SUMMARY VIEW (NEW) == -->
    <?php if ($view === 'summary'): ?>
    <div id="summary" class="tab-content active">
        <div class="match-detail-section">
            <h3>Match Information</h3>
            <div class="info-grid">
                <div class="info-item"><i class="fa-solid fa-calendar-day"></i><span><?php echo date('l, d F Y', strtotime($fixture->match_datetime)); ?></span></div>
                <div class="info-item"><i class="fa-solid fa-clock"></i><span><?php echo date('H:i', strtotime($fixture->match_datetime)); ?> (Local Time)</span></div>
                <div class="info-item"><i class="fa-solid fa-location-dot"></i><span><?php echo htmlspecialchars($fixture->venue ?? 'TBA'); ?></span></div>
                <div class="info-item"><i class="fa-solid fa-whistle"></i><span><?php echo htmlspecialchars($fixture->referee_name ?? 'TBA'); ?></span></div>
                <div class="info-item"><i class="fa-solid fa-user-tie"></i><span><?php echo htmlspecialchars($fixture->commissioner_name ?? 'TBA'); ?></span></div>
            </div>
        </div>

        <?php if ($prediction): ?>
        <div class="match-detail-section prediction-section">
            <h3><i class="fa-solid fa-brain"></i> AI Prediction</h3>
            <div class="prediction-content">
                <div class="prediction-outcome">
                    <span class="outcome-label">Probable Outcome</span>
                    <span class="outcome-value"><?php echo htmlspecialchars($prediction->outcome); ?></span>
                    <?php if (isset($prediction->confidence)): ?>
                        <span class="confidence-badge confidence-<?php echo strtolower($prediction->confidence); ?>">
                            <?php echo htmlspecialchars($prediction->confidence); ?> Confidence
                        </span>
                    <?php endif; ?>
                </div>
                <div class="prediction-reasoning">
                    <span class="reasoning-label">Reasoning</span>
                    <p><?php echo htmlspecialchars($prediction->reasoning); ?></p>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <?php if (!empty($productAds)): ?>
            <div class="match-detail-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; ?>
    </div>
    <?php endif; ?>

    <!-- == EVENTS VIEW (WAS SUMMARY) == -->
    <?php if ($view === 'events'): ?>
    <div id="events" class="tab-content active">
        <?php
        // Sort events chronologically for the timeline
        usort($match_events, function($a, $b) {
            if ($a->minute == $b->minute) return $a->id <=> $b->id;
            return $a->minute <=> $b->minute;
        });

        if ($fixture->status === 'finished' && !empty($fixture->man_of_the_match_player_id)): ?>
            <div class="match-detail-section motm-section">
                <h3>Man of the Match</h3>
                <div class="motm-player">
                    <i class="fa-solid fa-star"></i>
                    <span class="motm-name"><?php echo htmlspecialchars($fixture->motm_first_name . ' ' . $fixture->motm_last_name); ?></span>
                </div>
            </div>
        <?php endif; ?>

        <div class="match-detail-section" style="margin-top: 0; padding: 0;">
            <div class="timeline-header">Match Events</div>
            
            <?php if (empty($match_events)): ?>
                <div style="padding: 30px; text-align: center; color: #999; font-style: italic;">No events recorded for this match yet.</div>
            <?php else: ?>
                <div class="modern-timeline">
                    <div class="timeline-sticky-header" id="timeline-sticky-header">
                        <div class="tl-side home">
                            <span class="team-name-sticky"><?php echo htmlspecialchars($fixture->home_team_name); ?></span>
                        </div>
                        <div class="tl-center"></div>
                        <div class="tl-side away">
                            <span class="team-name-sticky"><?php echo htmlspecialchars($fixture->away_team_name); ?></span>
                        </div>
                    </div>
                    <div class="timeline-marker start">
                        <i class="fa-regular fa-clock"></i> Kick Off
                    </div>

                    <?php 
                    $halfTimeShown = false;
                    foreach ($match_events as $event): 
                        // Show Half Time marker if we pass 45 mins and haven't shown it
                        if (!$halfTimeShown && $event->minute > 45) {
                            echo '<div class="timeline-marker ht">Half Time</div>';
                            $halfTimeShown = true;
                        }

                        $isHome = ($event->team_id == $fixture->home_team_id);
                        $pName = htmlspecialchars($player_names[$event->player_id] ?? '');
                        
                        // Icon & Content Logic
                        $icon = '';
                        $primaryText = $pName;
                        $secondaryText = '';

                        switch ($event->event_type) {
                            case 'goal': 
                                $icon = '<i class="fa-solid fa-futbol" style="color: #2ecc71;"></i>'; 
                                if (!empty($event->assisted_by_player_id)) {
                                    $assistName = htmlspecialchars($player_names[$event->assisted_by_player_id] ?? '');
                                    if ($assistName) $secondaryText = "Assist: $assistName";
                                }
                                break;
                            case 'penalty_scored': 
                                $icon = '<i class="fa-solid fa-futbol" style="color: #2ecc71;"></i>'; 
                                $secondaryText = "(Penalty)";
                                break;
                            case 'own_goal': 
                                $icon = '<i class="fa-solid fa-futbol" style="color: #e74c3c;"></i>'; 
                                $secondaryText = "(Own Goal)";
                                break;
                            case 'penalty_missed': 
                                $icon = '<i class="fa-solid fa-circle-xmark" style="color: #e74c3c;"></i>'; 
                                $secondaryText = "Penalty Missed";
                                break;
                            case 'yellow_card': 
                                $icon = '<i class="fa-solid fa-square" style="color: #f1c40f;"></i>'; 
                                break;
                            case 'red_card': 
                                $icon = '<i class="fa-solid fa-square" style="color: #e74c3c;"></i>'; 
                                break;
                            case 'substitution': 
                                $icon = '<i class="fa-solid fa-right-left" style="color: #3498db;"></i>'; 
                                $pIn = htmlspecialchars($player_names[$event->assisted_by_player_id] ?? '');
                                $primaryText = "<span class='sub-in'>$pIn</span>";
                                $secondaryText = "<span class='sub-out'>$pName</span>";
                                break;
                            case 'corner': 
                                $icon = '<i class="fa-regular fa-flag" style="color: #34495e;"></i>'; 
                                $primaryText = 'Corner';
                                break;
                            case 'foul': 
                                $icon = '<i class="fa-solid fa-hand" style="color: #e67e22;"></i>'; 
                                $secondaryText = 'Foul';
                                break;
                            case 'offside': 
                                $icon = '<i class="fa-solid fa-flag" style="color: #e74c3c;"></i>'; 
                                $secondaryText = 'Offside';
                                break;
                            case 'shot_on_target': 
                                $icon = '<i class="fa-solid fa-bullseye" style="color: #2980b9;"></i>'; 
                                $secondaryText = 'Shot on Target';
                                break;
                            case 'shot_off_target': 
                                $icon = '<i class="fa-solid fa-crosshairs" style="color: #7f8c8d;"></i>'; 
                                $secondaryText = 'Shot off Target';
                                break;
                            default:
                                $icon = '<i class="fa-solid fa-circle-info"></i>';
                                $secondaryText = ucwords(str_replace('_', ' ', $event->event_type));
                        }
                        
                        // Stoppage time formatting (simplified)
                        $displayTime = $event->minute . "'";

                        // If player name is empty for events that might not have one, use the event type as primary text
                        if (empty($pName) && in_array($event->event_type, ['foul', 'offside', 'shot_on_target', 'shot_off_target'])) {
                            $primaryText = $secondaryText;
                            $secondaryText = '';
                        }
                    ?>
                    <div class="timeline-row">
                        <div class="tl-side home">
                            <?php if ($isHome): ?>
                                <div class="event-content">
                                    <div class="event-info">
                                        <div class="e-main"><?php echo $primaryText; ?></div>
                                        <?php if($secondaryText): ?><div class="e-sub"><?php echo $secondaryText; ?></div><?php endif; ?>
                                    </div>
                                    <div class="e-icon-wrapper"><?php echo $icon; ?></div>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="tl-center">
                            <div class="tl-time"><?php echo $displayTime; ?></div>
                            <div class="tl-line"></div>
                        </div>

                        <div class="tl-side away">
                            <?php if (!$isHome): ?>
                                <div class="event-content">
                                    <div class="e-icon-wrapper"><?php echo $icon; ?></div>
                                    <div class="event-info">
                                        <div class="e-main"><?php echo $primaryText; ?></div>
                                        <?php if($secondaryText): ?><div class="e-sub"><?php echo $secondaryText; ?></div><?php endif; ?>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    
                    <div class="timeline-marker end">
                        <?php echo ($fixture->status === 'finished') ? 'Full Time' : 'End of Events'; ?>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- == LINEUPS VIEW == -->
    <?php if ($view === 'lineups'): ?>
    <div id="lineups" class="tab-content active">
        <div class="match-detail-section lineup-view" style="margin-top: 0;">
            <?php
            $home_lineup_available = $home_lineup && !empty($home_lineup->starters);
            $away_lineup_available = $away_lineup && !empty($away_lineup->starters);

            function render_pitch_players($players_by_pos, $team_class, $player_details, $formation) {
                // Vertical Pitch Logic:
                // Away Team (Top Half): GK (Top) -> Def -> Mid -> Fwd (Center)
                // Home Team (Bottom Half): Fwd (Center) -> Mid -> Def -> GK (Bottom)
                $positions = ($team_class === 'home-team-pitch') 
                    ? ['Forward', 'Midfielder', 'Defender', 'Goalkeeper'] 
                    : ['Goalkeeper', 'Defender', 'Midfielder', 'Forward'];

                foreach ($positions as $position) {
                    echo "<div class='pitch-row'>";
                    if (!empty($players_by_pos[$position])) {
                        foreach ($players_by_pos[$position] as $player) {
                            echo "<a href='player.php?id={$player->id}' class='player-on-pitch'>
                                    <div class='player-avatar' data-player-id='{$player->id}'>
                                        <img src='" . htmlspecialchars($player_details[$player->id]->profile_picture ?? '/smart_football/public/assets/images/default_avatar.png') . "' alt='" . htmlspecialchars($player->last_name) . "'>
                                        <span class='player-squad-number'>" . htmlspecialchars($player_details[$player->id]->squad_number) . "</span>
                                    </div>
                                    <span class='player-name-label'>" . htmlspecialchars($player->last_name) . "</span>
                                  </a>";
                        }
                    }
                    echo "</div>";
                }
            }
            ?>
            <div class="lineup-header">
                <div class="lineup-team-info">
                    <img src="<?php echo htmlspecialchars($fixture->home_team_logo); ?>" alt="<?php echo htmlspecialchars($fixture->home_team_name); ?>">
                    <span><?php echo htmlspecialchars($fixture->home_team_name); ?></span>
                    <small><?php echo htmlspecialchars($home_lineup->formation ?? ''); ?></small>
                </div>
                <div class="lineup-team-info away">
                    <small><?php echo htmlspecialchars($away_lineup->formation ?? ''); ?></small>
                    <span><?php echo htmlspecialchars($fixture->away_team_name); ?></span>
                    <img src="<?php echo htmlspecialchars($fixture->away_team_logo); ?>" alt="<?php echo htmlspecialchars($fixture->away_team_name); ?>">
                </div>
            </div>
            <div class="full-pitch-container">
                <!-- Pitch Overlays -->
                <div class="pitch-overlay referee-badge">
                    <i class="fa-solid fa-whistle"></i> <?php echo htmlspecialchars($fixture->referee_name ?? 'Ref: TBA'); ?>
                </div>
                
                <div class="pitch-overlay manager-badge away-manager">
                    <small>Manager</small><br><?php echo htmlspecialchars($fixture->away_manager_name ?? 'TBA'); ?>
                </div>
                <div class="pitch-overlay manager-badge home-manager">
                    <small>Manager</small><br><?php echo htmlspecialchars($fixture->home_manager_name ?? 'TBA'); ?>
                </div>

                <div class="pitch-overlay formation-badge away-formation">
                    <?php echo htmlspecialchars($away_lineup->formation ?? ''); ?>
                </div>
                <div class="pitch-overlay formation-badge home-formation">
                    <?php echo htmlspecialchars($home_lineup->formation ?? ''); ?>
                </div>

                <div class="pitch-half away-team-pitch">
                    <?php
                    if ($away_lineup_available) {
                        $away_starters_by_pos = organize_by_position($away_lineup->starters, $player_details);
                        render_pitch_players($away_starters_by_pos, 'away-team-pitch', $player_details, $away_lineup->formation);
                    } else {
                        echo "<div class='tba-message'>Lineup To Be Announced</div>";
                    }
                    ?>
                </div>
                <div class="pitch-half home-team-pitch">
                    <?php
                    if ($home_lineup_available) {
                        $home_starters_by_pos = organize_by_position($home_lineup->starters, $player_details);
                        render_pitch_players($home_starters_by_pos, 'home-team-pitch', $player_details, $home_lineup->formation);
                    } else {
                        echo "<div class='tba-message'>Lineup To Be Announced</div>";
                    }
                    ?>
                </div>
            </div>

            <div class="benches-container">
                <!-- Home Bench -->
                <div class="bench-column">
                    <h4 class="bench-title">Bench</h4>
                    <ul class="player-list">
                        <?php if ($home_lineup_available): ?>
                            <?php foreach ($home_lineup->substitutes as $player_id): ?>
                                <li><a href="player.php?id=<?php echo $player_id; ?>"><span class="sub-squad-number"><?php echo htmlspecialchars($player_details[$player_id]->squad_number ?? ''); ?></span> <?php echo htmlspecialchars($player_names[$player_id] ?? 'Unknown Player'); ?></a></li>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <li class="tba-sub">To be announced</li>
                        <?php endif; ?>
                    </ul>
                    <?php if (!empty($home_unavailable['injured']) || !empty($home_unavailable['suspended'])): ?>
                        <div class="unavailable-container">
                            <div class="unavailable-header">Unavailable</div>
                            <ul class="unavailable-list">
                                <?php foreach($home_unavailable['injured'] as $p): ?>
                                    <li class="unavailable-item">
                                        <div class="unavailable-player">
                                            <i class="fa-solid fa-user-injured icon-injured"></i> 
                                            <?php echo htmlspecialchars($p->first_name . ' ' . $p->last_name); ?>
                                        </div>
                                        <div class="unavailable-detail"><?php echo htmlspecialchars($p->injury_description); ?></div>
                                    </li>
                                <?php endforeach; ?>
                                <?php foreach($home_unavailable['suspended'] as $p): ?>
                                    <li class="unavailable-item">
                                        <div class="unavailable-player">
                                            <i class="fa-solid fa-ban icon-suspended"></i> 
                                            <?php echo htmlspecialchars($p->first_name . ' ' . $p->last_name); ?>
                                        </div>
                                        <div class="unavailable-detail">Suspended: <?php echo htmlspecialchars($p->reason); ?></div>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    <?php endif; ?>
                </div>
                <!-- Away Bench -->
                <div class="bench-column">
                    <h4 class="bench-title">Bench</h4>
                    <ul class="player-list">
                        <?php if ($away_lineup_available): ?>
                            <?php foreach ($away_lineup->substitutes as $player_id): ?>
                                <li><a href="player.php?id=<?php echo $player_id; ?>"><span class="sub-squad-number"><?php echo htmlspecialchars($player_details[$player_id]->squad_number ?? ''); ?></span> <?php echo htmlspecialchars($player_names[$player_id] ?? 'Unknown Player'); ?></a></li>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <li class="tba-sub">To be announced</li>
                        <?php endif; ?>
                    </ul>
                     <?php if (!empty($away_unavailable['injured']) || !empty($away_unavailable['suspended'])): ?>
                        <div class="unavailable-container">
                            <div class="unavailable-header">Unavailable</div>
                            <ul class="unavailable-list">
                                <?php foreach($away_unavailable['injured'] as $p): ?>
                                    <li class="unavailable-item">
                                        <div class="unavailable-player">
                                            <i class="fa-solid fa-user-injured icon-injured"></i> 
                                            <?php echo htmlspecialchars($p->first_name . ' ' . $p->last_name); ?>
                                        </div>
                                        <div class="unavailable-detail"><?php echo htmlspecialchars($p->injury_description); ?></div>
                                    </li>
                                <?php endforeach; ?>
                                <?php foreach($away_unavailable['suspended'] as $p): ?>
                                    <li class="unavailable-item">
                                        <div class="unavailable-player">
                                            <i class="fa-solid fa-ban icon-suspended"></i> 
                                            <?php echo htmlspecialchars($p->first_name . ' ' . $p->last_name); ?>
                                        </div>
                                        <div class="unavailable-detail">Suspended: <?php echo htmlspecialchars($p->reason); ?></div>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php if (!$home_lineup_available && !$away_lineup_available): ?>
                <p class="no-data-msg">Lineups will be available 30 minutes before kick-off.</p>
            <?php endif; ?>
        </div>    
    </div>
    <?php endif; ?>

    <!-- == STATS VIEW == -->
    <?php if ($view === 'stats'): ?>
    <div id="stats" class="tab-content active">
        <div class="match-detail-section">
            <?php if ($match_stats): ?>
                <div class="stats-comparison-container">
                    <?php
                    $stat_map = [
                        'Shots' => 'shots',
                        'Shots on Target' => 'shots_on_target',
                        'Possession %' => 'possession',
                        'Corners' => 'corners',
                        'Fouls' => 'fouls',
                        'Yellow Cards' => 'yellow_cards',
                        'Red Cards' => 'red_cards',
                        'Offsides' => 'offsides',
                    ];

                    foreach ($stat_map as $label => $key):
                        $home_stat = $match_stats->home->$key ?? 0;
                        $away_stat = $match_stats->away->$key ?? 0;
                        $total = $home_stat + $away_stat;
                        $home_perc = $total > 0 ? ($home_stat / $total) * 100 : 50;
                        $away_perc = $total > 0 ? ($away_stat / $total) * 100 : 50;
                    ?>
                        <div class="stat-row"><span class="stat-value"><?php echo $home_stat; ?></span> <span class="stat-label"><?php echo $label; ?></span> <span class="stat-value"><?php echo $away_stat; ?></span></div>
                        <div class="stat-bar"><div class="bar-home" style="width: <?php echo $home_perc; ?>%;"></div><div class="bar-away" style="width: <?php echo $away_perc; ?>%;"></div></div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p class="no-data-msg">Match statistics are not available for this fixture yet.</p>
            <?php endif; ?>
        </div>
        <?php if (!empty($productAds)): ?>
            <div class="match-detail-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; ?>
    </div>
    <?php endif; ?>

    <!-- == TABLE VIEW == -->
    <?php if ($view === 'table'): ?>
    <div id="table" class="tab-content active">
        <div class="match-detail-section">
            <div class="sub-tabs" style="margin-bottom: 1.5rem;">
                <a href="?id=<?php echo $fixture_id; ?>&view=table&table_type=long#table" class="sub-tab-link <?php echo ($table_type === 'long') ? 'active' : ''; ?>">Overall</a>
                <a href="?id=<?php echo $fixture_id; ?>&view=table&table_type=form#table" class="sub-tab-link <?php echo ($table_type === 'form') ? 'active' : ''; ?>">Form</a>
            </div>

            <?php if (!empty($live_table)): ?>
                <div class="table-wrapper">
                    <table class="styled-table">
                        <thead>
                            <tr>
                                <th></th> <!-- Change Indicator -->
                                <th>#</th>
                                <th>Club</th>
                                <?php if ($table_type === 'long'): ?>
                                    <th>P</th>
                                    <th>W</th>
                                    <th>D</th>
                                    <th>L</th>
                                    <th>GF</th>
                                    <th>GA</th>
                                    <th>GD</th>
                                    <th>Pts</th>
                                <?php else: // 'form' view ?>
                                    <th class="form-header">Last 5</th>
                                    <th>Pts</th>
                                <?php endif; ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($live_table as $index => $team): 
                                $prev_rank = $prev_ranks[$team->team_id] ?? ($index + 1);
                                $diff = $prev_rank - ($index + 1);
                                $change_icon = '<i class="fa-solid fa-minus" style="color:#ccc; font-size:0.7rem;"></i>';
                                if ($diff > 0) $change_icon = '<i class="fa-solid fa-caret-up" style="color:#2ecc71;"></i> <small style="color:#2ecc71; font-weight:bold;">' . $diff . '</small>';
                                elseif ($diff < 0) $change_icon = '<i class="fa-solid fa-caret-down" style="color:#e74c3c;"></i> <small style="color:#e74c3c; font-weight:bold;">' . abs($diff) . '</small>';
                                
                                $is_playing = ($team->team_id == $fixture->home_team_id || $team->team_id == $fixture->away_team_id);
                            ?>
                                <tr class="<?php echo $is_playing ? 'highlighted-row' : ''; ?>">
                                    <td style="text-align: center; width: 30px;"><?php echo $change_icon; ?></td>
                                    <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 === 'long'): ?>
                                        <td><?php echo $team->played; ?></td>
                                        <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>
                                        <td><strong><?php echo $team->points; ?></strong></td>
                                    <?php else: // 'form' view ?>
                                        <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>
                                        <td><strong><?php echo $team->points; ?></strong></td>
                                    <?php endif; ?>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <p class="no-data-msg">The live league table could not be generated.</p>
            <?php endif; ?>
        </div>    
    </div>
    <?php endif; ?>

    <!-- == H2H VIEW == -->
    <?php if ($view === 'h2h'): ?>
    <div id="h2h" class="tab-content active">
        <div class="match-detail-section">
            <h3>Head to Head</h3>
            <div class="h2h-summary">
                <div class="h2h-team-stat">
                    <img src="<?php echo htmlspecialchars($fixture->home_team_logo); ?>" alt="">
                    <span><?php echo htmlspecialchars($fixture->home_team_name); ?></span>
                    <div class="h2h-wins"><?php echo $home_wins; ?> Wins</div>
                </div>
                <div class="h2h-draws">
                    <div class="h2h-draw-value"><?php echo $draws; ?></div>
                    <span>Draws</span>
                </div>
                <div class="h2h-team-stat">
                    <img src="<?php echo htmlspecialchars($fixture->away_team_logo); ?>" alt="">
                    <span><?php echo htmlspecialchars($fixture->away_team_name); ?></span>
                    <div class="h2h-wins"><?php echo $away_wins; ?> Wins</div>
                </div>
            </div>
        </div>

        <div class="match-detail-section">
            <h4>Previous Meetings</h4>
            <?php if (empty($h2h_matches)): ?>
                <p class="no-data-msg">No previous meetings found between these two teams.</p>
            <?php else: ?>
                <div class="fixture-list">
                    <?php foreach ($h2h_matches as $match): ?>
                        <a href="fixture.php?id=<?php echo $match->id; ?>" class="fixture-item">
                            <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>
                            <div class="score-box finished">
                                <span class="score"><?php echo $match->home_team_score ?? 0; ?> - <?php echo $match->away_team_score ?? 0; ?></span>
                                <span class="date"><?php echo date('d M Y', strtotime($match->match_datetime)); ?></span>
                            </div>
                            <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>
                        </a>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>
</div>

<style>
/* App-like Styling Improvements */
.hero-team-name { font-weight: 600; letter-spacing: 0.5px; margin-top: 10px; }
.hero-score .score { font-size: 2.5rem; font-weight: 700; text-shadow: 0 2px 4px rgba(0,0,0,0.3); }
.match-status { background: rgba(255,255,255,0.15); padding: 4px 12px; border-radius: 20px; font-size: 0.85rem; backdrop-filter: blur(5px); }

.match-hero { position: relative; }
.league-badge-overlay {
    position: absolute;
    top: 15px;
    left: 50%;
    transform: translateX(-50%);
    background: rgba(255,255,255,0.2);
    padding: 4px 12px;
    border-radius: 15px;
    font-size: 0.8rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 1px;
}

.hero-scorers {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 10px;
    font-size: 0.8rem;
    line-height: 1.3;
    opacity: 0.9;
}
.h-scorers { text-align: right; }
.a-scorers { text-align: left; }

.main-tabs {
    display: flex;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    scrollbar-width: none; /* For Firefox */
    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;
}
.main-tabs::-webkit-scrollbar {
    display: none; /* For Chrome, Safari, and Opera */
}
.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; }

.match-detail-section {
    background: #fff;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.04);
    margin-bottom: 20px;
    border: 1px solid #f1f5f9;
}
.match-detail-section h3 {
    font-size: 1.1rem;
    color: #1e293b;
    margin-top: 0;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e2e8f0;
}

.info-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 1.5rem;
}
.info-item {
    display: flex;
    align-items: center;
    gap: 10px;
    background-color: #f8fafc;
    padding: 15px;
    border-radius: 8px;
}
.info-item i {
    color: var(--primary-color);
    font-size: 1.2rem;
}

.prediction-section {
    background-color: #f1f5f9;
    border-left: 5px solid var(--primary-color);
}
.prediction-content {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}
.prediction-outcome .outcome-value {
    font-size: 2.5rem;
    font-weight: bold;
    letter-spacing: 2px;
    color: var(--primary-color);
}
.prediction-reasoning {
    border-top: 1px solid #e0e0e0;
    padding-top: 1rem;
}
.prediction-reasoning p { margin: 0; color: #333; }

.confidence-badge {
    display: inline-block;
    font-size: 0.75rem;
    padding: 3px 8px;
    border-radius: 12px;
    font-weight: 700;
    text-transform: uppercase;
    margin-top: 5px;
    color: white;
}
.confidence-high { background-color: #27ae60; }
.confidence-medium { background-color: #f39c12; }
.confidence-low { background-color: #95a5a6; }

.motm-section {
    text-align: center;
    background-color: #fdfae1;
    border: 1px solid #f1c40f;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 2rem;
}
.motm-player {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    font-size: 1.2rem;
    font-weight: bold;
}
.motm-player .fa-star { color: #f1c40f; }

.timeline-container {
    position: relative;
    padding: 20px 0;
}
.timeline-container::before {
    content: '';
    position: absolute;
    top: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 2px;
    height: 100%;
    background-color: #e2e8f0;
}
.timeline-event {
    display: flex;
    align-items: center;
    position: relative;
    margin: 10px 0;
    width: 50%;
    box-sizing: border-box; /* Prevent padding from breaking width */
}
.timeline-event .event-details { flex: 1; min-width: 0; text-align: right; padding-right: 20px; font-size: 0.9rem; word-wrap: break-word; overflow-wrap: break-word; white-space: normal; }
.timeline-event .event-icon { width: 36px; height: 36px; border-radius: 50%; background-color: #fff; border: 2px solid #e2e8f0; display: flex; justify-content: center; align-items: center; z-index: 1; box-shadow: 0 2px 4px rgba(0,0,0,0.05); flex-shrink: 0; }
.timeline-event .minute { font-weight: bold; padding-left: 20px; }

.home-event {
    justify-content: flex-end;
    left: 0;
    padding-right: 20px;
}

.away-event {
    left: 50%;
    padding-left: 20px;
}
.away-event .event-details { order: 3; text-align: left; padding-left: 20px; padding-right: 0; }
.away-event .event-icon { order: 2; }
.away-event .minute { order: 1; padding-left: 0; padding-right: 20px; }

.player-name { display: block; }
.assist-text {
    color: #777;
    font-size: 0.85em;
}

.pitch-row {
    display: flex;
    justify-content: space-around;
    align-items: center;
}

.player-on-pitch {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
}

.stats-comparison-container {
    padding: 1rem 0;
}
.stat-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: bold;
    margin-bottom: 5px;
}
.stat-label {
    font-size: 0.9rem;
    color: #555;
}
.stat-value {
    font-size: 1.1rem;
}
.stat-bar {
    display: flex;
    height: 8px;
    border-radius: 4px;
    overflow: hidden;
    background-color: #e9ecef;
    margin-bottom: 1.2rem;
}
.bar-home {
    background-color: var(--primary-color); /* Or your home team's color */
}
.bar-away {
    background-color: #7f8c8d; /* Or your away team's color */
}

.lineup-view {
    --home-color: #3498db;
    --away-color: #e74c3c;
}

.lineup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    background-color: #f8fafc;
    border-radius: 8px;
    margin-bottom: 1rem;
}
.lineup-team-info {
    display: flex;
    align-items: center;
    gap: 15px;
    font-size: 1.2rem;
    font-weight: bold;
}
.lineup-team-info img { width: 40px; height: 40px; }
.lineup-team-info small { font-size: 0.9rem; color: #555; font-weight: normal; }

.full-pitch-container {
    background-color: #27ae60;
    background-image: url('/smart_football/public/assets/images/pitch.svg');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    background-blend-mode: multiply;
    display: flex;
    flex-direction: column;
    height: auto;
    min-height: 700px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    margin-bottom: 2rem;
    position: relative;
    overflow: hidden;
}
.pitch-half {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    padding: 20px 0;
}
.home-team-pitch { flex-direction: column; }
.away-team-pitch { flex-direction: column; }

.player-avatar {
    position: relative;
    width: 38px;
    height: 38px;
}
.player-avatar img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 50%;
    border: 2px solid white;
    box-shadow: 0 2px 4px rgba(0,0,0,0.5);
}
.player-squad-number {
    position: absolute;
    bottom: -5px;
    left: 50%;
    transform: translateX(-50%);
    background-color: rgba(0,0,0,0.7);
    color: white;
    font-size: 0.7rem;
    font-weight: bold;
    padding: 1px 5px;
    border-radius: 4px;
}
.player-name-label {
    background-color: rgba(0, 0, 0, 0.7);
    color: white;
    font-size: 0.65rem;
    padding: 2px 6px;
    border-radius: 4px;
    white-space: nowrap;
}

.benches-container {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 2rem;
    margin-top: 2rem;
    background-color: #f8fafc;
    padding: 20px;
    border-radius: 8px;
}
.bench-title {
    text-align: center;
    font-size: 1.1rem;
    margin-bottom: 1rem;
}
.player-list {
    list-style: none;
    padding: 0;
    margin: 0;
}
.player-list.unavailable li {
    color: #777;
    font-style: italic;
}
.player-list li {
    padding: 8px 5px;
    border-bottom: 1px solid #e2e8f0;
}
.player-list li a {
    text-decoration: none;
    color: #333;
    display: flex;
    align-items: center;
    gap: 10px;
}
.sub-squad-number {
    font-weight: normal;
    color: #888;
    width: 20px;
}

.tba-message {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    color: rgba(255, 255, 255, 0.7);
    font-weight: bold;
    font-size: 1.2rem;
    text-align: center;
}
.tba-sub {
    color: #888;
    font-style: italic;
}

/* Pitch Overlays */
.pitch-overlay {
    position: absolute;
    background-color: rgba(0, 0, 0, 0.6);
    color: #fff;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 0.50rem;
    z-index: 10;
    pointer-events: none;
}

.referee-badge {
    top: 10px;
    right: 10px;
    background-color: rgba(0, 0, 0, 0.8);
    border: 1px solid #555;
    font-size: 0.50rem;
}

.manager-badge {
    left: 10px;
    font-weight: bold;
    text-align: left;
    font-size: 0.50rem;
}
.manager-badge small { font-weight: normal; opacity: 0.8; font-size: 0.65rem; }
.manager-badge.away-manager { top: 20px; }
.manager-badge.home-manager { bottom: 20px; }

.formation-badge {
    right: 10px;
    font-weight: bold;
    background-color: rgba(255, 255, 255, 0.9);
    color: #333;
}
.formation-badge.away-formation { top: 48%; transform: translateY(-100%); }
.formation-badge.home-formation { bottom: 48%; transform: translateY(100%); }

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

/* Unavailable Players Styling */
.unavailable-container {
    margin-top: 1.5rem;
    background-color: #fff5f5;
    border-radius: 6px;
    border: 1px solid #ffebeb;
    overflow: hidden;
}
.unavailable-header {
    background-color: #ffebeb;
    color: #c0392b;
    padding: 8px 12px;
    font-size: 0.85rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}
.unavailable-list {
    list-style: none;
    padding: 0;
    margin: 0;
}
.unavailable-item {
    padding: 10px 12px;
    border-bottom: 1px solid #ffebeb;
    display: flex;
    flex-direction: column;
    gap: 2px;
}
.unavailable-item:last-child {
    border-bottom: none;
}
.unavailable-player {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    color: #444;
    font-size: 0.9rem;
}
.unavailable-detail {
    font-size: 0.75rem;
    color: #e74c3c;
    margin-left: 24px;
    font-style: italic;
}
.icon-injured { color: #e74c3c; width: 16px; text-align: center; }
.icon-suspended { color: #c0392b; width: 16px; text-align: center; }

/* Live Table Highlights */
.highlighted-row {
    background-color: #fff8e1 !important; /* Light yellow highlight */
    border-left: 3px solid #f1c40f;
}

/* H2H Summary Styles */
.h2h-summary {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #f8f9fa;
    padding: 20px;
    border-radius: 8px;
}
.h2h-team-stat {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    font-weight: bold;
}
.h2h-team-stat img {
    width: 60px;
    height: 60px;
}
.h2h-wins {
    font-size: 1.2rem;
    color: var(--primary-color);
}
.h2h-draws { text-align: center; }
.h2h-draw-value { font-size: 2rem; font-weight: 800; }

/* Sticky Timeline Header */
.timeline-sticky-header {
    display: none; /* Hidden by default */
    position: sticky;
    /* top value will be set by JS */
    background: #f8f9fa;
    z-index: 900;
    padding: 10px 0;
    border-bottom: 1px solid #eee;
    box-shadow: 0 2px 5px rgba(0,0,0,0.05);
}
.timeline-sticky-header.visible {
    display: flex;
}
.timeline-sticky-header .tl-side { padding: 0 15px; align-items: center; }
.team-name-sticky { font-weight: 700; font-size: 1rem; }

/* Modern Timeline Styles */
.timeline-header {
    padding: 15px 20px;
    font-weight: 700;
    border-bottom: 1px solid #eee;
    background: #f8f9fa;
    color: #333;
    font-size: 1rem;
    border-radius: 12px 12px 0 0;
}

.modern-timeline {
    position: relative;
    padding: 20px 0;
    background: #fff;
}

.timeline-marker {
    text-align: center;
    font-weight: 700;
    color: #777;
    font-size: 0.85rem;
    text-transform: uppercase;
    margin: 15px 0;
    position: relative;
    z-index: 2;
}
.timeline-marker.ht, .timeline-marker.start, .timeline-marker.end {
    background: #f1f3f5;
    display: inline-block;
    padding: 4px 12px;
    border-radius: 12px;
    left: 50%;
    transform: translateX(-50%);
}

.timeline-row {
    display: flex;
    align-items: stretch;
    min-height: 50px;
    position: relative;
}

.tl-side {
    flex: 1;
    padding: 10px 15px;
    display: flex;
    align-items: center;
}
.tl-side.home { justify-content: flex-end; text-align: right; }
.tl-side.away { justify-content: flex-start; text-align: left; }

.tl-center {
    width: 50px;
    position: relative;
    display: flex;
    justify-content: center;
    flex-shrink: 0;
}

.tl-time {
    background: #fff;
    border: 2px solid #eee;
    color: #333;
    font-weight: 700;
    font-size: 0.8rem;
    width: 34px;
    height: 34px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 2;
    margin-top: 10px;
}

.tl-line {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 50%;
    width: 2px;
    background: #eee;
    transform: translateX(-1px);
    z-index: 1;
}

.event-content { display: flex; align-items: center; gap: 12px; max-width: 100%; }
.e-icon-wrapper { width: 30px; text-align: center; font-size: 1.1rem; flex-shrink: 0; }
.event-info { display: flex; flex-direction: column; }
.e-main { font-weight: 600; font-size: 0.95rem; color: #2c3e50; }
.e-sub { font-size: 0.8rem; color: #7f8c8d; }

/* Specific Event Styles */
.type-goal .e-icon-wrapper { color: #2ecc71; }
.type-own-goal .e-icon-wrapper { color: #e74c3c; }
.type-miss .e-icon-wrapper { color: #e74c3c; }
.type-sub .e-icon-wrapper { color: #3498db; font-size: 0.9rem; }

.card-icon {
    width: 14px;
    height: 20px;
    border-radius: 2px;
    display: inline-block;
    box-shadow: 0 1px 3px rgba(0,0,0,0.2);
}
.card-icon.yellow { background: #f1c40f; }
.card-icon.red { background: #e74c3c; }

.sub-in { color: #27ae60; font-weight: 600; }
.sub-in::before { content: '▲ '; font-size: 0.7em; }
.sub-out { color: #e74c3c; font-size: 0.85em; }
.sub-out::before { content: '▼ '; font-size: 0.7em; }
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const timerDisplay = document.getElementById('fixture-timer-display');
    if (timerDisplay) {
        const firstHalfStart = timerDisplay.dataset.firstHalfStart;
        const secondHalfStart = timerDisplay.dataset.secondHalfStart;
        const firstHalfEnd = timerDisplay.dataset.firstHalfEnd;
        let status = timerDisplay.dataset.status;

        // Robust check for Half Time: If status is 'live' but 1st half ended and 2nd hasn't started
        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';
        }

        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(startTime, offsetMinutes) {
            if (status !== 'live') return; // Only run timer if status is 'live'
            const matchStartTime = new Date(startTime).getTime();
            const fullTimeDuration = parseInt(timerDisplay.dataset.fullTimeDuration || 90);
            const halfTimeMark = fullTimeDuration / 2;
            
            const timerInterval = setInterval(() => {
                const now = new Date().getTime();
                const elapsedSeconds = Math.floor((now - matchStartTime) / 1000);
                let displaySeconds = (offsetMinutes * 60) + elapsedSeconds;

                // Handle stoppage time display
                if (displaySeconds >= halfTimeMark * 60 && offsetMinutes < halfTimeMark) {
                    const stoppageSeconds = displaySeconds - (halfTimeMark * 60);
                    timerDisplay.textContent = `${formatTime(halfTimeMark * 60)} +${formatTime(stoppageSeconds)}`;
                } else if (displaySeconds >= fullTimeDuration * 60) {
                    const stoppageSeconds = displaySeconds - (fullTimeDuration * 60);
                    timerDisplay.textContent = `${formatTime(fullTimeDuration * 60)} +${formatTime(stoppageSeconds)}`;
                } else {
                    timerDisplay.textContent = formatTime(displaySeconds);
                }
            }, 1000);
        }

        if (status === 'half_time') {
            timerDisplay.textContent = 'Half Time';
        } else if (status === 'finished' || status === 'full_time') {
            timerDisplay.textContent = 'Full Time';
        } else if (status === 'live' && secondHalfStart && secondHalfStart !== '0000-00-00 00:00:00') {
            startTimer(secondHalfStart, (parseInt(timerDisplay.dataset.fullTimeDuration || 90) / 2));
        } else if (status === 'live' && firstHalfStart && firstHalfStart !== '0000-00-00 00:00:00') {
            startTimer(firstHalfStart, 0);
        } else {
            // Use JavaScript to capitalize the first letter for the fallback status
            timerDisplay.textContent = status.charAt(0).toUpperCase() + status.slice(1);
        }
    }

    // --- Sticky Header for Events Timeline ---
    const heroSection = document.querySelector('.match-hero');
    const stickyHeader = document.getElementById('timeline-sticky-header');
    const eventsTab = document.getElementById('events');
    const mainTabs = document.querySelector('.main-tabs');

    if (heroSection && stickyHeader && eventsTab && mainTabs) {
        const mainTabsHeight = mainTabs.offsetHeight;
        stickyHeader.style.top = `${mainTabsHeight}px`;

        const observer = new IntersectionObserver(
            ([entry]) => {
                // Only do this if the events tab is active
                if (eventsTab.classList.contains('active')) {
                    if (!entry.isIntersecting) {
                        stickyHeader.classList.add('visible');
                    } else {
                        stickyHeader.classList.remove('visible');
                    }
                }
            },
            {
                root: null,
                threshold: 0,
                rootMargin: `-${mainTabsHeight}px 0px 0px 0px`
            }
        );

        observer.observe(heroSection);

        // Also need to hide it if we switch tabs
        document.querySelectorAll('.tab-link').forEach(link => {
            link.addEventListener('click', () => {
                setTimeout(() => {
                    if (!eventsTab.classList.contains('active')) {
                        stickyHeader.classList.remove('visible');
                    } else {
                        const isHeroVisible = heroSection.getBoundingClientRect().bottom > mainTabsHeight;
                        if (!isHeroVisible) {
                            stickyHeader.classList.add('visible');
                        }
                    }
                }, 10);
            });
        });
    }
});
</script>

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