<?php
require 'conexion.php';

/* ===== Captura de filtros ===== */
$localidad = $_GET['localidad'] ?? '';
$barrio    = $_GET['barrio']    ?? '';
$operacion = $_GET['operacion'] ?? '';
$tipo      = $_GET['tipo']      ?? '';
$ambientes = $_GET['ambientes'] ?? '';

/* ===== SQL dinámica con prepared ===== */
$sql = "SELECT * FROM propiedades WHERE 1=1";
$params = [];
$types  = '';

if ($localidad) { $sql .= " AND localidad = ?"; $params[] = $localidad; $types .= 's'; }
if ($barrio)    { $sql .= " AND barrio = ?";    $params[] = $barrio;    $types .= 's'; }
if ($operacion) { $sql .= " AND operacion = ?"; $params[] = $operacion; $types .= 's'; }
if ($tipo)      { $sql .= " AND tipo = ?";      $params[] = $tipo;      $types .= 's'; }
if ($ambientes !== '') { $sql .= " AND ambientes = ?"; $params[] = (int)$ambientes; $types .= 'i'; }

$sql .= " ORDER BY id DESC";

$stmt = $conn->prepare($sql);
if (!empty($params)) { $stmt->bind_param($types, ...$params); }
$stmt->execute();
$result = $stmt->get_result();

/* ===== Localidades para select ===== */
$loc_query = $conn->query("SELECT DISTINCT localidad FROM propiedades WHERE localidad <> '' ORDER BY localidad ASC");
$localidades = $loc_query ? $loc_query->fetch_all(MYSQLI_ASSOC) : [];

?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Buscador de Propiedades</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" />
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&family=Playfair+Display:wght@400;600;700&display=swap" rel="stylesheet">
  <link rel="icon" href="img/faviconcin.png" type="image/png">
  <style>
    /* ====== Theme (igual a index/propiedad) ====== */
    :root{
      --primary:#8f82ae;
      --primary-600:#7c6ca0;
      --primary-700:#6b5d90;
      --accent:#e74c3c;
      --dark:#1e293b;
      --muted:#64748b;
      --line:#e2e8f0;
      --bg:#f8fafc;
      --radius:14px;
      --shadow:0 6px 18px rgba(2,8,23,.08);
      --shadow-lg:0 14px 32px rgba(2,8,23,.15);
      --grad:linear-gradient(135deg, var(--primary) 0%, #5d89ff 100%);
    }
    body{font-family:'Poppins',system-ui,-apple-system,Segoe UI,Roboto,'Helvetica Neue',Arial,sans-serif;color:var(--dark);background:#fff}
    h1,h2,h3{font-family:'Playfair Display',serif}
    .navbar-premium{background: rgba(17,24,39,.6);backdrop-filter:saturate(140%) blur(8px);border-bottom:1px solid rgba(255,255,255,.08)}
    .brand-img{height:30px}
    .search-wrap{background:var(--grad);color:#fff;padding:2.25rem 0;box-shadow:var(--shadow)}
    .search-wrap .form-label{color:#fff;font-weight:600}
    .search-wrap .form-select{border:1px solid rgba(255,255,255,.4);background:#fff;border-radius:10px}
    .btn-theme{background:var(--primary);border:none;border-radius:12px;padding:.75rem 1.25rem;font-weight:600;box-shadow:var(--shadow)}
    .btn-theme:hover{background:var(--primary-600)}

    .prop-card{border:none;border-radius:16px;overflow:hidden;background:#fff;box-shadow:var(--shadow);transition:.28s;height:100%}
    .prop-card:hover{transform:translateY(-6px);box-shadow:var(--shadow-lg)}
    .prop-img{height:220px;width:100%;object-fit:cover}
    .prop-title{color:#0f172a;font-weight:700}
    .price{color:var(--accent);font-weight:800;font-size:1.1rem}
    .meta{color:var(--muted);font-size:.95rem}
    .badge-feature{background:var(--bg);border:1px solid var(--line);border-radius:999px;padding:.35rem .7rem;font-weight:600;color:var(--muted)}

    .nores{background:var(--bg);border:1px dashed var(--line);border-radius:16px;padding:2.5rem;text-align:center}
  </style>
  <script>
    function cargarBarrios() {
      const locSel = document.getElementById('localidad');
      const barrioSel = document.getElementById('barrio');
      const loc = locSel.value;
      barrioSel.innerHTML = '<option value=\"\">Todos</option>';
      barrioSel.disabled = true;
      if (!loc) return;
      fetch('ajax_barrios.php?localidad=' + encodeURIComponent(loc))
        .then(r => r.json())
        .then(data => {
          if (Array.isArray(data) && data.length) {
            data.forEach(function(b){
              const opt = document.createElement('option');
              opt.value = b; opt.textContent = b;
              if (b === <?php echo json_encode($barrio); ?>) opt.selected = true;
              barrioSel.appendChild(opt);
            });
            barrioSel.disabled = false;
          }
        })
        .catch(console.error);
    }
    document.addEventListener('DOMContentLoaded', cargarBarrios);
  </script>
</head>
<body>

<nav class="navbar navbar-expand-lg navbar-dark navbar-premium sticky-top">
  <div class="container">
    <a class="navbar-brand d-flex align-items-center gap-2" href="index.php">
      <img src="img/faviconcin3.png" class="brand-img" alt="Logo">
      <span>David Lagar · Servicios Inmobiliarios</span>
    </a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#nav">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div id="nav" class="collapse navbar-collapse"></div>
  </div>
</nav>

<div class="search-wrap">
  <div class="container">
    <h4 class="mb-4 fw-semibold">Encontrá tu propiedad ideal</h4>
    <form action="buscador.php" method="get" class="row g-3 align-items-end">
      <div class="col-md-3">
        <label class="form-label">Localidad</label>
        <select name="localidad" id="localidad" class="form-select" onchange="cargarBarrios()">
          <option value="">Todas</option>
          <?php foreach ($localidades as $loc): ?>
            <option value="<?= htmlspecialchars($loc['localidad']) ?>" <?= $localidad === $loc['localidad'] ? 'selected' : '' ?>>
              <?= htmlspecialchars($loc['localidad']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-3">
        <label class="form-label">Barrio</label>
        <select name="barrio" id="barrio" class="form-select" disabled>
          <option value="">Todos</option>
        </select>
      </div>
      <div class="col-md-2">
        <label class="form-label">Operación</label>
        <select name="operacion" class="form-select">
          <option value="">Todas</option>
          <option value="Comprar" <?= $operacion==='Comprar'?'selected':'' ?>>Comprar</option>
          <option value="Alquilar" <?= $operacion==='Alquilar'?'selected':'' ?>>Alquilar</option>
        </select>
      </div>
      <div class="col-md-2">
        <label class="form-label">Tipo</label>
        <select name="tipo" class="form-select">
          <option value="">Todos</option>
          <?php foreach (['Casa','Departamento','PH','Lote','Galpón','Garage','Oficina'] as $t): ?>
            <option value="<?= $t ?>" <?= $tipo===$t?'selected':'' ?>><?= $t ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-1">
        <label class="form-label">Amb.</label>
        <select name="ambientes" class="form-select">
          <option value="">--</option>
          <?php for ($i=1;$i<=4;$i++): ?>
            <option value="<?= $i ?>" <?= $ambientes===(string)$i?'selected':'' ?>><?= $i ?></option>
          <?php endfor; ?>
        </select>
      </div>
      <div class="col-md-1">
        <button type="submit" class="btn btn-theme w-100"><i class="bi bi-search"></i></button>
      </div>
    </form>
  </div>
</div>

<div class="container py-5">
  <?php if ($result->num_rows === 0): ?>
    <div class="nores">
      <div class="display-6 mb-2"><i class="bi bi-house-x"></i></div>
      <h5 class="fw-bold mb-2">No se encontraron propiedades</h5>
      <p class="text-muted mb-3">Ajustá los filtros y volvé a intentar.</p>
      <a href="index.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-left"></i> Volver</a>
    </div>
  <?php else: ?>
    <div class="mb-3 text-muted fw-semibold"><?= $result->num_rows ?> propiedades encontradas</div>
    <div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-4">
      <?php while ($fila = $result->fetch_assoc()): ?>
        <div class="col">
          <div class="prop-card h-100">
            <?php if (!empty($fila['imagen'])): ?>
              <img src="uploads/<?= htmlspecialchars($fila['imagen']) ?>" class="prop-img" alt="<?= htmlspecialchars($fila['titulo']) ?>">
            <?php else: ?>
              <div class="prop-img d-flex align-items-center justify-content-center bg-light">
                <i class="bi bi-house text-muted" style="font-size:3rem"></i>
              </div>
            <?php endif; ?>
            <div class="p-3">
              <h5 class="prop-title mb-1">
                <a href="propiedad.php?id=<?= (int)$fila['id'] ?>" class="text-decoration-none"><?= htmlspecialchars($fila['titulo']) ?></a>
              </h5>
              <?php
                $precio = isset($fila['precio']) && is_numeric($fila['precio']) ? number_format((float)$fila['precio'], 0, ',', '.') : 'Consultar';
              ?>
              <div class="price"><?= ($fila['moneda'] ?? 'ARS') === 'USD' ? 'USD ' : '$ ' ?><?= $precio ?></div>
              <div class="meta mb-2"><i class="bi bi-geo-alt"></i> <?= htmlspecialchars(($fila['barrio'] ?? '').', '.($fila['localidad'] ?? '')) ?></div>
              <div class="d-flex flex-wrap gap-2">
                <span class="badge-feature"><i class="bi bi-door-open me-1"></i><?= htmlspecialchars((string)($fila['ambientes'] ?? '')) ?> amb.</span>
                <span class="badge-feature"><i class="bi bi-building me-1"></i><?= htmlspecialchars($fila['tipo'] ?? '') ?></span>
                <span class="badge-feature"><i class="bi bi-arrow-left-right me-1"></i><?= htmlspecialchars($fila['operacion'] ?? '') ?></span>
              </div>
              <a href="propiedad.php?id=<?= (int)$fila['id'] ?>" class="btn btn-outline-secondary w-100 mt-3">Ver detalles</a>
            </div>
          </div>
        </div>
      <?php endwhile; ?>
    </div>
  <?php endif; ?>
</div>

<?php $stmt->close(); $conn->close(); ?>

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