<?php
require 'conexion.php';

/* ---------- Datos de la propiedad ---------- */
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if (!$id) { echo "ID inválido"; exit; }

/* Propiedad principal */
$stmt = $conn->prepare("SELECT * FROM propiedades WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$res = $stmt->get_result();
if ($res->num_rows === 0) { echo "Propiedad no encontrada"; exit; }
$p = $res->fetch_assoc();
$stmt->close();

/* Galería (otras imágenes) */
$stmt_gal = $conn->prepare("SELECT archivo FROM imagenes_propiedades WHERE propiedad_id = ? ORDER BY orden ASC");
$stmt_gal->bind_param("i", $id);
$stmt_gal->execute();
$gal_res = $stmt_gal->get_result();
$galeria = $gal_res->fetch_all(MYSQLI_ASSOC);
$stmt_gal->close();

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

$localidad = $_GET['localidad'] ?? '';
$barrio    = $_GET['barrio']    ?? '';
$operacion = $_GET['operacion'] ?? '';
$tipo      = $_GET['tipo']      ?? '';
$ambientes = $_GET['ambientes'] ?? '';

/* ---------- Helpers ---------- */
function fmt_precio($monto, $moneda) {
  $moneda = $moneda ?: 'ARS';
  $pref = ($moneda === 'USD') ? 'USD ' : '$ ';
  $val = (is_numeric($monto) ? number_format((float)$monto, 0, ',', '.') : 'Consultar');
  return $pref . $val;
}

$resumen = ($p['titulo'] ?? '')
  . " | " . ($p['tipo'] ?? '')
  . " | " . ((string)($p['ambientes'] ?? '')). " amb."
  . " | " . trim(($p['barrio'] ?? '').', '.($p['localidad'] ?? ''), ' ,')
  . " | " . fmt_precio(($p['precio'] ?? ''), ($p['moneda'] ?? 'ARS'));
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><?= htmlspecialchars($p['titulo']) ?> | Detalle de Propiedad</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/buscador) ====== */
    :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)}

    .header{padding:1.5rem 0;border-bottom:1px solid var(--line);margin-bottom:1rem}
    .price{color:var(--accent);font-weight:800;font-size:1.6rem}
    .detail{display:flex;align-items:center;gap:.6rem;margin-bottom:.6rem}
    .detail i{color:var(--primary-700)}
    .feature-chip{background:var(--bg);border:1px solid var(--line);border-radius:999px;padding:.45rem .85rem;font-weight:600;color:var(--muted)}
    .desc{background:var(--bg);border:1px solid var(--line);border-radius:14px;padding:1.25rem}
    .carousel{border-radius:16px;overflow:hidden;box-shadow:var(--shadow-lg);background:#000}
    .carousel-item img{height:500px;object-fit:cover}
    @media (max-width: 768px){ .carousel-item img{height:320px} }
  </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(b => {
            const opt = document.createElement('option');
            opt.value = b; opt.textContent = b;
            if (b === <?= json_encode($barrio) ?>) opt.selected = true;
            barrioSel.appendChild(opt);
          });
          barrioSel.disabled = false;
        }
      }).catch(()=>{});
  }
  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>

<!-- Buscador superior (consistente) -->
<div class="search-wrap">
  <div class="container">
    <h4 class="mb-4 fw-semibold">Encontrá tu propiedad ideal</h4>
    <form id="formConsulta" 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 ($a=1;$a<=4;$a++): ?>
            <option value="<?= $a ?>" <?= $ambientes==(string)$a?'selected':'' ?>><?= $a ?></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-4">
  <div class="header">
    <h1 class="h3 fw-bold mb-1"><?= htmlspecialchars($p['titulo']) ?></h1>
    <div class="price"><?= fmt_precio(($p['precio'] ?? ''), ($p['moneda'] ?? 'ARS')) ?></div>
    <div class="text-muted"><i class="bi bi-geo-alt-fill"></i> <?= htmlspecialchars(trim(($p['barrio'] ?? '').', '.($p['localidad'] ?? ''), ' ,')) ?></div>
  </div>

  <div class="row g-4">
    <div class="col-lg-8">
      <?php if (!empty($p['imagen'])): ?>
        <img src="uploads/<?= htmlspecialchars($p['imagen']) ?>" class="img-fluid rounded mb-4 shadow" alt="Imagen principal">
      <?php endif; ?>

      <?php if (!empty($galeria)): ?>
        <div id="carouselGal<?= $id ?>" class="carousel slide mb-4" data-bs-ride="carousel">
          <div class="carousel-inner">
            <?php foreach ($galeria as $i => $g): ?>
              <div class="carousel-item <?= $i===0?'active':'' ?>">
                <img src="uploads/<?= htmlspecialchars($g['archivo']) ?>" class="d-block w-100" alt="Imagen <?= $i+1 ?>">
              </div>
            <?php endforeach; ?>
          </div>
          <button class="carousel-control-prev" type="button" data-bs-target="#carouselGal<?= $id ?>" data-bs-slide="prev">
            <span class="carousel-control-prev-icon"></span>
          </button>
          <button class="carousel-control-next" type="button" data-bs-target="#carouselGal<?= $id ?>" data-bs-slide="next">
            <span class="carousel-control-next-icon"></span>
          </button>
        </div>
      <?php endif; ?>

      <div class="desc">
        <h5 class="fw-bold mb-2">Descripción</h5>
        <p class="mb-0"><?= nl2br(htmlspecialchars($p['descripcion'] ?? '')) ?></p>
      </div>
    </div>

    <div class="col-lg-4">
      <div class="card shadow-sm rounded-4">
        <div class="card-body">
          <h5 class="fw-bold mb-3">Detalles</h5>

          <div class="detail"><i class="bi bi-building"></i><span class="fw-semibold">Tipo:</span><span><?= htmlspecialchars($p['tipo'] ?? '') ?></span></div>
          <div class="detail"><i class="bi bi-arrow-left-right"></i><span class="fw-semibold">Operación:</span><span><?= htmlspecialchars($p['operacion'] ?? '') ?></span></div>
          <div class="detail"><i class="bi bi-door-open"></i><span class="fw-semibold">Ambientes:</span><span><?= htmlspecialchars((string)($p['ambientes'] ?? '')) ?></span></div>
          <div class="detail"><i class="bi bi-pin-map-fill"></i><span class="fw-semibold">Ubicación:</span><span><?= htmlspecialchars(trim(($p['barrio'] ?? '').', '.($p['localidad'] ?? ''), ' ,')) ?></span></div>
          <div class="detail"><i class="bi bi-currency-dollar"></i><span class="fw-semibold">Precio:</span><span class="fw-bold"><?= fmt_precio(($p['precio'] ?? ''), ($p['moneda'] ?? 'ARS')) ?></span></div>

          <div class="mt-3 d-flex flex-wrap gap-2">
            <span class="feature-chip"><i class="bi bi-aspect-ratio me-1"></i>
              <?php
                if (isset($p['m2']) && $p['m2'] !== '' && $p['m2'] !== null) {
                  echo number_format((float)$p['m2'], 2, ',', '.') . ' m²';
                } elseif (isset($p['metros']) && $p['metros'] !== '') {
                  echo htmlspecialchars($p['metros']) . ' m²';
                } else {
                  echo '--';
                }
              ?>
            </span>
            <span class="feature-chip"><i class="bi bi-droplet me-1"></i>
              <?= (isset($p['banos']) && $p['banos'] !== '' && $p['banos'] !== null) ? (int)$p['banos'] . ' baño' . (((int)$p['banos']===1)?'':'s') : '--' ?>
            </span>
            <span class="feature-chip"><i class="bi bi-car-front-fill me-1"></i>
              <?php
                if (isset($p['cocheras'])) {
                  $n = (int)$p['cocheras'];
                  echo $n . ' cochera' . ($n===1?'':'s');
                } elseif (isset($p['cochera'])) {
                  echo ((int)$p['cochera']===1) ? 'Sí' : 'No';
                } else {
                  echo '--';
                }
              ?>
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Formulario de consulta -->
  <div class="card shadow-sm rounded-4 mt-4">
    <div class="card-header bg-light fw-bold"><i class="bi bi-envelope-fill"></i> Consultá por esta propiedad</div>
    <div class="card-body">
      <?php if (isset($_GET['ok'])): ?>
        <div class="alert alert-success d-flex align-items-center"><i class="bi bi-check-circle-fill me-2"></i><div>Tu mensaje fue enviado, te contactaremos pronto.</div></div>
      <?php elseif (isset($_GET['error'])): ?>
        <div class="alert alert-danger d-flex align-items-center"><i class="bi bi-exclamation-triangle-fill me-2"></i><div>Ocurrió un error al enviar. Intentá más tarde.</div></div>
      <?php endif; ?>

      <form action="enviar.php" method="post">
        <input type="hidden" name="propiedad_id" value="<?= (int)$id ?>">
        <input type="hidden" name="propiedad_resumen" value="<?= htmlspecialchars($resumen, ENT_QUOTES) ?>">

        <div class="mb-3">
          <label class="form-label">Propiedad</label>
          <input type="text" class="form-control" value="<?= htmlspecialchars($resumen) ?>" readonly>
        </div>
        <div class="mb-3">
          <label class="form-label">Nombre</label>
          <input type="text" name="nombre" class="form-control" required>
        </div>
        <div class="mb-3">
          <label class="form-label">Teléfono</label>
          <input type="text" name="telefono" class="form-control" required>
        </div>
        <div class="mb-3">
          <label class="form-label">Mensaje</label>
          <textarea name="mensaje" class="form-control" rows="5"></textarea>
        </div>
        <button type="submit" class="btn btn-theme"><i class="bi bi-send-fill"></i> Enviar consulta</button>
      </form>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function(){
  const form = document.getElementById('formConsulta');
  if (form) {
    form.addEventListener('submit', function(){
      const btn = form.querySelector('button[type=submit]');
      if (btn) { btn.disabled = true; btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Enviando...'; }
    });
  }
});
</script>
</body>
</html>
