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

/* =========================================
OBTENER RANKING
========================================= */

$sqlRanking = "
SELECT

    u.*,

    (
        SELECT COUNT(*)
        FROM pronosticos p
        WHERE p.id_usuario = u.id
        AND p.puntos = 3
    ) exactos,

    (
        SELECT COUNT(*)
        FROM pronosticos p
        WHERE p.id_usuario = u.id
        AND p.puntos >= 1
    ) aciertos

FROM usuarios u

ORDER BY u.puntos DESC, u.nombre ASC
";

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

$stmtRanking->execute();

$ranking = $stmtRanking->fetchAll(PDO::FETCH_ASSOC);

?>

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

<meta charset="UTF-8">

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

<title>Ranking | 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,.70),
    rgba(0,27,77,.82)
    ),
    url('assets/img/fondo_estadio.jpg');

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

    font-family:Arial;

    color:white;

    padding-bottom:100px;
}

.container-main{

    padding:20px;

    max-width:800px;

    margin:auto;
}

.logo{

    width:220px;

    display:block;

    margin:20px auto;
}

.title{

    font-size:32px;

    font-weight:bold;

    text-align:center;

    margin-bottom:30px;
}

/* =========================================
TOP 3
========================================= */

.top3{

    display:flex;

    gap:15px;

    align-items:flex-end;

    justify-content:center;

    margin-bottom:35px;
}

.top-card{

    flex:1;

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

    border-radius:25px;

    padding:20px;

    text-align:center;

    backdrop-filter:blur(10px);

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

    position:relative;
}

.top-card.first{

    border:3px solid #F4C400;

    transform:scale(1.06);
}

.top-photo{

    width:75px;

    height:75px;

    border-radius:50%;

    object-fit:cover;

    border:3px solid #F4C400;

    margin-bottom:12px;
}

.top-position{

    font-size:28px;

    margin-bottom:10px;
}

.top-name{

    font-size:18px;

    font-weight:bold;
}

.top-points{

    font-size:24px;

    font-weight:bold;

    color:#F4C400;

    margin-top:10px;
}

/* =========================================
LISTA
========================================= */

.ranking-card{

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

    border-radius:20px;

    padding:15px;

    margin-bottom:12px;

    

    backdrop-filter:blur(10px);

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

.ranking-header{

    display:flex;

    justify-content:space-between;

    align-items:center;
}

.ranking-card.me{

    border:2px solid #F4C400;
}

.left{

    display:flex;

    align-items:center;

    gap:15px;
}

.position{

    width:45px;

    height:45px;

    border-radius:50%;

    background:#F4C400;

    color:#001B4D;

    display:flex;

    justify-content:center;

    align-items:center;

    font-weight:bold;

    font-size:18px;
}

.user-photo{

    width:55px;

    height:55px;

    border-radius:50%;

    object-fit:cover;

    border:2px solid rgba(255,255,255,.3);
}

.name{

    font-size:18px;

    font-weight:bold;
}

.you{

    color:#F4C400;

    font-size:13px;
}

.points{

    font-size:24px;

    font-weight:bold;

    color:#F4C400;

    min-width:70px;

    text-align:right;
}
.desglose-btn{

    border-radius:12px;

    padding:10px 15px;

    font-weight:bold;

    width:100%;
}

.desglose-btn:hover{

    background:#F4C400;

    color:#001B4D;
}

.detalle-card{

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

    border-radius:15px;

    padding:12px;

    margin-bottom:10px;

    border-left:4px solid #F4C400;
}

/* =========================================
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;
}

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

@media(max-width:768px){

    .top3{

        flex-direction:column;

        align-items:stretch;
    }

    .top-card.first{

        transform:none;
    }

    .top-name{

        font-size:16px;
    }

    .points{

        font-size:20px;
    }

}

</style>

</head>
<body>

<div class="container-main">

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

    <div class="title">
        🏆 Ranking General
    </div>

    <!-- TOP 3 -->

<div class="top3">

    <?php for($i=1;$i<=3;$i++){ ?>

        <?php if(isset($ranking[$i-1])){ ?>

            <?php

            $jugador = $ranking[$i-1];

            $clase = "";

            if($i == 1){

                $clase = "first";
            }

            $foto = "assets/img/usuarios/default.png";

            if($jugador["foto"] != ""){

                $foto = "assets/img/usuarios/".$jugador["foto"];
            }

            ?>

            <div class="top-card <?php echo $clase; ?>">

                <div class="top-position">

                    <?php

                    if($i == 1){

                        echo "🥇";

                    } elseif($i == 2){

                        echo "🥈";

                    } else {

                        echo "🥉";
                    }

                    ?>

                </div>

                <img
                    src="<?php echo $foto; ?>"
                    class="top-photo"
                >

                <div class="top-name">

                    <?php echo $jugador["nombre"]; ?>

                </div>

                <div class="top-points">

                    <?php echo $jugador["puntos"]; ?>

                    pts

                </div>

            </div>

        <?php } ?>

    <?php } ?>

</div>

    <!-- LISTA -->

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

    <?php

    $clase = "";

    if($jugador["id"] == $id_usuario){

        $clase = "me";
    }

    $foto = "assets/img/usuarios/default.png";

    if($jugador["foto"] != ""){

        $foto = "assets/img/usuarios/".$jugador["foto"];
    }

    ?>

    <div class="ranking-card <?php echo $clase; ?>">

        <div class="ranking-header">

            <div class="left">

                <div class="position">
                    <?php echo $index + 1; ?>
                </div>

                <img
                    src="<?php echo $foto; ?>"
                    class="user-photo"
                >

                <div>

                    <div class="name">

                        <?php echo $jugador["nombre"]; ?>

                    </div>

                    <?php if($jugador["id"] == $id_usuario){ ?>

                        <div class="you">
                            Tú
                        </div>

                    <?php } ?>

                </div>

            </div>

            <div class="points">

                <?php echo $jugador["puntos"]; ?>

            </div>

        </div>

        <?php

        $sqlDetalle = "

        SELECT

            p.equipo_local,
            p.equipo_visitante,

            p.goles_local,
            p.goles_visitante,

            pr.goles_local pron_local,
            pr.goles_visitante pron_visitante,

            pr.puntos

        FROM pronosticos pr

        INNER JOIN partidos p
        ON p.id = pr.id_partido

        WHERE pr.id_usuario = :id_usuario
        AND p.estatus = 'finalizado'

        ORDER BY p.fecha DESC

        LIMIT 10
        ";

        $stmtDetalle = $conexion->prepare($sqlDetalle);

        $stmtDetalle->bindParam(
            ":id_usuario",
            $jugador["id"]
        );

        $stmtDetalle->execute();

        $detalles = $stmtDetalle->fetchAll(PDO::FETCH_ASSOC);

        ?>

        <div style="margin-top:15px;">

            <button

    class="btn btn-sm btn-outline-light desglose-btn"

    type="button"

    data-bs-toggle="collapse"

    data-bs-target="#detalle<?php echo $jugador["id"]; ?>"

    onclick="
    this.innerText =
    this.innerText == 'Ver desglose'
    ? 'Ocultar desglose'
    : 'Ver desglose';
    "
>

                Ver desglose

            </button>

            <div

                class="collapse mt-3"

                id="detalle<?php echo $jugador["id"]; ?>"

            >

                <?php foreach($detalles as $d){ ?>

                    <div class="detalle-card">

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

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

                            vs

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

                        </div>

                        <div style="margin-top:8px;">

                            Resultado:

                            <b>

                                <?php echo $d["goles_local"]; ?>

                                -

                                <?php echo $d["goles_visitante"]; ?>

                            </b>

                        </div>

                        <div>

                            Pronóstico:

                            <b>

                                <?php echo $d["pron_local"]; ?>

                                -

                                <?php echo $d["pron_visitante"]; ?>

                            </b>

                        </div>

                        <?php

$colorPuntos = "#dc3545";

if($d["puntos"] == 1){

    $colorPuntos = "#ffc107";
}

if($d["puntos"] == 3){

    $colorPuntos = "#198754";
}

?>

<div
    style="
    color:<?php echo $colorPuntos; ?>;
    font-weight:bold;
    margin-top:5px;
    "
>

                            🏆

                            <?php echo $d["puntos"]; ?>

                            pts
<?php if($d["puntos"] == 3){ ?>

    <div style="color:#198754;font-size:13px;">
        🎯 Marcador exacto
    </div>

<?php } elseif($d["puntos"] >= 1){ ?>

    <div style="color:#ffc107;font-size:13px;">
        ✅ Acierto
    </div>

<?php } else { ?>

    <div style="color:#dc3545;font-size:13px;">
        ❌ Fallado
    </div>

<?php } ?>
                        </div>

                    </div>

                <?php } ?>

            </div>

        </div>

    </div>

<?php } ?>
</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>

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

</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>