<!DOCTYPE html>
<html lang="it">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sport Guide</title>
    <style>
        body, html {
            margin: 0;
            padding: 0;
            overflow: hidden;
            background-color: #000;
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100%;
        }
        .poster {
            position: absolute;
            width: 100%;
            height: 100%;
            left: 0;
            top: 0;
            background-image: url('https://library.sportingnews.com/styles/twitter_card_120x120/s3/2022-06/premier-league-clubs-badges-2022.jpg');
            background-size: cover;
            background-position: center;
            padding: 10px; /* Reduced padding */
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
            opacity: 0;
            transition: opacity 1s ease-in-out;
            display: flex;
            flex-direction: column;
            justify-content: center; /* Center content vertically */
            align-items: center; /* Center content horizontally */
        }
        .poster::before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.8); /* Dark overlay */
            z-index: 1;
        }
        .poster-content {
            text-align: center;
            color: white;
            width: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            position: relative; /* To be above the overlay */
            z-index: 2;
        }
        .poster.active {
            opacity: 1;
        }
        .match-info-container {
            margin-top: 20px; /* Reduced margin from the top */
            display: flex;
            flex-direction: column;
            align-items: center;
            width: 100%;
        }
        .match-tital-container {
            margin-top: 20px; /* Reduced margin from the top */
            display: flex;
            flex-direction: column;
            align-items: center;
            width: 100%;
        }
        .team-logos {
            display: flex;
            justify-content: space-around; /* Ensure space around the logos */
            align-items: center; /* Center content vertically */
            width: 100%;
            max-width: 800px; /* Increase max-width to add more space between logos */
            margin-bottom: 20px; /* Reduced margin between team logos and rest of the content */
            position: relative; /* Position relative for absolute positioning of match time */
            gap: 80px; /* Adjust gap between logos for balanced spacing */
        }
        .team-logo-container {
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .team-logo {
            height: 130px; /* Adjustable size of team logos */
            margin: 0 10px; /* Reduced margin */
        }
        .team-name {
            color: white;
            font-size: 26px; /* Adjustable font size for team names */
            font-weight: 800; /* Extra bold text */
            margin-top: -5px;
            text-align: center;
        }
        .match-time {
            font-size: 36px; /* Reduced font size for match time */
            font-weight: bold;
            color: #fff;
            position: absolute; /* Position it in the center */
            top: 50%; /* Vertically center */
            left: 50%; /* Horizontally center */
            transform: translate(-50%, -50%); /* Adjust position to perfectly center */
            background-color: rgba(0, 0, 0, 0.0); /* No background to keep clear */
            padding: 5px 15px; /* Reduced padding around the match time */
            border-radius: 10px; /* Rounded corners for better aesthetics */
        }
        .match-info {
            font-size: 18px; /* Reduced font size for date and stadium */
            color: #aaa;
            font-weight: bold;
            margin: 0; /* Removed margin */
        }
        .match-tital {
            font-size: 25px; /* Reduced font size for date and stadium */
            color: #fff;
            font-weight: bold;
            margin: 0; /* Removed margin */
        }
        .channel-info {
            margin-top: 10px; /* Reduced margin between channel list and match info */
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            align-items: flex-start;
            text-align: left; /* Align text to the left */
            width: 100%;
            max-width: 1000px; /* Adjust max-width as needed */
        }
        .channel-column {
            flex: 1; /* Equal width for each column */
            min-width: 250px; /* Minimum width for each column */
            margin-right: 10px; /* Space between columns */
        }
        .channel-item {
            display: flex;
            margin: 2px 0; /* Reduced margin for more compact display */
            align-items: center;
        }
        .channel-item span.country {
            font-weight: bold;
            color: #ffbf00; /* Country text color */
            width: 120px; /* Fixed width for alignment */
            text-align: right; /* Align text to the right */
            display: inline-block; /* To keep the vertical alignment */
        }
        .channel-item span.channel {
            display: inline-block; /* Display channel inline */
            color: #0f0; /* Channel text color */
            margin-left: 5px; /* Less margin to fit more channels */
            white-space: nowrap; /* Prevent wrapping */
        }
        .control-button, .next-button, .prev-button {
            position: absolute;
            background-color: rgba(255, 255, 255, 0.9);
            border: none;
            padding: 20px;
            border-radius: 50%;
            cursor: pointer;
            font-size: 20px;
            color: #ff0000;
            z-index: 3;
            transition: background-color 0.3s ease;
        }
        .control-button:hover, .next-button:hover, .prev-button:hover {
            background-color: #ff0000;
            color: #fff;
        }
        .control-button {
            top: 10px;
            left: 10px;
        }
        .prev-button {
            left: 10px;
            top: 50%;
            transform: translateY(-50%);
        }
        .next-button {
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
        }
        .loading-container {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100%;
            width: 100%;
        }
        .loading-spinner {
            border: 16px solid #f3f3f3;
            border-radius: 50%;
            border-top: 16px solid #3498db;
            width: 120px;
            height: 120px;
            animation: spin 2s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    
<div id="loading" class="loading-container">
    <div class="loading-spinner"></div>
</div>

<div id="poster-container">

<?php
    include ('APIkey.php');
    include(__DIR__ . '/../includes/functions.php');
    global $db; 
    $mes = $db->select('leagueshift', '*', 'id = :id', '', [':id' => 1]);
    $res = $db->select('leaguesx', '*', '', '');
    
    $urlsfb = array(); 
    
    $apie_key = getApiKey();
    
    
    $currentCla = $mes[0]['cla'] ?? '+'; 
    $currentTime = $mes[0]['time'] ?? '0';
    
    $finaltime = "$currentCla $currentTime"; 
    
    
    function fetchEvents($apiUrl) {
        $json = file_get_contents($apiUrl);
        $data = json_decode($json, true);

        if ($data && isset($data['events'])) {
            return $data['events'];
        }
        return [];
    }

    function displayEvents($events, $finaltime, $mapikey) {
        foreach ($events as $event) {
            $eventName = $event['strEvent'];
            $eventDate = date("l, F j, Y", strtotime($event['dateEvent']));
            $eventTime = $event['strTime'];
            
           $eventTimePlus = date("g:i A", strtotime($eventTime. ' ' . $finaltime.' minutes'));
            $homeTeam = $event['strHomeTeam'];
            $awayTeam = $event['strAwayTeam'];
            $homeTeamLogo = $event['strHomeTeamBadge'];
            $awayTeamLogo = $event['strAwayTeamBadge'];
            $eventcity = $event['strCity'];
            $eventstadian = $event['strVenue'];
            $strLeague = $event['strLeague'];

            echo "<div class='poster'>";
            echo "<div class='poster-content'>";
            echo "<div class='match-info-container'>";
            echo "<div class='team-logos'>";
            echo "<div class='team-logo-container'><img src='$homeTeamLogo' class='team-logo' alt='$homeTeam Logo'><div class='team-name'>$homeTeam</div></div>";
            echo "<div class='team-logo-container'><img src='$awayTeamLogo' class='team-logo' alt='$awayTeam Logo'><div class='team-name'>$awayTeam</div></div>";
            echo "<div class='match-time'>$eventTimePlus</div>";
            echo "</div>";
            echo "<div class='match-info'>$eventDate | $eventcity | $eventstadian</div>";
            echo "<div class='match-tital'>$strLeague</div>";
            echo "</div>";

            // Fetch channels showing this event
            $eventId = $event['idEvent'];
            $channelUrl = "https://www.thesportsdb.com/api/v1/json/$mapikey/lookuptv.php?id=$eventId";
            $channelData = json_decode(file_get_contents($channelUrl), true);

            echo "<div class='channel-info'>";
            if (isset($channelData['tvevent']) && count($channelData['tvevent']) > 0) {
                $channels = $channelData['tvevent'];
                
                // Sort channels to start with 'United Kingdom'
                usort($channels, function($a, $b) {
                    if ($a['strCountry'] === 'United Kingdom') return -1;
                    if ($b['strCountry'] === 'United Kingdom') return 1;
                    return strcmp($a['strCountry'], $b['strCountry']);
                });

                $totalChannels = count($channels);
                $columns = 2; // Split into 2 columns
                if ($totalChannels > 12) $columns = 3; // Split into 3 columns if there are more channels
                $itemsPerColumn = ceil($totalChannels / $columns);
                $chunks = array_chunk($channels, $itemsPerColumn);

                foreach ($chunks as $chunk) {
                    echo "<div class='channel-column'>"; // Start of channel column
                    foreach ($chunk as $channel) {
                        $country = $channel['strCountry'] ?? 'Unknown';
                        $channelName = $channel['strChannel'] ?? 'Unknown';
                        echo "<div class='channel-item'><span class='country'>$country</span> <span class='channel'>$channelName</span></div>";
                    }
                    echo "</div>"; // end of channel-column
                }
            } else {
                echo "<p>No channels available</p>";
            }
            echo "</div>"; // end of channel-info
            echo "</div>"; // end of poster-content
            echo "</div>"; // end of poster
        }
    }
    
    foreach ($res as $index => $row) {
        $leagueId = $row['leagueId'];
        $apiUrl = 'https://www.thesportsdb.com/api/v1/json/'.$apie_key.'/eventsnextleague.php?id=' . $leagueId;
        $events = fetchEvents($apiUrl);
         displayEvents($events, $finaltime,$apie_key);
    }
    ?>

</div>

<button class="control-button" id="playPauseBtn">Pause</button>
<button class="prev-button" id="prevBtn">&#9664;</button>
<button class="next-button" id="nextBtn">&#9654;</button>

<script>

    function displayLoading(show) {
        const loadingElement = document.getElementById('loading');
        const posterContainer = document.getElementById('poster-container');
        if (show) {
            loadingElement.style.display = 'flex';
            posterContainer.style.display = 'none';
        } else {
            loadingElement.style.display = 'none';
            posterContainer.style.display = 'block';
        }
    }

    const posters = document.querySelectorAll('.poster');
    const playPauseBtn = document.getElementById('playPauseBtn');
    const nextBtn = document.getElementById('nextBtn');
    const prevBtn = document.getElementById('prevBtn');
    let currentIndex = 0;
    let intervalId;

    function showPoster(index) {
        posters.forEach((poster, i) => poster.classList.remove('active')); // Remove 'active' from all
        posters[index].classList.add('active'); // Add 'active' to the current
    }

    function showNextPoster() {
        const nextIndex = (currentIndex + 1) % posters.length;
        showPoster(nextIndex);
        currentIndex = nextIndex;
    }

    function showPrevPoster() {
        const prevIndex = (currentIndex - 1 + posters.length) % posters.length;
        showPoster(prevIndex);
        currentIndex = prevIndex;
        displayLoading(false);
    }

    function startSlideshow() {
        intervalId = setInterval(showNextPoster, 5000);
        displayLoading(false);
    }

    function stopSlideshow() {
        clearInterval(intervalId);
    }

    playPauseBtn.addEventListener('click', () => {
        if (playPauseBtn.textContent === 'Pause') {
            stopSlideshow();
            playPauseBtn.textContent = 'Play';
        } else {
            startSlideshow();
            playPauseBtn.textContent = 'Pause';
        }
    });

    nextBtn.addEventListener('click', showNextPoster);
    prevBtn.addEventListener('click', showPrevPoster);

    // Initial state
    posters[0].classList.add('active');
    startSlideshow();
</script>

</body>
</html>
