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

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

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

    $nombre = trim($_POST["nombre"]);

    $usuario = trim($_POST["usuario"]);

    $password = password_hash(
        $_POST["password"],
        PASSWORD_DEFAULT
    );

    $rol = $_POST["rol"];
    
    $pagado = floatval($_POST["pagado"]);

$foto = "";

if(isset($_FILES["foto"]) && $_FILES["foto"]["name"] != ""){

    $extension = pathinfo(
        $_FILES["foto"]["name"],
        PATHINFO_EXTENSION
    );

    $foto = uniqid().".".$extension;

    move_uploaded_file(
        $_FILES["foto"]["tmp_name"],
        "../assets/img/usuarios/".$foto
    );

}

    $sqlInsert = "INSERT INTO usuarios(
        nombre,

        usuario,

        password,

        rol,

        puntos,

        pagado,

        foto
    ) VALUES(
        :nombre,

        :usuario,

        :password,

        :rol,

        0,

        :pagado,

        :foto
    )";

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

    $stmtInsert->bindParam(":nombre", $nombre);
    $stmtInsert->bindParam(":usuario", $usuario);
    $stmtInsert->bindParam(":password", $password);
    $stmtInsert->bindParam(":rol", $rol);
    $stmtInsert->bindParam(":pagado", $pagado);

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

    $stmtInsert->execute();

    header("Location: usuarios.php?ok=1");
    exit;
}

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

if(isset($_GET["eliminar"])){

    $id = intval($_GET["eliminar"]);

    $sqlDelete = "DELETE FROM usuarios
    WHERE id = :id";

    $stmtDelete = $conexion->prepare($sqlDelete);

    $stmtDelete->bindParam(":id", $id);

    $stmtDelete->execute();

    header("Location: usuarios.php");
    exit;
}

/* =========================================
RESET PASSWORD
========================================= */

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

    $id = intval($_POST["id_usuario"]);

    $password = password_hash(
        $_POST["nueva_password"],
        PASSWORD_DEFAULT
    );

    $sqlUpdate = "UPDATE usuarios
    SET password = :password
    WHERE id = :id";

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

    $stmtUpdate->bindParam(":password", $password);
    $stmtUpdate->bindParam(":id", $id);

    $stmtUpdate->execute();

    header("Location: usuarios.php?pass=1");
    exit;
}

/* =========================================
OBTENER USUARIOS
========================================= */

$sqlUsuarios = "SELECT *
FROM usuarios
ORDER BY puntos DESC";

$stmtUsuarios = $conexion->prepare($sqlUsuarios);

$stmtUsuarios->execute();

$usuarios = $stmtUsuarios->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>Usuarios | Admin</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,.92), rgba(0,27,77,.96)),
    url('../assets/img/fondo_estadio.jpg');

    background-size:cover;

    background-attachment:fixed;

    font-family:Arial;

    color:white;

    padding:20px;

    padding-bottom:110px;
}

.card-main{

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

    border-radius:25px;

    padding:25px;

    margin-bottom:20px;

    backdrop-filter:blur(10px);

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

.title{

    font-size:28px;

    font-weight:bold;

    margin-bottom:20px;
}

.form-control,
.form-select{

    height:50px;

    border:none;
}

.btn-save{

    width:100%;

    height:50px;

    border:none;

    border-radius:15px;

    background:#F4C400;

    color:#001B4D;

    font-weight:bold;
}

.user-card{
    
   

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

    border-radius:20px;

    padding:20px;

    margin-bottom:15px;

    backdrop-filter:blur(10px);
}

.user-name{

    font-size:22px;

    font-weight:bold;
}

.user-info{

    color:#ccc;

    margin-top:5px;
}

.user-points{

    color:#F4C400;

    font-size:28px;

    font-weight:bold;
}

.btn-action{

    border:none;

    border-radius:12px;

    padding:10px 15px;

    font-size:14px;

    margin-top:10px;
}

.btn-reset{

    background:#0d6efd;

    color:white;
}

.btn-delete{

    background:#dc3545;

    color:white;
}

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

@media(min-width:768px){

    .container-custom{

        max-width:900px;

        margin:auto;
    }
}

</style>

</head>
<body>

<div class="container-custom">

    <div class="card-main">

        <div class="title">
            👥 Administrar Usuarios
        </div>

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

            <div class="alert alert-success">
                Usuario creado correctamente
            </div>

        <?php } ?>

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

            <div class="alert alert-success">
                Contraseña actualizada
            </div>

        <?php } ?>

        <form method="POST" enctype="multipart/form-data">

            <div class="row">

                <div class="col-md-3 mb-3">

                    <input
                        type="text"
                        name="nombre"
                        class="form-control"
                        placeholder="Nombre"
                        required
                    >

                </div>

                <div class="col-md-3 mb-3">

                    <input
                        type="text"
                        name="usuario"
                        class="form-control"
                        placeholder="Usuario"
                        required
                    >

                </div>

                <div class="col-md-3 mb-3">

                    <input
                        type="password"
                        name="password"
                        class="form-control"
                        placeholder="Contraseña"
                        required
                    >

                </div>
                <div class="col-md-3 mb-3">

    <input
        type="number"
        step="0.01"
        name="pagado"
        class="form-control"
        placeholder="Pagó"
        required
    >

</div>

                <div class="col-md-3 mb-3">

                    <select
                        name="rol"
                        class="form-select"
                    >

                        <option value="usuario">
                            Usuario
                        </option>

                        <option value="admin">
                            Admin
                        </option>

                    </select>

                </div>

            </div>
<div class="col-md-3 mb-3">

    <input
        type="file"
        name="foto"
        class="form-control"
        accept="image/*"
    >

</div>
            <button
                class="btn-save"
                name="crear_usuario"
            >

                Crear Usuario

            </button>

        </form>

    </div>

    <!-- LISTA -->

    <?php foreach($usuarios as $usuario){ ?>

        <div class="user-card">

<?php

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

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

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

}

?>

<img

    src="<?php echo $foto; ?>"

    style="

    width:70px;

    height:70px;

    border-radius:50%;

    object-fit:cover;

    border:3px solid #F4C400;

    margin-bottom:15px;

    "

>


            <div class="d-flex justify-content-between">

                <div>

                    <div class="user-name">

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

                    </div>

                    <div class="user-info">

                        @<?php echo $usuario["usuario"]; ?>

                        •

                        <?php echo strtoupper($usuario["rol"]); ?>
                        <br>

💰 Pagó:

$<?php echo number_format($usuario["pagado"],2); ?>

                    </div>

                </div>

                <div class="user-points">

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

                    pts

                </div>

            </div>

            <!-- RESET PASSWORD -->

            <form
                method="POST"
                class="mt-3"
            >

                <input
                    type="hidden"
                    name="id_usuario"
                    value="<?php echo $usuario["id"]; ?>"
                >

                <div class="row">

                    <div class="col-md-8 mb-2">

                        <input
                            type="text"
                            name="nueva_password"
                            class="form-control"
                            placeholder="Nueva contraseña"
                            required
                        >

                    </div>

                    <div class="col-md-4 mb-2">

                        <button
                            class="btn-action btn-reset w-100"
                            name="reset_password"
                        >

                            Reset Password

                        </button>

                    </div>

                </div>

            </form>

            <!-- ELIMINAR -->

            <?php if($usuario["id"] != $_SESSION["usuario_id"]){ ?>

                <a
                    href="usuarios.php?eliminar=<?php echo $usuario["id"]; ?>"
                    onclick="return confirm('¿Eliminar usuario?')"
                >

                    <button class="btn-action btn-delete">

                        Eliminar Usuario

                    </button>

                </a>

            <?php } ?>

        </div>

    <?php } ?>

</div>

<!-- MENU -->

<div class="bottom-menu">

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

    <a href="partidos.php">
        <i class="bi bi-calendar-event-fill"></i>
        Partidos
    </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>