<?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($_POST['password'], PASSWORD_BCRYPT);
    $numero_departamento = trim($_POST['numero_departamento']);
    $celular  = trim($_POST['celular']);
    $estacionamiento = trim($_POST['estacionamiento']);

    $conn->begin_transaction();
    try {
        $stmt1 = $conn->prepare("INSERT INTO usuarios (nombre, rut, email, password, rol) VALUES (?, ?, ?, ?, 'propietario')");
        $stmt1->bind_param('ssss', $nombre, $rut, $email, $password);
        if (!$stmt1->execute()) {
            throw new Exception('No se pudo crear el usuario (¿RUT o email ya registrado?): ' . $stmt1->error);
        }
        $id_usuario = $conn->insert_id;

        $stmt2 = $conn->prepare("INSERT INTO propietarios (id_usuario, numero_departamento, celular, estacionamiento) VALUES (?, ?, ?, ?)");
        $stmt2->bind_param('isss', $id_usuario, $numero_departamento, $celular, $estacionamiento);
        if (!$stmt2->execute()) {
            throw new Exception('No se pudo crear el propietario: ' . $stmt2->error);
        }

        $conn->commit();
        $success = 'Propietario registrado con éxito.';
    } catch (Exception $e) {
        $conn->rollback();
        $error = $e->getMessage();
    }
}

page_header('Nuevo Propietario', 'nuevo_propietario');
?>

<div class="row justify-content-center">
  <div class="col-lg-7">
    <div class="card">
      <div class="card-header"><i class="bi bi-person-plus me-2 text-primary"></i> Registrar Propietario</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) ?>
            <a href="admin_dashboard.php" class="alert-link">Volver al dashboard</a></div>
        <?php endif; ?>

        <form method="POST" action="">
          <?= csrf_field() ?>
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label">Nombre *</label>
              <input type="text" class="form-control" name="nombre" required>
            </div>
            <div class="col-md-6">
              <label class="form-label">RUT *</label>
              <input type="text" class="form-control" name="rut" required oninput="marcarRut(this)" placeholder="12345678-9">
            </div>
            <div class="col-md-6">
              <label class="form-label">Correo electrónico *</label>
              <input type="email" class="form-control" name="email" required>
            </div>
            <div class="col-md-6">
              <label class="form-label">Contraseña *</label>
              <input type="password" class="form-control" name="password" required minlength="6">
            </div>
            <div class="col-md-4">
              <label class="form-label">N° Departamento *</label>
              <input type="text" class="form-control" name="numero_departamento" required>
            </div>
            <div class="col-md-4">
              <label class="form-label">Celular *</label>
              <input type="text" class="form-control" name="celular" required placeholder="+56 9 ...">
            </div>
            <div class="col-md-4">
              <label class="form-label">Estacionamiento *</label>
              <input type="text" class="form-control" name="estacionamiento" required>
            </div>
          </div>
          <div class="d-flex gap-2 mt-4">
            <button type="submit" class="btn btn-primary"><i class="bi bi-check-lg me-1"></i> Registrar</button>
            <a href="admin_dashboard.php" class="btn btn-outline-secondary">Volver</a>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<?php page_footer(); ?>
