<?php
session_start();
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
include 'conexion.php';
$error = '';
$exito = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $error="❌ Token CSRF inválido. Posible intento de ataque.";
        enviarCorreo($para, $error, "Registo.");
    }
    $usuario = trim($_POST['usuario']);
    $clave = $_POST['clave'];
    $rol = $_POST['rol'];

    if (strlen($clave) < 6) {
        $error = "La contraseña debe tener al menos 6 caracteres.";
    } else {
        $hash = password_hash($clave, PASSWORD_DEFAULT);
        $stmt = $conexion->prepare("INSERT INTO usuarios (usuario, contraseña, rol) VALUES (?, ?, ?)");
        $stmt->bind_param("sss", $usuario, $hash, $rol);
        if ($stmt->execute()) {
            $exito = "✅ Usuario registrado correctamente.";
        } else {
            $error = "❌ El usuario ya existe o hubo un error.";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Registro</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="d-flex align-items-center justify-content-center vh-100 bg-light">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-11 col-sm-8 col-md-6 col-lg-4">
                <div class="card shadow-sm border-0">
                    <div class="card-body p-4">
                        <h4 class="card-title text-center mb-4">🧾 Registro de Usuario</h4>
                        <?php if ($error): ?>
                            <div class="alert alert-danger"><?= $error ?></div>
                        <?php elseif ($exito): ?>
                            <div class="alert alert-success"><?= $exito ?></div>
                        <?php endif; ?>
                        <form method="post" class="needs-validation" novalidate>
                            <div class="mb-3">
                                <label for="usuario" class="form-label">Usuario</label>
                                <input type="text" class="form-control" id="usuario" name="usuario" required>
                                <div class="invalid-feedback">Introduce un nombre de usuario.</div>
                            </div>
                            <div class="mb-3">
                                <label for="clave" class="form-label">Contraseña</label>
                                <input type="password" class="form-control" id="clave" name="clave" required minlength="6">
                                <div class="invalid-feedback">La contraseña debe tener al menos 6 caracteres.</div>
                            </div>
                            <div class="mb-3">
                                <label for="rol" class="form-label">Rol</label>
                                <select name="rol" id="rol" class="form-select" required>
                                    <option value="user">Usuario</option>
                                    <option value="admin">Administrador</option>
                                </select>
                                <div class="invalid-feedback">Selecciona un rol.</div>
                            </div>
                            <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                            <div class="d-grid">
                                <button type="submit" class="btn btn-success">Registrar</button>
                            </div>
                            <p></p>
                            <div class="d-grid">
                                <!--<a href="/index.php?id=<?= $id ?>" class="btn btn-warning btn-sm">✏️ Regresar</a>-->
                                <p class="mt-3 text-center text-muted small"><a href="gestionar_usuarios.php">❌ Volver a la gestión</a></p>
                            </div>
                        </form>
                        <!--<p class="mt-3 text-center text-muted small">¿Ya tienes cuenta? <a href="login.php">Inicia sesión</a></p>-->
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script>
    (() => {
        'use strict';
        const forms = document.querySelectorAll('.needs-validation');
        Array.from(forms).forEach(form => {
            form.addEventListener('submit', event => {
                if (!form.checkValidity()) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            }, false);
        });
    })();
    </script>
</body>
</html>
