<?php
date_default_timezone_set('Europe/London');
$API_KEY = "492939";

// Set sport to 'Soccer' to match TheSportsDB naming
$selectedSport = $_GET['sport'] ?? 'Soccer';
//$selectedLeague = $_GET['league'] ?? 'all';
$selectedLeague = $_GET['league'] ?? 'English Premier League';

// Fetch all leagues from TheSportsDB
$leagueData = file_get_contents("https://www.thesportsdb.com/api/v1/json/492939/all_leagues.php");
$leagueList = json_decode($leagueData, true);

$targetLeagues = [];
foreach ($leagueList['leagues'] as $league) {
    if ($league['strSport'] === $selectedSport) {
        $targetLeagues[] = $league['strLeague'];
    }
}

$allEvents = [];

// Pull 7 days of events
for ($i = 0; $i < 7; $i++) {
    $date = date('Y-m-d', strtotime("+$i day"));
    $url = "https://www.thesportsdb.com/api/v1/json/{$API_KEY}/eventsday.php?d={$date}";
    $json = @file_get_contents($url);
    $data = json_decode($json, true);

    if (!empty($data['events'])) {
        foreach ($data['events'] as $event) {
            if ($event['strSport'] === $selectedSport && in_array($event['strLeague'], $targetLeagues)) {
                if ($selectedLeague === 'all' || $selectedLeague === $event['strLeague']) {
                    $event['matchDate'] = $date;
                    $allEvents[] = $event;
                }
            }
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Sports Guide</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <header>
        <h1>Upcoming Sports Events</h1>
    </header>

    <section class="filters">
        <form method="get">
            <input type="hidden" name="sport" value="<?= htmlspecialchars($selectedSport) ?>">
            <label for="league">Filter by League:</label>
            <select name="league" id="league" onchange="this.form.submit()">
                <option value="all" <?= $selectedLeague === 'all' ? 'selected' : '' ?>>All</option>
                <?php foreach ($targetLeagues as $league): ?>
                    <option value="<?= htmlspecialchars($league) ?>" <?= $selectedLeague === $league ? 'selected' : '' ?>>
                        <?= htmlspecialchars($league) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </form>
    </section>

    <section class="events">
        <?php if (!empty($allEvents)): ?>
            <?php
            $grouped = [];
            foreach ($allEvents as $event) {
                $grouped[$event['matchDate']][] = $event;
            }

            foreach ($grouped as $date => $events):
            ?>
                <h2 class="date-heading"><?= date('l, j F Y', strtotime($date)) ?></h2>
                <div class="event-row">
                    <?php foreach ($events as $event): ?>
                        <div class="event-card">
                            <div class="team-logos">
                                <img src="<?= $event['strHomeTeamBadge'] ?? '#' ?>" alt="<?= $event['strHomeTeam'] ?>">
                                <span>vs</span>
                                <img src="<?= $event['strAwayTeamBadge'] ?? '#' ?>" alt="<?= $event['strAwayTeam'] ?>">
                            </div>
                            <div class="event-info">
                                <strong><?= htmlspecialchars($event['strEvent']) ?></strong><br>
                                <?= htmlspecialchars($event['strLeague']) ?><br>
                                <?= date('H:i', strtotime($event['strTime'])) ?>
                                <?php if (!empty($event['strTVStation'])): ?>
                                    <div class="tv-channel">Watch on: <?= htmlspecialchars($event['strTVStation']) ?></div>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <p>No events scheduled in <?= htmlspecialchars($selectedSport) ?> over the next 7 days.</p>
        <?php endif; ?>
    </section>
</body>
</html>