<?php
// public/register.php
session_start();
require '../src/db.php';

// Si ya está logueado, va al dashboard
if (isset($_SESSION['user'])) {
    header('Location: index.php');
    exit;
}

$errors = [];
$success = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nombre   = trim($_POST['nombre']);
    $email    = trim($_POST['email']);
    $passw    = $_POST['password'];
    $passw2   = $_POST['password2'];

    // Validaciones básicas
    if (!$nombre)  $errors[] = "El nombre es obligatorio.";
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "El email no es válido.";
    }
    if (strlen($passw) < 6) {
        $errors[] = "La contraseña debe tener al menos 6 caracteres.";
    }
    if ($passw !== $passw2) {
        $errors[] = "Las contraseñas no coinciden.";
    }

    // Verificar email único
    if (empty($errors)) {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM usuarios WHERE email = ?");
        $stmt->execute([$email]);
        if ($stmt->fetchColumn() > 0) {
            $errors[] = "Ese email ya está registrado.";
        }
    }

    // Insertar usuario
    if (empty($errors)) {
        $hash = password_hash($passw, PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("INSERT INTO usuarios (nombre, email, password) VALUES (?, ?, ?)");
        $stmt->execute([$nombre, $email, $hash]);
        $success = "Registro exitoso. Ya puedes <a href='login.php'>iniciar sesión</a>.";
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <title>Registrarse | Biblioteca Virtual</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="style.css">
</head>
<body class="d-flex align-items-center justify-content-center vh-100">
  <div class="card shadow-sm p-4" style="width: 100%; max-width: 450px;">
    <h2 class="text-center mb-4">Crear cuenta</h2>

    <?php if ($errors): ?>
      <div class="alert alert-danger">
        <ul class="mb-0">
          <?php foreach ($errors as $e): ?>
            <li><?= htmlspecialchars($e) ?></li>
          <?php endforeach; ?>
        </ul>
      </div>
    <?php elseif ($success): ?>
      <div class="alert alert-success"><?= $success ?></div>
    <?php endif; ?>

    <form method="post" novalidate>
      <div class="mb-3">
        <label for="nombre" class="form-label">Nombre completo</label>
        <input type="text" id="nombre" name="nombre" class="form-control" required>
      </div>
      <div class="mb-3">
        <label for="email" class="form-label">Correo electrónico</label>
        <input type="email" id="email" name="email" class="form-control" required>
      </div>
      <div class="mb-3">
        <label for="password" class="form-label">Contraseña</label>
        <input type="password" id="password" name="password" class="form-control" required>
      </div>
      <div class="mb-4">
        <label for="password2" class="form-label">Repetir contraseña</label>
        <input type="password" id="password2" name="password2" class="form-control" required>
      </div>
      <div class="d-grid gap-2">
        <button type="submit" class="btn btn-primary">Registrarse</button>
        <a href="login.php" class="btn btn-outline-secondary">Volver al login</a>
      </div>
    </form>
  </div>

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