<?php
session_start();

if(!isset($_SESSION["usuario_id"])){
    header("Location: login.php");
    exit;
}

require_once("config/conexion.php");

$id_usuario = $_SESSION["usuario_id"];

$sqlUsuario = "
SELECT *
FROM usuarios
WHERE id = :id
";

$stmtUsuario = $conexion->prepare($sqlUsuario);
$stmtUsuario->bindParam(":id",$id_usuario);
$stmtUsuario->execute();

$usuario = $stmtUsuario->fetch(PDO::FETCH_ASSOC);

/* =========================================
API FOOTBALL DATA
========================================= */

$apiKey = "d65844c049bc4302af0178efd9684364";

$url = "https://api.football-data.org/v4/competitions/WC/matches";

$curl = curl_init();

curl_setopt_array($curl,[
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "X-Auth-Token: ".$apiKey
    ]
]);

$response = curl_exec($curl);

curl_close($curl);

$data = json_decode($response,true);



/* =========================================
TRADUCCIONES
========================================= */

$traducciones = [

"Mexico" => "México",
"Japan" => "Japón",
"South Africa" => "Sudáfrica",
"South Korea" => "Corea del Sur",
"Czechia" => "República Checa",
"Canada" => "Canadá",
"Bosnia and Herzegovina" => "Bosnia y Herzegovina",
"Qatar" => "Catar",
"Switzerland" => "Suiza",
"Brazil" => "Brasil",
"Morocco" => "Marruecos",
"Haiti" => "Haití",
"Scotland" => "Escocia",
"United States" => "Estados Unidos",
"Paraguay" => "Paraguay",
"Australia" => "Australia",
"Turkey" => "Turquía",
"Germany" => "Alemania",
"Curacao" => "Curazao",
"Cote d'Ivoire" => "Costa de Marfil",
"Ecuador" => "Ecuador",
"Netherlands" => "Países Bajos",
"Sweden" => "Suecia",
"Tunisia" => "Túnez",
"Belgium" => "Bélgica",
"Egypt" => "Egipto",
"Iran" => "Irán",
"New Zealand" => "Nueva Zelanda",
"Spain" => "España",
"Cape Verde" => "Cabo Verde",
"Saudi Arabia" => "Arabia Saudita",
"Uruguay" => "Uruguay",
"France" => "Francia",
"Senegal" => "Senegal",
"Iraq" => "Irak",
"Norway" => "Noruega",
"Argentina" => "Argentina",
"Algeria" => "Argelia",
"Austria" => "Austria",
"Jordan" => "Jordania",
"Portugal" => "Portugal",
"DR Congo" => "RD Congo",
"Uzbekistan" => "Uzbekistán",
"Colombia" => "Colombia",
"England" => "Inglaterra",
"Croatia" => "Croacia",
"Ghana" => "Ghana",
"Panama" => "Panamá"

];

function traducirPais($pais,$traducciones){

    return $traducciones[$pais] ?? $pais;
}

/* =========================================
BANDERAS
========================================= */

function bandera($pais){

$banderas = [

"México"=>"🇲🇽",
"Japón"=>"🇯🇵",
"Sudáfrica"=>"🇿🇦",
"Corea del Sur"=>"🇰🇷",
"República Checa"=>"🇨🇿",
"Canadá"=>"🇨🇦",
"Bosnia y Herzegovina"=>"🇧🇦",
"Catar"=>"🇶🇦",
"Suiza"=>"🇨🇭",
"Brasil"=>"🇧🇷",
"Marruecos"=>"🇲🇦",
"Haití"=>"🇭🇹",
"Escocia"=>"🏴",
"Estados Unidos"=>"🇺🇸",
"Paraguay"=>"🇵🇾",
"Australia"=>"🇦🇺",
"Turquía"=>"🇹🇷",
"Alemania"=>"🇩🇪",
"Curazao"=>"🇨🇼",
"Costa de Marfil"=>"🇨🇮",
"Ecuador"=>"🇪🇨",
"Países Bajos"=>"🇳🇱",
"Suecia"=>"🇸🇪",
"Túnez"=>"🇹🇳",
"Bélgica"=>"🇧🇪",
"Egipto"=>"🇪🇬",
"Irán"=>"🇮🇷",
"Nueva Zelanda"=>"🇳🇿",
"España"=>"🇪🇸",
"Cabo Verde"=>"🇨🇻",
"Arabia Saudita"=>"🇸🇦",
"Uruguay"=>"🇺🇾",
"Francia"=>"🇫🇷",
"Senegal"=>"🇸🇳",
"Irak"=>"🇮🇶",
"Noruega"=>"🇳🇴",
"Argentina"=>"🇦🇷",
"Argelia"=>"🇩🇿",
"Austria"=>"🇦🇹",
"Jordania"=>"🇯🇴",
"Portugal"=>"🇵🇹",
"RD Congo"=>"🇨🇩",
"Uzbekistán"=>"🇺🇿",
"Colombia"=>"🇨🇴",
"Inglaterra"=>"🏴",
"Croacia"=>"🇭🇷",
"Ghana"=>"🇬🇭",
"Panamá"=>"🇵🇦"

];

return $banderas[$pais] ?? "⚽";
}
?>
<!DOCTYPE html>
<html lang="es">
<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Mundial 2026 | COQUINIELA</title>

<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
rel="stylesheet">

<link
href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css"
rel="stylesheet">

<style>

body{

    margin:0;

    background:
    linear-gradient(
    rgba(0,27,77,.60),
    rgba(0,27,77,.80)
    ),
    url('assets/img/fondo_estadio.jpg');

    background-size:cover;
    background-attachment:fixed;

    color:white;

    font-family:Arial;

    padding-bottom:100px;
}

.container-main{

    max-width:1000px;

    margin:auto;

    padding:20px;
}

.logo{

    width:220px;

    display:block;

    margin:20px auto;
}

.page-title{

    text-align:center;

    font-size:32px;

    font-weight:bold;

    margin-bottom:30px;
}

.filtro-box{

    background:rgba(255,255,255,.08);

    border-radius:20px;

    padding:15px;

    margin-bottom:25px;

    backdrop-filter:blur(10px);
}

.partido-card{

    background:rgba(255,255,255,.08);

    border-radius:20px;

    padding:20px;

    margin-bottom:15px;

    backdrop-filter:blur(10px);

    box-shadow:0 0 20px rgba(0,0,0,.25);

    transition:.2s;
}

.partido-card:hover{

    transform:translateY(-2px);
}

.grupo{

    color:#F4C400;

    font-weight:bold;

    margin-bottom:10px;
}

.estado{

    float:right;

    font-size:12px;

    padding:5px 10px;

    border-radius:20px;
}

.estado-programado{

    background:#0dcaf0;

    color:#001B4D;
}

.estado-vivo{

    background:#198754;
}

.estado-final{

    background:#dc3545;
}

.equipos{

    text-align:center;

    font-size:22px;

    font-weight:bold;

    margin-top:10px;
}

.vs{

    text-align:center;

    margin:10px 0;

    color:#F4C400;

    font-weight:bold;
}

.fecha{

    text-align:center;

    color:#ddd;

    margin-top:15px;
}

.resultado{

    text-align:center;

    margin-top:15px;

    font-size:28px;

    font-weight:bold;

    color:#F4C400;
}

.bottom-menu{

    position:fixed;

    bottom:0;

    left:0;

    width:100%;

    height:75px;

    background:#001B4D;

    display:flex;

    justify-content:space-around;

    align-items:center;

    box-shadow:0 -5px 20px rgba(0,0,0,.4);
}

.bottom-menu a{

    color:white;

    text-decoration:none;

    text-align:center;

    font-size:13px;
}

.bottom-menu i{

    display:block;

    font-size:24px;
}

@media(max-width:768px){

    .equipos{

        font-size:18px;
    }

    .resultado{

        font-size:24px;
    }

}

</style>

</head>

<body>

<div class="container-main">

    <img
        src="assets/img/logo.png"
        class="logo"
    >

    <div class="page-title">

        🏆 Mundial 2026

    </div>
<div style="

text-align:center;

margin-bottom:20px;

color:#F4C400;

font-size:18px;

font-weight:bold;

">

⚽ <?php echo count($data["matches"]); ?> partidos disponibles

</div>
    <div class="filtro-box">

        <form method="GET">

            <select
                name="fase"
                class="form-select"
                onchange="this.form.submit()"
            >

                <option value="">
                    Todas las fases
                </option>

                <option value="GROUP_STAGE">
                    Fase de Grupos
                </option>

                <option value="LAST_32">
                    Dieciseisavos
                </option>

                <option value="LAST_16">
                    Octavos
                </option>

                <option value="QUARTER_FINALS">
                    Cuartos
                </option>

                <option value="SEMI_FINALS">
                    Semifinales
                </option>

                <option value="FINAL">
                    Final
                </option>

            </select>

        </form>

    </div>
    <?php

$faseSeleccionada = $_GET["fase"] ?? "";

date_default_timezone_set('America/Mexico_City');

$fases = [

    "GROUP_STAGE"     => "Fase de Grupos",
    "LAST_32"         => "Dieciseisavos",
    "LAST_16"         => "Octavos de Final",
    "QUARTER_FINALS"  => "Cuartos de Final",
    "SEMI_FINALS"     => "Semifinales",
    "THIRD_PLACE"     => "Tercer Lugar",
    "FINAL"           => "Final"

];






if(!isset($data["matches"])){

    echo '

    <div class="alert alert-danger">

        Error al obtener partidos desde la API.

    </div>';

}else{
foreach($data["matches"] as $match){

    if(
        $faseSeleccionada != ""
        &&
        $match["stage"] != $faseSeleccionada
    ){
        continue;
    }

    $local = traducirPais(
        $match["homeTeam"]["name"] ?? "",
        $traducciones
    );

    $visitante = traducirPais(
        $match["awayTeam"]["name"] ?? "",
        $traducciones
    );

    $fecha = strtotime($match["utcDate"]);

    $fechaMexico = date(

    "d/m/Y H:i",

    strtotime($match["utcDate"])

);

    $estado = $match["status"];

    $claseEstado = "estado-programado";

    $textoEstado = "PROGRAMADO";

    if(
        $estado == "IN_PLAY"
        ||
        $estado == "PAUSED"
    ){

        $claseEstado = "estado-vivo";

        $textoEstado = "EN VIVO";
    }

    if(
    $estado == "FINISHED"
){

    $claseEstado = "estado-final";

    $textoEstado = "FINALIZADO";
}

?>

<div class="partido-card">

    <div>

        <span class="grupo">

<?php

echo !empty($match["group"])
    ? str_replace("GROUP_","Grupo ",$match["group"])
    : ($fases[$match["stage"]] ?? $match["stage"]);

?>

</span>

        <span
            class="
            estado
            <?php echo $claseEstado; ?>
            "
        >

            <?php echo $textoEstado; ?>

        </span>

    </div>

    <div class="equipos">

        <?php echo bandera($local); ?>

        <?php echo $local; ?>

    </div>

    <div class="vs">
        VS
    </div>

    <div class="equipos">

        <?php echo bandera($visitante); ?>

        <?php echo $visitante; ?>

    </div>

    <div class="fecha">

        📅 <?php echo $fechaMexico; ?>

    </div>

    <?php

    if(
        isset($match["score"]["fullTime"]["home"])
    ){

?>

        <div class="resultado">

            <?php echo $match["score"]["fullTime"]["home"]; ?>

            -

            <?php echo $match["score"]["fullTime"]["away"]; ?>

        </div>

<?php } ?>

</div>

<?php } // FIN FOREACH ?>

<?php } // FIN ELSE ?>

<div class="bottom-menu">

    <a href="dashboard.php">
        <i class="bi bi-house-fill"></i>
        Inicio
    </a>

    <a href="partidos.php">
        <i class="bi bi-calendar-event-fill"></i>
        Partidos
    </a>

    <a href="mundial.php">
        <i class="bi bi-globe-americas"></i>
        Mundial
    </a>

    <a href="ranking.php">
        <i class="bi bi-trophy-fill"></i>
        Ranking
    </a>

    <?php if($usuario["rol"]=="admin"){ ?>

    <a href="admin/index.php">
        <i class="bi bi-shield-lock-fill"></i>
        Admin
    </a>

    <?php } ?>

</div>