<?php
session_start();

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

require_once("config/conexion.php");

$id_usuario = $_SESSION["usuario_id"];

if(!isset($_GET["token"])){
    header("Location: dashboard.php");
    exit;
}

$token = $_GET["token"];

/* =========================================
OBTENER PARTIDO
========================================= */

$sqlPartido = "SELECT *
FROM partidos
WHERE token = :token
LIMIT 1";

$stmtPartido = $conexion->prepare($sqlPartido);

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

$stmtPartido->execute();

$partido = $stmtPartido->fetch(PDO::FETCH_ASSOC);
$id_partido = $partido["id"];

if(!$partido){
    header("Location: dashboard.php");
    exit;
}

/* =========================================
VALIDAR BLOQUEO
1 HORA ANTES
========================================= */

$bloqueado = false;

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

if(time() >= $hora_limite){

    $bloqueado = true;

}

/* =========================================
OBTENER PRONÓSTICO EXISTENTE
========================================= */

$sqlPronostico = "SELECT *
FROM pronosticos
WHERE id_usuario = :id_usuario
AND id_partido = :id_partido
LIMIT 1";

$stmtPronostico = $conexion->prepare($sqlPronostico);

$stmtPronostico->bindParam(":id_usuario", $id_usuario);
$stmtPronostico->bindParam(":id_partido", $id_partido);

$stmtPronostico->execute();

$pronostico = $stmtPronostico->fetch(PDO::FETCH_ASSOC);


/* =========================================
GUARDAR PRONÓSTICO
========================================= */

$mensaje = "";

if($_SERVER["REQUEST_METHOD"] == "POST"){

    /* =========================================
    REVALIDAR BLOQUEO
    ========================================= */

    $sqlValidar = "SELECT id
    FROM pronosticos
    WHERE id_usuario = :id_usuario
    AND id_partido = :id_partido
    LIMIT 1";

    $stmtValidar = $conexion->prepare($sqlValidar);

    $stmtValidar->bindParam(":id_usuario", $id_usuario);
    $stmtValidar->bindParam(":id_partido", $id_partido);

    $stmtValidar->execute();

    $existe = $stmtValidar->fetch(PDO::FETCH_ASSOC);

    /* =========================================
    SI YA EXISTE -> BLOQUEAR
    ========================================= */

    if($existe){

        header("Location: dashboard.php");

        exit;

    }

    /* =========================================
    VALIDAR HORA
    ========================================= */

    if($bloqueado){

        header("Location: dashboard.php");

        exit;

    }

    /* =========================================
    INSERTAR
    ========================================= */

    $goles_local = intval($_POST["goles_local"]);

    $goles_visitante = intval($_POST["goles_visitante"]);

    try{

        $sqlInsert = "INSERT INTO pronosticos (
            id_usuario,
            id_partido,
            goles_local,
            goles_visitante
        ) VALUES (
            :id_usuario,
            :id_partido,
            :goles_local,
            :goles_visitante
        )";

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

        $stmtInsert->bindParam(":id_usuario", $id_usuario);
        $stmtInsert->bindParam(":id_partido", $id_partido);
        $stmtInsert->bindParam(":goles_local", $goles_local);
        $stmtInsert->bindParam(":goles_visitante", $goles_visitante);

        $stmtInsert->execute();

    } catch(PDOException $e){

    }

    header("Location: dashboard.php");

    exit;

}
?>

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

<meta charset="UTF-8">

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

<title>Pronóstico | COQUINIELA</title>

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

<style>

body{

    margin:0;

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

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

    font-family:Arial;

    color:white;

    min-height:100vh;
}

.container-main{

    padding:20px;
}

.logo{

    width:220px;

    display:block;

    margin:20px auto;
}

.card-main{

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

    backdrop-filter:blur(10px);

    border-radius:25px;

    padding:25px;

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

.teams{

    text-align:center;

    font-size:28px;

    font-weight:bold;

    margin-bottom:20px;
}

.date{

    text-align:center;

    color:#ddd;

    margin-bottom:30px;
}

.score-container{

    display:flex;

    justify-content:center;
    align-items:center;

    gap:20px;

    margin-bottom:30px;
}

.score-input{

    width:100px;

    height:100px;

    border:none;

    border-radius:20px;

    text-align:center;

    font-size:40px;

    font-weight:bold;
    
    background:#eee;

color:#001B4D;
}
.score-input[readonly]{

    opacity:.7;

    cursor:not-allowed;

    background:#d9d9d9;

}
.vs{

    font-size:40px;

    font-weight:bold;

    color:#F4C400;
}

.btn-save{

    width:100%;

    height:60px;

    border:none;

    border-radius:18px;

    background:#F4C400;

    color:#001B4D;

    font-size:22px;

    font-weight:bold;
}

.alert-custom{

    background:#198754;

    padding:15px;

    border-radius:15px;

    text-align:center;

    margin-bottom:20px;
}

.blocked{

    background:#dc3545;

    padding:15px;

    border-radius:15px;

    text-align:center;

    margin-bottom:20px;
}

.back{

    color:white;

    text-decoration:none;

    display:inline-block;

    margin-bottom:20px;
}

</style>

</head>
<body>

<div class="container-main">

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

    <a href="dashboard.php" class="back">
        ← Volver
    </a>

    <div class="card-main">

        <?php if(isset($_GET["ok"])){ ?>

            <div class="alert-custom">
                Pronóstico guardado correctamente 🔥
            </div>

        <?php } ?>

        <?php if($bloqueado){ ?>

            <div class="blocked">
                Pronósticos cerrados ⛔⚽
            </div>

        <?php } ?>
        
        <?php if($pronostico){ ?>

    <div class="alert-custom">

        ✅ Tu pronóstico ya fue guardado correctamente

    </div>

<?php } ?>
        

        <div class="teams">

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

            VS

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

        </div>

        <div class="date">

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

        </div>

        <form method="POST">

            <div class="score-container">

              <input

    type="number"

    name="goles_local"

    class="score-input"

    min="0"

    required

    <?php if($pronostico){ echo "readonly"; } ?>

    value="<?php

    echo $pronostico["goles_local"] ?? '';

    ?>"

>

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

                <input

    type="number"

    name="goles_visitante"

    class="score-input"

    min="0"

    required

    <?php if($pronostico){ echo "readonly"; } ?>

    value="<?php

    echo $pronostico["goles_visitante"] ?? '';

    ?>"

>

            </div>

            <?php if(!$bloqueado && !$pronostico){ ?>

                <button class="btn-save">
                    Guardar Pronóstico
                </button>

            <?php } ?>

        </form>

    </div>

</div>
<script>

window.addEventListener("pageshow", function(event){

    if(event.persisted){

        window.location.reload();

    }

});

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