<?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(); 

$api_key = getApiKey();

foreach ($res as $index => $row) {
    $urlsfb[] = 'https://www.thesportsdb.com/api/v1/json/'.$api_key.'/eventsnextleague.php?id='.$row['leagueId']; 
}

$urls = $urlsfb;


$currentCla = $mes[0]['cla'] ?? '+';  
$currentTime = $mes[0]['time']?? '0';

$finaltime = "$currentCla $currentTime"; 


$filteredEvents = [];

function fetchJsonData($url) {
    $json = file_get_contents($url);
    return json_decode($json, true);
}

foreach ($urls as $url) {
    $data = fetchJsonData($url);
    if (isset($data['events'])) {
        foreach ($data['events'] as $event) {

            $filteredEvent = [
                'idEvent' => $event['idEvent'],
                'strSport' => $event['strSport'],
                'strEvent' => $event['strEvent'],
                'strLeague' => $event['strLeague'],
                'dateEvent' => date('d-m-Y', strtotime($event['dateEvent'])), // Changed to dd-mm-yyyy format
                'strTimestamp' => $event['strTime'],
                'strThumb' => $event['strThumb'],
                'strStatus' => $event['strStatus']
            ];
            $filteredEvents[] = $filteredEvent;
        }
    }
}

// Sort events by dateEvent in ascending order
usort($filteredEvents, function($a, $b) {
    $dateA = DateTime::createFromFormat('d-m-Y', $a['dateEvent']);
    $dateB = DateTime::createFromFormat('d-m-Y', $b['dateEvent']);
    return $dateA <=> $dateB;
});

// Group events by dateEvent
$groupedEvents = [];
foreach ($filteredEvents as $event) {
    $groupedEvents[$event['dateEvent']][] = $event;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Events</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
        <style>
        .event-item {
            position: relative;
            margin: 2.3px;
            border-radius: 13px;
        }
        .event-item img {
            width: 209px;
            height: 130px;
            border-radius: 13px;
            z-index: 4;
            position: relative;
        }
        .event-item .overlay {
           position: absolute;
           top: 0;
           left: 0;
           width: 100%;
           height: 100%;
           background-color: rgba(0, 0, 0, 0.6);
           border-radius: 13px;
           z-index: 4;
           border: 3px solid gray; /* Silver border */
        }
        .event-item:focus, .event-item:focus .overlay {
            outline: none;
            box-shadow: 0 0 5px 3px red;
            border-radius: 13px;
        }
        .event-info {
           position: absolute;
           top: 5px;
           left: 50%;
           transform: translateX(-50%);
           width: 100%;
           text-align: center;
           font-weight: bold;
           color: white;
           font-size: 13px;
           z-index: 4;
           text-shadow: 4px 4px 4px rgba(1, 1, 1, 1);
        }
        .league {
            margin: -2px 0;
        }
        .event {
            margin: -2px 0;
        }
        .timestamp {
            margin: 18px 0;
            font-size: 15px;
        }
        body {
            background: transparent;
            color: white;
        }
        #modalbody {
            color: black;
            font-size: 14px;
            font-weight: bold;
        }
        .channel-item {
            display: flex;
            align-items: center;
            margin-bottom: 5px;
        }
        .channel-logo {
            width: 75px;
            height: 40px;
            margin-right: 10px;
            background-color: #2e2e2e;
            background-image: url('background-image.png');
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            border-radius: 2px;
        }
    </style>
</head>
<body>
    <?php foreach ($groupedEvents as $dateEvent => $events): ?>
        <h4 class="font-weight-light"><?php echo htmlspecialchars($dateEvent); ?></h4>

        <div style="width:100%;overflow:scroll;">
            <div class="container-fluid py-2">
                <div class="d-flex flex-row flex-nowrap">
                    <?php foreach ($events as $index => $event): ?>
                        <?php if ($index > 0 && $index % 5 == 0): ?>
                            </div></div><div style="width:100%;overflow:scroll;"><div class="container-fluid py-2"><div class="d-flex flex-row flex-nowrap">
                        <?php endif; ?>
                        <a href='#' onclick="return handleclick(<?php echo $event['idEvent']; ?>)">
                            <div class="event-item" data-index="<?php echo $index; ?>" data-id="<?php echo $event['idEvent']; ?>">
                                <div class="event-banner" style="background-color: rgba(255, 255, 255, 0.2);"></div>
                                <img src="<?php echo htmlspecialchars($event['strThumb']); ?>" alt="<?php echo htmlspecialchars($event['strEvent']); ?>">
                                <div class="overlay"></div>
                                <div class="event-info">
                                    <div class="league"><?php echo htmlspecialchars($event['strLeague']); ?></div>
                                    <div class="event"><?php echo  htmlspecialchars($event['strEvent']); ?></div>
                                    <div class="timestamp">
                                        <?php
                                            echo date("g:i A", strtotime($event['strTimestamp'] . ' ' . $finaltime.' minutes'));
                                        ?>
                                    </div>
                                </div>
                            </div>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    <?php endforeach; ?>

    <div id="channelmodal" class="modal" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content" style="background-color: gray;">
                <div class="modal-header">
                    <h5 class="modal-title" style="color:black; font-size:25px; font-weight:bold;">𝐂𝐡𝐚𝐧𝐧𝐞𝐥𝐬 𝐬𝐡𝐨𝐰𝐢𝐧𝐠 𝐭𝐡𝐢𝐬 𝐞𝐯𝐞𝐧𝐭</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="modalbody"></div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function handleclick(id) {
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    const response = JSON.parse(this.responseText);
                    const modalBody = document.getElementById("modalbody");
                    
                    if (response.tvevent && response.tvevent.length > 0) {
                        const channels = response.tvevent.map(item => `
                            <div class="channel-item">
                                <img src="${item.strLogo || 'default-logo.png'}" alt="Logo" class="channel-logo">
                                <span>${item.strChannel}</span>
                            </div>
                        `).join('');
                        modalBody.innerHTML = channels;
                    } else {
                        modalBody.innerHTML = 'No channels available';
                    }
                    
                    var myModal = new bootstrap.Modal(document.getElementById('channelmodal'));
                    myModal.show();
                }
            };
            xhttp.open("GET", "lookuptv.php?id=" + id, true);
            xhttp.send();
            return false;
        }

        // Close modal with Android TV remote back button
        document.addEventListener('keydown', function(event) {
            const modal = document.getElementById('channelmodal');
            if (event.key === 'Escape' && modal.classList.contains('show')) {
                const myModal = bootstrap.Modal.getInstance(modal);
                myModal.hide();
            }
        });
    </script>
</body>
</html>