<?php
require_once 'includes/auth.php';
exigir_rol('admin');
require_once 'conexion.php';
require_once 'includes/layout.php';

$error = $success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check();
    $nombre = trim($_POST['nombre']);
    $rut    = trim($_POST['rut']);
    $email  = trim($_POST['email']);
    $password = password_hash('123456', PASSWORD_BCRYPT);

    $stmt = $conn->prepare("SELECT 1 FROM usuarios WHERE email = ?");
    $stmt->bind_param('s', $email);
    $stmt->execute();
    if ($stmt->get_result()->num_rows > 0) {
        $error = 'El correo ya está registrado.';
    } else {
        $stmt = $conn->prepare("INSERT INTO usuarios (nombre, rut, email, password, rol, estado)
                                VALUES (?, ?, ?, ?, 'conserje', 'activo')");
        $stmt->bind_param('ssss', $nombre, $rut, $email, $password);
        if ($stmt->execute()) {
            $success = "Conserje creado con éxito. Contraseña inicial: '123456'";
        } else {
            $error = 'Error al crear el conserje: ' . $stmt->error;
        }
    }
}

page_header('Nuevo Conserje', 'nuevo_conserje');
?>

<div class="row justify-content-center">
  <div class="col-lg-6">
    <div class="card">
      <div class="card-header"><i class="bi bi-person-badge me-2 text-primary"></i> Crear Conserje</div>
      <div class="card-body">

        <?php if ($error): ?>
          <div class="alert alert-danger py-2"><i class="bi bi-x-circle me-1"></i><?= e($error) ?></div>
        <?php elseif ($success): ?>
          <div class="alert alert-success py-2"><i class="bi bi-check-circle me-1"></i><?= e($success) ?></div>
        <?php endif; ?>

        <form method="POST" action="">
          <?= csrf_field() ?>
          <div class="mb-3">
            <label class="form-label">Nombre *</label>
            <input type="text" class="form-control" name="nombre" required>
          </div>
          <div class="mb-3">
            <label class="form-label">RUT *</label>
            <input type="text" class="form-control" name="rut" required oninput="marcarRut(this)">
          </div>
          <div class="mb-3">
            <label class="form-label">Correo electrónico *</label>
            <input type="email" class="form-control" name="email" required>
          </div>
          <div class="alert alert-info py-2" style="font-size:13px">
            <i class="bi bi-info-circle me-1"></i> La contraseña inicial será <strong>123456</strong>.
            El conserje puede cambiarla luego en "Contraseña".
          </div>
          <div class="d-flex gap-2">
            <button type="submit" class="btn btn-primary"><i class="bi bi-check-lg me-1"></i> Crear Conserje</button>
            <a href="listar_conserjes.php" class="btn btn-outline-secondary">Ver conserjes</a>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<?php page_footer(); ?>
