<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require '../conexion.php';

if ($_SERVER["REQUEST_METHOD"] === "POST") {
  $titulo      = $_POST['titulo'] ?? '';
  $descripcion = $_POST['descripcion'] ?? '';
  $tipo        = $_POST['tipo'] ?? '';
  $operacion   = $_POST['operacion'] ?? '';
  $precio      = $_POST['precio'] ?? 0;
  $moneda      = $_POST['moneda'] ?? 'ARS'; // NUEVO
  $localidad   = $_POST['localidad'] ?? '';
  $barrio      = $_POST['barrio'] ?? '';
  $ambientes   = intval($_POST['ambientes'] ?? 0);

  // NUEVOS CAMPOS
  $m2      = (isset($_POST['m2']) && $_POST['m2'] !== '') ? (float)$_POST['m2'] : null;
  $banos   = (isset($_POST['banos']) && $_POST['banos'] !== '') ? (int)$_POST['banos'] : null;
  $cochera = isset($_POST['cochera']) ? (int)$_POST['cochera'] : 0;

  $imagen_principal = '';
  if (isset($_FILES['imagen']) && $_FILES['imagen']['error'] === UPLOAD_ERR_OK) {
    $imagen_principal = uniqid() . '_' . basename($_FILES['imagen']['name']);
    move_uploaded_file($_FILES['imagen']['tmp_name'], '../uploads/' . $imagen_principal);
  }

  $stmt = $conn->prepare("
    INSERT INTO propiedades 
      (titulo, descripcion, tipo, operacion, precio, moneda, localidad, barrio, ambientes, m2, banos, cochera, imagen)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  ");

  $stmt->bind_param(
    "ssssdsssidiis",
    $titulo,
    $descripcion,
    $tipo,
    $operacion,
    $precio,
    $moneda,
    $localidad,
    $barrio,
    $ambientes,
    $m2,
    $banos,
    $cochera,
    $imagen_principal
  );

  if ($stmt->execute()) {
    $propiedad_id = $stmt->insert_id;

    if (!empty($_FILES['galeria']['name'][0])) {
      foreach ($_FILES['galeria']['tmp_name'] as $key => $tmp_name) {
        if ($_FILES['galeria']['error'][$key] === UPLOAD_ERR_OK) {
          $nombre = uniqid() . '_' . basename($_FILES['galeria']['name'][$key]);
          move_uploaded_file($tmp_name, '../uploads/' . $nombre);
          $stmt_img = $conn->prepare("INSERT INTO imagenes_propiedades (propiedad_id, archivo) VALUES (?, ?)");
          $stmt_img->bind_param("is", $propiedad_id, $nombre);
          $stmt_img->execute();
          $stmt_img->close();
        }
      }
    }

    echo "<div class='container mt-4'><div class='alert alert-success'>Propiedad cargada correctamente.</div></div>";
  } else {
    echo "<div class='container mt-4'><div class='alert alert-danger'>Error: " . $stmt->error . "</div></div>";
  }

  $stmt->close();
  $conn->close();
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <title>Cargar Propiedad</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body { background-color: #f8f9fa; }
    .card { border-radius: 16px; box-shadow: 0 0 18px rgba(0,0,0,0.05); }
    .form-label { font-weight: 500; }
    .btn-primary { padding: 10px 20px; font-weight: 500; }
  </style>
</head>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
  <div class="container">
    <a class="navbar-brand" href="index.php">
      <i class="bi bi-house-door-fill"></i> Cargar propiedades
    </a>
    <div class="ms-auto">
      <a href="dashboard.php" class="btn btn-outline-light">
        <i class="bi bi-arrow-left"></i> Volver
      </a>
    </div>
  </div>
</nav>

<body>
  <div class="container py-5">
    <div class="row justify-content-center">
      <div class="col-lg-8">
        <div class="card p-4">
          <h2 class="mb-4 text-center">Cargar nueva propiedad</h2>
          <form method="post" enctype="multipart/form-data">
            
            <div class="mb-3">
              <label for="titulo" class="form-label">Título</label>
              <input type="text" class="form-control" id="titulo" name="titulo" required>
            </div>

            <div class="mb-3">
              <label for="descripcion" class="form-label">Descripción</label>
              <textarea class="form-control" id="descripcion" name="descripcion" rows="4"></textarea>
            </div>

            <div class="mb-3">
              <label for="tipo" class="form-label">Tipo de propiedad</label>
              <select class="form-select" id="tipo" name="tipo" required>
                <option value="">Seleccionar tipo</option>
                <option value="Casa">Casa</option>
                <option value="Departamento">Departamento</option>
                <option value="PH">PH</option>
                <option value="Lote">Lote</option>
                <option value="Galpón">Galpón</option>
                <option value="Garage">Garage</option>
                <option value="Oficina">Oficina</option>
              </select>
            </div>

            <div class="mb-3">
              <label for="operacion" class="form-label">Operación</label>
              <select class="form-select" id="operacion" name="operacion" required>
                <option value="">Seleccionar operación</option>
                <option value="Comprar">Comprar</option>
                <option value="Alquilar">Alquilar</option>
              </select>
            </div>

            <div class="row">
              <div class="col-md-6 mb-3">
                <label for="moneda" class="form-label">Moneda</label>
                <select class="form-select" id="moneda" name="moneda" required>
                  <option value="ARS">Pesos (ARS)</option>
                  <option value="USD">Dólares (USD)</option>
                </select>
              </div>
              <div class="col-md-6 mb-3">
                <label for="precio" class="form-label">Precio</label>
                <input type="number" step="0.01" class="form-control" id="precio" name="precio" required placeholder="Ej: 150000">
              </div>
            </div>

            <div class="row">
              <div class="col-md-6 mb-3">
                <label for="localidad" class="form-label">Localidad</label>
                <input type="text" class="form-control" id="localidad" name="localidad">
              </div>
              <div class="col-md-6 mb-3">
                <label for="barrio" class="form-label">Barrio</label>
                <input type="text" class="form-control" id="barrio" name="barrio">
              </div>
            </div>

            <div class="row">
              <div class="col-md-3 mb-3">
                <label for="ambientes" class="form-label">Ambientes</label>
                <input type="number" class="form-control" id="ambientes" name="ambientes" min="1" placeholder="Ej: 3">
              </div>
              <div class="col-md-3 mb-3">
                <label for="m2" class="form-label">Superficie (m²)</label>
                <input type="number" step="0.01" min="0" class="form-control" id="m2" name="m2" placeholder="Ej: 65">
              </div>
              <div class="col-md-3 mb-3">
                <label for="banos" class="form-label">Baños</label>
                <input type="number" min="0" class="form-control" id="banos" name="banos" placeholder="Ej: 1">
              </div>
              <div class="col-md-3 mb-3">
                <label for="cochera" class="form-label">Cochera</label>
                <select class="form-select" id="cochera" name="cochera">
                  <option value="0">No</option>
                  <option value="1">Sí</option>
                </select>
              </div>
            </div>

            <div class="mb-3">
              <label for="imagen" class="form-label">Imagen principal (preview)</label>
              <input type="file" class="form-control" id="imagen" name="imagen" accept="image/*">
            </div>

            <div class="mb-3">
              <label for="galeria" class="form-label">Galería de imágenes</label>
              <input type="file" class="form-control" id="galeria" name="galeria[]" multiple accept="image/*">
            </div>

            <div class="text-center">
              <button type="submit" class="btn btn-primary">Guardar propiedad</button>
            </div>

          </form>
        </div>
      </div>
    </div>
  </div>
</body>
</html>
