<?php
/*******************************************************
 * Sports Hub - Versión Integrada con Header
 *******************************************************/

// Gestión de sesión (necesario para el header)
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

/** ===== CONFIG ===== */
const TZ_REGION      = 'America/Lima'; 
const TZ_OFFSET      = '-5';
const API_FOOTBALL_KEY = ''; 
const API_FOOTBALL_URL = 'https://v3.football.api-sports.io/fixtures';
const IFRAME_BASE = 'https://sport-tv-guide.live/';

/** ===== Helpers ===== */
function todayLocalYmd(string $tz = TZ_REGION): string {
    try {
        $dt = new DateTime('now', new DateTimeZone($tz));
        return $dt->format('Y-m-d');
    } catch (Throwable $e) {
        return date('Y-m-d');
    }
}

function getSoccerEventsToday(string $leagueFilter = null): array {
    if (empty(API_FOOTBALL_KEY)) return [];
    $date = todayLocalYmd();
    $params = http_build_query(['date' => $date, 'timezone' => TZ_REGION]);
    $url = API_FOOTBALL_URL . '?' . $params;

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 20,
        CURLOPT_HTTPHEADER     => [
            'x-rapidapi-key: ' . API_FOOTBALL_KEY,
            'x-rapidapi-host: v3.football.api-sports.io',
        ],
        CURLOPT_SSL_VERIFYPEER => false
    ]);
    $res = curl_exec($ch);
    curl_close($ch);

    $json = json_decode($res, true);
    if (!isset($json['response'])) return [];

    $items = [];
    foreach ($json['response'] as $fx) {
        $go = [
            'title'   => ($fx['teams']['home']['name']) . ' vs ' . ($fx['teams']['away']['name']),
            'date'    => $fx['fixture']['date'],
            'league'  => $fx['league']['name'],
            'image'   => $fx['league']['logo'],
            'status'  => $fx['fixture']['status']['short'],
        ];
        if ($leagueFilter && strcasecmp($leagueFilter, 'Todas las Ligas') !== 0) {
            if (strcasecmp($go['league'], $leagueFilter) !== 0) continue;
        }
        $items[] = $go;
    }
    return $items;
}

$selectedSport  = $_GET['sport']  ?? 'Soccer';
$selectedLeague = $_GET['league'] ?? 'Todas las Ligas';
$todayYmd = todayLocalYmd();
$events = (strcasecmp($selectedSport, 'Soccer') === 0) ? getSoccerEventsToday($selectedLeague) : [];
$iframeUrl = IFRAME_BASE . '?date=' . urlencode($todayYmd) . '&tz=' . urlencode(TZ_OFFSET);
?>

<!doctype html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Sports Hub - JTECH TV</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --n-red: #E50914;
            --n-black: #141414;
            --n-dark: #181818;
            --n-gray: #a3a3a3;
            --n-white: #ffffff;
        }

        body {
            background-color: var(--n-black);
            color: var(--n-white);
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
            margin: 0;
        }

        /* ESPACIO PARA EL HEADER FIJO */
        .main-wrapper {
            padding-top: 100px; /* Ajusta según la altura de tu header */
            padding-bottom: 50px;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 0 4%;
        }

        /* Estilo Títulos */
        .page-header {
            margin-bottom: 30px;
        }

        .page-header h1 {
            color: var(--n-red);
            font-size: 2.5rem;
            margin: 0;
            font-weight: 900;
            text-transform: uppercase;
        }

        /* Filtros */
        .filters-bar {
            background: rgba(24, 24, 24, 0.8);
            padding: 20px;
            border-radius: 8px;
            display: flex;
            gap: 20px;
            align-items: flex-end;
            margin-bottom: 40px;
            backdrop-filter: blur(10px);
        }

        .filter-item { display: flex; flex-direction: column; gap: 8px; }
        .filter-item label { font-size: 12px; font-weight: bold; color: var(--n-gray); text-transform: uppercase; }
        
        select, .btn-submit {
            background: #2f2f2f;
            color: white;
            border: 1px solid #444;
            padding: 10px 15px;
            border-radius: 4px;
            outline: none;
        }

        .btn-submit {
            background: var(--n-red);
            border: none;
            font-weight: bold;
            cursor: pointer;
            padding: 11px 30px;
            transition: 0.3s;
        }

        .btn-submit:hover { background: #b20710; }

        /* Grid de Eventos */
        .section-label {
            font-size: 1.5rem;
            margin-bottom: 20px;
            font-weight: bold;
        }

        .events-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
        }

        .sport-card {
            background: var(--n-dark);
            border-radius: 12px;
            overflow: hidden;
            border: 1px solid #222;
            transition: transform 0.3s;
        }

        .sport-card:hover { transform: scale(1.03); }

        .card-top {
            height: 140px;
            background: #000;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .card-top img { max-height: 100%; object-fit: contain; }

        .card-info { padding: 20px; }
        .league-tag { color: var(--n-red); font-size: 12px; font-weight: bold; margin-bottom: 10px; display: block; }
        .match-name { font-size: 1.1rem; font-weight: bold; line-height: 1.4; min-height: 50px; }
        
        .card-footer {
            display: flex;
            justify-content: space-between;
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid #333;
            align-items: center;
        }

        .match-time { font-weight: bold; color: #fff; background: #333; padding: 5px 10px; border-radius: 4px; }
        .match-status { color: #46d369; font-weight: bold; font-size: 13px; }

        /* Iframe */
        .iframe-wrap {
            border-radius: 15px;
            overflow: hidden;
            border: 1px solid #333;
            background: #000;
        }

        @media (max-width: 768px) {
            .filters-bar { flex-direction: column; align-items: stretch; }
            .main-wrapper { padding-top: 80px; }
        }
    </style>
</head>
<body>

    <!-- INTEGRACIÓN DEL HEADER -->
    <?php include 'header.php'; ?>

    <div class="main-wrapper">
        <div class="container">
            
            <header class="page-header">
                <h1>Sports Hub</h1>
                <p style="color: var(--n-gray)">Los mejores eventos deportivos en vivo</p>
            </header>

            <form class="filters-bar" method="get">
                <div class="filter-item">
                    <label>Deporte</label>
                    <select name="sport">
                        <?php
                        $sports = ['Soccer','Basketball','Baseball','Tennis','Hockey','MMA','Boxing','Football'];
                        foreach ($sports as $s) {
                            $sel = (strcasecmp($selectedSport,$s)===0) ? 'selected' : '';
                            echo "<option $sel value='$s'>$s</option>";
                        }
                        ?>
                    </select>
                </div>
                <div class="filter-item">
                    <label>Liga</label>
                    <select name="league">
                        <?php
                        $leagues = ['Todas las Ligas','Premier League','La Liga','Serie A','Bundesliga','Ligue 1','MLS'];
                        foreach ($leagues as $l) {
                            $sel = (strcasecmp($selectedLeague,$l)===0) ? 'selected' : '';
                            echo "<option $sel value='$l'>$l</option>";
                        }
                        ?>
                    </select>
                </div>
                <button type="submit" class="btn-submit">APLICAR</button>
            </form>

            <?php if (!empty($events)): ?>
                <div class="section-label">Partidos para Hoy</div>
                <div class="events-grid">
                    <?php foreach ($events as $ev): ?>
                        <div class="sport-card">
                            <div class="card-top">
                                <img src="<?= $ev['image'] ?>" onerror="this.src='https://via.placeholder.com/150x80/111/fff?text=Sport'">
                            </div>
                            <div class="card-info">
                                <span class="league-tag"><?= htmlspecialchars($ev['league']) ?></span>
                                <div class="match-name"><?= htmlspecialchars($ev['title']) ?></div>
                                <div class="card-footer">
                                    <span class="match-time">
                                        <i class="far fa-clock"></i> 
                                        <?= (new DateTime($ev['date']))->setTimezone(new DateTimeZone(TZ_REGION))->format('H:i') ?>
                                    </span>
                                    <span class="match-status"><?= $ev['status'] ?></span>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <div class="section-label">Guía de Canales</div>
                <div class="iframe-wrap">
                    <iframe src="<?= htmlspecialchars($iframeUrl) ?>" width="100%" height="800" frameborder="0"></iframe>
                </div>
            <?php endif; ?>

        </div>
    </div>

</body>
</html>