<?php
session_start();

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

require_once("config/conexion.php");

$id_usuario = $_SESSION["usuario_id"];

/* =========================================
RECALCULAR PUNTOS
========================================= */

$sqlRecalcular = "
UPDATE usuarios u
SET puntos = (
    SELECT COALESCE(SUM(p.puntos),0)
    FROM pronosticos p
    WHERE p.id_usuario = u.id
)
";

$stmtRecalcular = $conexion->prepare($sqlRecalcular);

$stmtRecalcular->execute();


/* =========================================
USUARIO
========================================= */

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

$stmtUsuario = $conexion->prepare($sqlUsuario);

$stmtUsuario->bindParam(":id", $id_usuario);

$stmtUsuario->execute();

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

/* =========================================
POSICIÓN EN RANKING
========================================= */

$sqlRanking = "
SELECT posicion FROM (

    SELECT
        id,
        ROW_NUMBER() OVER (
            ORDER BY puntos DESC
        ) posicion

    FROM usuarios

) t

WHERE id = :id
";

$stmtRanking = $conexion->prepare($sqlRanking);

$stmtRanking->bindParam(":id", $id_usuario);

$stmtRanking->execute();

$rankingUsuario = $stmtRanking->fetch(PDO::FETCH_ASSOC);

$posicion = $rankingUsuario["posicion"] ?? 0;

/* =========================================
ACIERTOS EXACTOS
========================================= */

$sqlExactos = "
SELECT COUNT(*) total
FROM pronosticos
WHERE id_usuario = :id_usuario
AND puntos = 3
";

$stmtExactos = $conexion->prepare($sqlExactos);

$stmtExactos->bindParam(":id_usuario", $id_usuario);

$stmtExactos->execute();

$exactos = $stmtExactos->fetch(PDO::FETCH_ASSOC);

/* =========================================
ACIERTOS
========================================= */

$sqlAciertos = "
SELECT COUNT(*) total
FROM pronosticos
WHERE id_usuario = :id_usuario
AND puntos >= 1
";

$stmtAciertos = $conexion->prepare($sqlAciertos);

$stmtAciertos->bindParam(":id_usuario", $id_usuario);

$stmtAciertos->execute();

$aciertos = $stmtAciertos->fetch(PDO::FETCH_ASSOC);

/* =========================================
TOTAL PRONÓSTICOS
========================================= */

$sqlPronosticosTotal = "
SELECT COUNT(*) total
FROM pronosticos
WHERE id_usuario = :id_usuario
";

$stmtPronosticosTotal = $conexion->prepare($sqlPronosticosTotal);

$stmtPronosticosTotal->bindParam(":id_usuario", $id_usuario);

$stmtPronosticosTotal->execute();

$totalPronosticos = $stmtPronosticosTotal->fetch(PDO::FETCH_ASSOC);

/* =========================================
EFECTIVIDAD
========================================= */

$efectividad = 0;

if($totalPronosticos["total"] > 0){

    $efectividad = round(
        (
            $aciertos["total"] /
            $totalPronosticos["total"]
        ) * 100
    );
}

/* =========================================
PARTIDOS PENDIENTES
========================================= */

$sqlPendientes = "
SELECT COUNT(*) total

FROM partidos p

WHERE p.estatus = 'pendiente'

AND NOT EXISTS(

    SELECT 1

    FROM pronosticos pr

    WHERE pr.id_partido = p.id
    AND pr.id_usuario = :id_usuario

)
";

$stmtPendientes = $conexion->prepare($sqlPendientes);

$stmtPendientes->bindParam(":id_usuario", $id_usuario);

$stmtPendientes->execute();

$pendientes = $stmtPendientes->fetch(PDO::FETCH_ASSOC);

/* =========================================
PARTIDOS HOY
========================================= */

$sqlHoy = "

SELECT COUNT(*) total

FROM partidos

WHERE DATE(fecha)=CURDATE()

AND estatus='pendiente'

";

$stmtHoy = $conexion->prepare($sqlHoy);
$stmtHoy->execute();

$hoy = $stmtHoy->fetch(PDO::FETCH_ASSOC);

/* =========================================
PARTIDOS MAÑANA
========================================= */

$sqlManana = "

SELECT COUNT(*) total

FROM partidos

WHERE DATE(fecha)=DATE_ADD(CURDATE(),INTERVAL 1 DAY)

AND estatus='pendiente'

";

$stmtManana = $conexion->prepare($sqlManana);
$stmtManana->execute();

$manana = $stmtManana->fetch(PDO::FETCH_ASSOC);


/* =========================================
LÍDER
========================================= */

$sqlLider = "
SELECT puntos
FROM usuarios
ORDER BY puntos DESC
LIMIT 1
";

$stmtLider = $conexion->prepare($sqlLider);

$stmtLider->execute();

$lider = $stmtLider->fetch(PDO::FETCH_ASSOC);

$diferencia = intval($lider["puntos"]) - intval($usuario["puntos"]);

/* =========================================
TOP 5
========================================= */

$sqlTop = "SELECT nombre, puntos
FROM usuarios
ORDER BY puntos DESC
LIMIT 5";

$stmtTop = $conexion->prepare($sqlTop);

$stmtTop->execute();

$topJugadores = $stmtTop->fetchAll(PDO::FETCH_ASSOC);

/* =========================================
PRÓXIMOS PARTIDOS
========================================= */

$sqlPartidos = "
SELECT
    p.*,

    pr.goles_local AS pronostico_local,
    pr.goles_visitante AS pronostico_visitante,
    pr.puntos AS pronostico_puntos

FROM partidos p

LEFT JOIN pronosticos pr
ON pr.id_partido = p.id
AND pr.id_usuario = :id_usuario

WHERE p.fecha >= DATE_SUB(NOW(), INTERVAL 3 DAY)

ORDER BY p.fecha ASC

LIMIT 30
";

$stmtPartidos = $conexion->prepare($sqlPartidos);

$stmtPartidos->bindParam(":id_usuario", $id_usuario);

$stmtPartidos->execute();

$partidos = $stmtPartidos->fetchAll(PDO::FETCH_ASSOC);

?>
<?php

function bandera($pais){

    $banderas = [

        "México" => "🇲🇽",
        "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" => "🇳🇱",
        "Japón" => "🇯🇵",
        "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>Dashboard | COQUINIELA</title>

<link rel="manifest" href="manifest.json">

<meta name="theme-color" content="#001B4D">

<link rel="apple-touch-icon"

href="assets/img/icon-192.png">

<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,.55),

rgba(0,27,77,.72)

),

url('assets/img/fondo_estadio.jpg');

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

    font-family:Arial;
    color:white;

    padding-bottom:90px;
}

/* =========================================
HEADER
========================================= */

.header{

    padding:20px;
}

.logo{

    width:220px;
    display:block;
    margin:auto;
}

/* =========================================
USER CARD
========================================= */

.user-card{

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

    border-radius:25px;

    padding:20px;

    backdrop-filter:blur(10px);

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

    margin-bottom:20px;
}

.user-name{

    font-size:24px;
    font-weight:bold;
}

.user-points{

    color:#F4C400;
    font-size:32px;
    font-weight:bold;
}

/* =========================================
SECTION TITLE
========================================= */

.section-title{

    font-size:26px;
    font-weight:bold;

    margin-bottom:15px;
}

/* =========================================
MATCH CARD
========================================= */

.match-card{

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

    border-radius:20px;

    padding:20px;

    margin-bottom:15px;

    backdrop-filter:blur(10px);
}

.match-teams{

    font-size:22px;
    font-weight:bold;
}

.match-date{

    color:#ddd;
    margin-top:10px;
}

.btn-pronostico{

    background:#F4C400;
    color:#001B4D;

    border:none;

    width:100%;

    height:50px;

    border-radius:15px;

    font-weight:bold;

    margin-top:15px;
}

/* =========================================
TOP PLAYERS
========================================= */

.player-card{

    display:flex;
    justify-content:space-between;
    align-items:center;

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

    padding:15px;

    border-radius:15px;

    margin-bottom:10px;
}

.player-name{

    font-size:18px;
    font-weight:bold;
}

.player-points{

    color:#F4C400;
    font-weight:bold;
}

/* =========================================
BOTTOM MENU
========================================= */

.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;

    font-size:13px;

    text-align:center;
}

.bottom-menu i{

    font-size:24px;
    display:block;
}

.bases-link{

    position:absolute;
    top:25px;
    right:20px;

    color:white;
    text-decoration:none;

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

    padding:8px 14px;

    border-radius:12px;

    font-size:14px;

    backdrop-filter:blur(10px);
}


/* =========================================
RESPONSIVE
========================================= */

@media(min-width:768px){

    .container-custom{
        max-width:700px;
        margin:auto;
    }
}

</style>

</head>
<body>

<div class="container-custom">

    <!-- HEADER -->

    <div
    class="header"
    style="position:relative;"
>

    <a
        href="bases.php"
        class="bases-link"
    >
        Bases
    </a>

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

</div>
<div id="instalarApp" style="display:none; margin-top:15px;">

    <button

        id="btnInstalar"

        class="btn-pronostico"

    >

        📲 Instalar App

    </button>

</div>
    <!-- USER -->

    <div class="container">

        <div class="user-card">

    <div class="user-name">

        👋 Hola,
        <?php echo $usuario["nombre"]; ?>

    </div>

    <div class="mt-4">

        <div class="row text-center">

            <div class="col-6 mb-4">

                <div style="font-size:15px;color:#ccc;">
                    Ranking
                </div>

                <div class="user-points">

                    🥇 #<?php echo $posicion; ?>

                </div>

            </div>

            <div class="col-6 mb-4">

                <div style="font-size:15px;color:#ccc;">
                    Puntos
                </div>

                <div class="user-points">

                    🏆 <?php echo $usuario["puntos"]; ?>

                </div>

            </div>

            <div class="col-6 mb-4">

                <div style="font-size:15px;color:#ccc;">
                    Exactos
                </div>

                <div style="
                    font-size:28px;
                    font-weight:bold;
                    color:#F4C400;
                ">

                    🎯 <?php echo $exactos["total"]; ?>

                </div>

            </div>

            <div class="col-6 mb-4">

                <div style="font-size:15px;color:#ccc;">
                    Aciertos
                </div>

                <div style="
                    font-size:28px;
                    font-weight:bold;
                    color:#F4C400;
                ">

                    ✅ <?php echo $aciertos["total"]; ?>

                </div>

            </div>

            <div class="col-12 mb-4">

                <div style="font-size:15px;color:#ccc;">
                    Efectividad
                </div>

                <div style="
                    font-size:34px;
                    font-weight:bold;
                    color:#00ff88;
                ">

                    📈 <?php echo $efectividad; ?>%

                </div>

            </div>

        </div>

        <!-- MINI KPIS -->

        <div class="row text-center">

            <div class="col-4">

                <div style="
                    background:rgba(255,255,255,.08);
                    border-radius:15px;
                    padding:15px;
                ">

                    <div style="font-size:13px;color:#ccc;">
                        Pendientes
                    </div>

                    <div style="
                        font-size:24px;
                        font-weight:bold;
                    ">

                        <?php echo $pendientes["total"]; ?>

                    </div>

                </div>

            </div>

            <div class="col-4">

                <div style="
                    background:rgba(255,255,255,.08);
                    border-radius:15px;
                    padding:15px;
                ">

                    <div style="font-size:13px;color:#ccc;">
                        Pronósticos
                    </div>

                    <div style="
                        font-size:24px;
                        font-weight:bold;
                    ">

                        <?php echo $totalPronosticos["total"]; ?>

                    </div>

                </div>

            </div>

            <div class="col-4">

                <div style="
                    background:rgba(255,255,255,.08);
                    border-radius:15px;
                    padding:15px;
                ">

                    <div style="font-size:13px;color:#ccc;">
                        Líder
                    </div>

                    <div style="
                        font-size:24px;
                        font-weight:bold;
                    ">

                        -<?php echo $diferencia; ?>

                    </div>

                </div>

            </div>

        </div>

    </div>

</div>
<?php if(floatval($usuario["pagado"]) <= 0){ ?>
<!-- FORMAS DE PAGO -->

<div
    style="
    margin-top:20px;
    background:rgba(255,255,255,.08);
    border-radius:20px;
    padding:20px;
    backdrop-filter:blur(10px);
    border:1px solid rgba(255,255,255,.10);
    "
>

    <div
        style="
        text-align:center;
        font-size:18px;
        font-weight:bold;
        margin-bottom:15px;
        color:#F4C400;
        "
    >
        💳 Formas de Pago
    </div>

    <div
        style="
        text-align:center;
        font-size:18px;
        margin-bottom:10px;
        "
    >
        💵 Efectivo
    </div>

    <hr style="border-color:rgba(255,255,255,.15);">

    <div
        style="
        text-align:center;
        color:#ccc;
        font-size:14px;
        "
    >
        Transferencia NU
    </div>

    <div
        id="cuentaNu"
        style="
        text-align:center;
        font-size:24px;
        font-weight:bold;
        color:#00ff88;
        letter-spacing:2px;
        margin-top:10px;
        "
    >
        638180010118592397
    </div>

    <div
        style="
        text-align:center;
        margin-top:8px;
        color:#ddd;
        "
    >
        Jaqueline Sanchez
    </div>

    <button
        onclick="copiarCuenta()"
        style="
        width:100%;
        margin-top:15px;
        background:#F4C400;
        color:#001B4D;
        border:none;
        border-radius:15px;
        height:50px;
        font-weight:bold;
        "
    >
        📋 Copiar Cuenta
    </button>
<?php } else { ?>

<div
    style="
    margin-top:20px;
    background:rgba(0,255,136,.15);
    border:2px solid #00ff88;
    border-radius:20px;
    padding:20px;
    text-align:center;
    "
>
    <div style="font-size:32px;">
        ✅
    </div>

    <div
        style="
        font-size:20px;
        font-weight:bold;
        color:#00ff88;
        "
    >
        Pago confirmado
    </div>

    <div
        style="
        color:#ddd;
        margin-top:8px;
        "
    >
        Gracias por participar en la Coquiniela
    </div>
</div>

<?php } ?>
</div>

        <!-- PARTIDOS -->

        <div class="section-title">
            📅 Actividad del Mundial
        </div>

        <?php foreach($partidos as $partido){ ?>

            <div class="match-card">

                <div class="match-teams">

                   <?php echo bandera($partido["equipo_local"]); ?>

<?php echo $partido["equipo_local"]; ?>

VS

<?php echo bandera($partido["equipo_visitante"]); ?>

<?php echo $partido["equipo_visitante"]; ?>

                </div>

                <div class="match-date">

                    <?php
                    echo date(
                        "d/m/Y H:i",
                        strtotime($partido["fecha"])
                    );
                    ?>

                </div>

                <?php

/* =========================================
CIERRE 1 HORA ANTES
========================================= */

$hora_limite = strtotime($partido["fecha"]) - 3600;

$cerrado = false;

if(time() >= $hora_limite){

    $cerrado = true;

}

?>

<?php if($partido["pronostico_local"] !== null){ ?>

    <!-- PRONÓSTICO GUARDADO -->

    <div
        style="
        margin-top:15px;
        background:rgba(244,196,0,.15);
        border:2px solid #F4C400;
        border-radius:15px;
        padding:15px;
        text-align:center;
        "
    >

        <div style="font-size:14px;color:#ccc;">
            Tu pronóstico
        </div>

        <div
            style="
            font-size:32px;
            font-weight:bold;
            color:#F4C400;
            "
        >

            <?php echo $partido["pronostico_local"]; ?>

            -

            <?php echo $partido["pronostico_visitante"]; ?>

        </div>

        <?php if($partido["estatus"] == "finalizado"){ ?>

            <div
                style="
                margin-top:10px;
                font-size:18px;
                font-weight:bold;
                "
            >

                🏆

                <?php echo $partido["pronostico_puntos"]; ?>

                pts

            </div>

        <?php } ?>

    </div>

<?php } else { ?>

    <?php if(!$cerrado){ ?>

        <!-- BOTÓN PRONÓSTICO -->

        <a href="pronosticos.php?token=<?php echo $partido["token"]; ?>">

            <button class="btn-pronostico">
                Hacer Pronóstico
            </button>

        </a>

    <?php } else { ?>

        <!-- CERRADO -->

        <div
            style="
            margin-top:15px;
            background:rgba(220,53,69,.2);
            border:2px solid #dc3545;
            border-radius:15px;
            padding:15px;
            text-align:center;
            font-weight:bold;
            "
        >

            Pronóstico cerrado ⛔

        </div>

    <?php } ?>

<?php } ?>

            </div>
<?php } ?>
<div class="match-card">

    <div
        style="
        font-size:24px;
        font-weight:bold;
        margin-bottom:20px;
        "
    >
        ⚽ Próximos partidos
    </div>

    <div class="row text-center">

        <div class="col-4">

            <div
                style="
                background:rgba(255,255,255,.08);
                border-radius:15px;
                padding:15px;
                "
            >

                <div style="color:#ccc;font-size:13px;">
                    ⚽ Hoy
                </div>

                <div
                    style="
                    font-size:28px;
                    font-weight:bold;
                    color:#F4C400;
                    "
                >

                    <?php echo $hoy["total"]; ?>

                </div>

            </div>

        </div>

        <div class="col-4">

            <div
                style="
                background:rgba(255,255,255,.08);
                border-radius:15px;
                padding:15px;
                "
            >

                <div style="color:#ccc;font-size:13px;">
                   🌙 Mañana
                </div>

                <div
                    style="
                    font-size:28px;
                    font-weight:bold;
                    color:#F4C400;
                    "
                >

                    <?php echo $manana["total"]; ?>

                </div>

            </div>

        </div>

        <div class="col-4">

            <div
                style="
                background:rgba(255,255,255,.08);
                border-radius:15px;
                padding:15px;
                "
            >

                <div style="color:#ccc;font-size:13px;">
                    📝 Sin pronóstico
                </div>

                <div
                    style="
                    font-size:28px;
                    font-weight:bold;
                    color:#dc3545;
                    "
                >

                    <?php echo $pendientes["total"]; ?>

                </div>

            </div>

        </div>

    </div>

    <a
        href="partidos.php"
        style="
        text-decoration:none;
        "
    >

        <button
            class="btn-pronostico"
            style="margin-top:20px;"
        >

            ⚽ Ver calendario completo

        </button>

    </a>

</div>



     

        <!-- TOP -->

        <div class="section-title mt-4">
            
             
            
            🏆 Top Jugadores
        </div>

        <?php foreach($topJugadores as $index => $jugador){ ?>

            <div class="player-card">

                <div>

                    <span style="font-size:22px;">
                        #<?php echo $index + 1; ?>
                    </span>

                    <span class="player-name ms-2">
                        <?php echo $jugador["nombre"]; ?>
                    </span>

                </div>

                <div class="player-points">
                    <?php echo $jugador["puntos"]; ?> pts
                </div>

            </div>

        <?php } ?>

    </div>

</div>

<!-- MENU -->

<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="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 } else { ?>

        <a href="perfil.php">
            <i class="bi bi-person-fill"></i>
            Perfil
        </a>

    <?php } ?>

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

</div>
<script>

function copiarCuenta(){

    navigator.clipboard.writeText(
        '638180010118592397'
    );

    alert(
        'Cuenta NU copiada al portapapeles'
    );

}

</script>


<script>

if('serviceWorker' in navigator){

    navigator.serviceWorker.register(
        'service-worker.js'
    );

}

</script>
<script>

let deferredPrompt;

window.addEventListener(
    'beforeinstallprompt',
    (e) => {

        e.preventDefault();

        deferredPrompt = e;

        document.getElementById(
            'instalarApp'
        ).style.display = 'block';

    }
);

document
.getElementById('btnInstalar')
.addEventListener('click', async () => {

    if(!deferredPrompt){
        return;
    }

    deferredPrompt.prompt();

    const result =
        await deferredPrompt.userChoice;

    deferredPrompt = null;

    document.getElementById(
        'instalarApp'
    ).style.display = 'none';

});

</script>
</body>
</html>