<?php
session_start();

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

if($_SESSION["rol"] != "admin"){
    exit("Acceso denegado");
}

require_once("../config/conexion.php");

/* =========================================
CONFIG API
========================================= */

$apiKey = "d65844c049bc4302af0178efd9684364";

$insertados = 0;
$duplicados = 0;
$error = "";

function traducirPais($pais){

    $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",
        "Curaçao" => "Curazao",
        "Cote d'Ivoire" => "Costa de Marfil",
        "Ivory Coast" => "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",
        "Cape Verde Islands" => "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",
        "Congo DR" => "RD Congo",
        "Uzbekistan" => "Uzbekistán",
        "Colombia" => "Colombia",
        "England" => "Inglaterra",
        "Croatia" => "Croacia",
        "Ghana" => "Ghana",
        "Panama" => "Panamá",
        "Bosnia-Herzegovina" => "Bosnia y Herzegovina"

    ];

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







/* =========================================
IMPORTAR
========================================= */

if(isset($_POST["importar"])){

    $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);

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

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

            $api_match_id = $match["id"];

            $sqlExiste = "
            SELECT id
            FROM partidos
            WHERE api_match_id = :api_match_id
            ";

            $stmtExiste = $conexion->prepare($sqlExiste);

            $stmtExiste->bindParam(
                ":api_match_id",
                $api_match_id
            );

            $stmtExiste->execute();

            if($stmtExiste->rowCount() > 0){

    $equipo_local = traducirPais(
        $match["homeTeam"]["name"] ?? ""
    );

    $equipo_visitante = traducirPais(
        $match["awayTeam"]["name"] ?? ""
    );

    $fecha = date(
        "Y-m-d H:i:s",
        strtotime($match["utcDate"])
    );

    $estatus = "pendiente";

    if(
        isset($match["status"])
        &&
        $match["status"] == "FINISHED"
    ){
        $estatus = "finalizado";
    }

    $sqlUpdate = "
    UPDATE partidos
    SET
        equipo_local = :equipo_local,
        equipo_visitante = :equipo_visitante,
        fecha = :fecha,
        estatus = :estatus
    WHERE api_match_id = :api_match_id
    ";

    $stmtUpdate = $conexion->prepare($sqlUpdate);

    $stmtUpdate->bindParam(
        ':equipo_local',
        $equipo_local
    );

    $stmtUpdate->bindParam(
        ':equipo_visitante',
        $equipo_visitante
    );

    $stmtUpdate->bindParam(
        ':fecha',
        $fecha
    );

    $stmtUpdate->bindParam(
        ':estatus',
        $estatus
    );

    $stmtUpdate->bindParam(
        ':api_match_id',
        $api_match_id
    );

    $stmtUpdate->execute();

    $duplicados++;

    continue;
}

            $equipo_local = traducirPais(

    $match["homeTeam"]["name"] ?? ""

);

$equipo_visitante = traducirPais(

    $match["awayTeam"]["name"] ?? ""

);
            $fecha = date(
                "Y-m-d H:i:s",
                strtotime($match["utcDate"])
            );

            $token = md5(
                uniqid().$api_match_id
            );

            $sqlInsert = "
            INSERT INTO partidos
            (
                api_match_id,
                equipo_local,
                equipo_visitante,
                fecha,
                estatus,
                token,
                origen
            )
            VALUES
            (
                :api_match_id,
                :equipo_local,
                :equipo_visitante,
                :fecha,
                'pendiente',
                :token,
                'mundial'
            )
            ";

            $stmtInsert =
            $conexion->prepare($sqlInsert);

            $stmtInsert->bindParam(
                ":api_match_id",
                $api_match_id
            );

            $stmtInsert->bindParam(
                ":equipo_local",
                $equipo_local
            );

            $stmtInsert->bindParam(
                ":equipo_visitante",
                $equipo_visitante
            );

            $stmtInsert->bindParam(
                ":fecha",
                $fecha
            );

            $stmtInsert->bindParam(
                ":token",
                $token
            );

            $stmtInsert->execute();

            $insertados++;
        }

    }else{

        $error = "La API no devolvió partidos.";

    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>

<meta charset="UTF-8">

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

<title>Importar Mundial</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{

    background:#001B4D;
    color:white;
    font-family:Arial;
    padding:20px;
    padding-bottom:110px;
}

.card{

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

    border:none;

    border-radius:20px;

    padding:25px;

    color:white;
}

.btn-importar{

    background:#F4C400;

    color:#001B4D;

    border:none;

    font-weight:bold;

    width:100%;
}

.bottom-menu{

    position:fixed;

    bottom:0;

    left:0;

    width:100%;

    height:75px;

    background:#001B4D;

    display:flex;

    justify-content:space-around;

    align-items:center;
}

.bottom-menu a{

    color:white;

    text-decoration:none;

    text-align:center;

    font-size:13px;
}

.bottom-menu i{

    display:block;

    font-size:24px;
}
</style>

</head>

<body>

<div class="container">

    <h2 class="mb-4">
        🌎 Importar Mundial 2026
    </h2>

    <div class="card">

        <p>
            Importa automáticamente
            los partidos desde la API.
        </p>

        <form method="POST">

            <button
                type="submit"
                name="importar"
                class="btn btn-importar">

                ⚽ Importar Partidos

            </button>

        </form>

    </div>

    <?php if($insertados > 0){ ?>

        <div
        class="alert alert-success mt-3">

            Partidos insertados:
            <strong>
            <?php echo $insertados; ?>
            </strong>

        </div>

    <?php } ?>

    <?php if($duplicados > 0){ ?>

        <div
        class="alert alert-warning mt-3">

            Partidos ya existentes:
            <strong>
            <?php echo $duplicados; ?>
            </strong>

        </div>

    <?php } ?>

    <?php if($error != ""){ ?>

        <div
        class="alert alert-danger mt-3">

            <?php echo $error; ?>

        </div>

    <?php } ?>

</div>

<div class="bottom-menu">

    <a href="index.php">
        <i class="bi bi-speedometer2"></i>
        Admin
    </a>

    <a href="resultados.php">
        <i class="bi bi-trophy-fill"></i>
        Resultados
    </a>

    <a href="usuarios.php">
        <i class="bi bi-people-fill"></i>
        Usuarios
    </a>

    <a href="../dashboard.php">
        <i class="bi bi-phone-fill"></i>
        App
    </a>

    <a href="../logout.php">
        <i class="bi bi-box-arrow-right"></i>
        Salir
    </a>

</div>

</body>
</html>