<?php
declare(strict_types=1);

require_once __DIR__ . '/../auth/guard.php';
require_once __DIR__ . '/../conexion.php';
require_once __DIR__ . '/../_helpers.php';

$u = require_login();
require_module_access($u, "vivienda");

if (!function_exists('respond')) {
  function respond(array $payload, int $code = 200): void { json_response($payload, $code); }
}
if (!function_exists('respond_error')) {
  function respond_error(string $msg, int $code = 400): void { json_response(['ok'=>false,'message'=>$msg], $code); }
}

$raw = file_get_contents('php://input');
$body = json_decode($raw ?: '[]', true);
if (!is_array($body)) $body = [];

$q  = trim((string)($body['q'] ?? ''));
$sz = trim((string)($body['sectorizacion'] ?? ''));
$sc = trim((string)($body['sector'] ?? ''));
$tp = trim((string)($body['tipo'] ?? ''));

try {
  $where = [];
  $params = [];

  if ($q !== '') {
    $where[] = "(v.cod_vivienda LIKE :q OR v.direccion LIKE :q)";
    $params[':q'] = "%$q%";
  }
  if ($sz !== '') {
    $where[] = "v.sectorizacion = :sz";
    $params[':sz'] = $sz;
  }
  if ($sc !== '') {
    $where[] = "v.sector = :sc";
    $params[':sc'] = $sc;
  }
  if ($tp !== '') {
    $where[] = "v.tipo_vivienda = :tp";
    $params[':tp'] = $tp;
  }

  $sql = "
    SELECT
      v.id, v.cod_vivienda, v.direccion, v.sectorizacion, v.sector,
      v.latitud, v.longitud,
      v.tipo_vivienda, v.tenencia, v.conservacion, v.calefaccion,
      v.numero_piezas, v.numero_dormitorios, v.numero_camas,
      v.creado_en, v.ultima_actualizacion, v.registrado_por,
      sz.nombre_sectorizacion,
      s.nombre_sector,
      v.codigo_familia
    FROM vivienda v
    LEFT JOIN sectorizacion sz ON sz.id = v.sectorizacion
    LEFT JOIN sectores s ON s.id = v.sector
  ";

  if ($where) $sql .= " WHERE " . implode(" AND ", $where);
  $sql .= " ORDER BY v.id DESC LIMIT 250";

  $st = $pdo->prepare($sql);
  $st->execute($params);
  $rows = $st->fetchAll(PDO::FETCH_ASSOC);
  if (!is_array($rows)) $rows = [];

  // ---- familias por vivienda (si existe vivienda_familias) ----
  $byId = [];
  $ids = [];
  foreach ($rows as &$r) {
    $r['familias'] = [];
    $byId[(string)$r['id']] = &$r;
    $ids[] = (int)$r['id'];
  }
  unset($r);

  if ($ids) {
    try {
      $in = implode(',', array_fill(0, count($ids), '?'));
      $stF = $pdo->prepare("
        SELECT vf.id_vivienda, vf.codigo_familia, f.apellido_familia
        FROM vivienda_familias vf
        LEFT JOIN familias f ON f.codigo_familia = vf.codigo_familia
        WHERE vf.id_vivienda IN ($in)
        ORDER BY vf.id_vivienda, vf.codigo_familia
      ");
      $stF->execute($ids);
      $fams = $stF->fetchAll(PDO::FETCH_ASSOC);
      if (is_array($fams)) {
        foreach ($fams as $f) {
          $vid = (string)($f['id_vivienda'] ?? '');
          if ($vid !== '' && isset($byId[$vid])) {
            $byId[$vid]['familias'][] = [
              'codigo'  => (string)($f['codigo_familia'] ?? ''),
              'apellido'=> (string)($f['apellido_familia'] ?? ''),
            ];
          }
        }
      }
    } catch (Throwable $e) {
      // si no existe la tabla puente, hacemos fallback con vivienda.codigo_familia
    }
  }

  // fallback: si no hay tabla puente o no hay familias, usar vivienda.codigo_familia si viene
  foreach ($rows as &$r) {
    if (empty($r['familias']) && !empty($r['codigo_familia'])) {
      $r['familias'][] = ['codigo'=>(string)$r['codigo_familia'], 'apellido'=>''];
    }
  }
  unset($r);

  respond([
    'ok' => true,
    'data' => $rows,
    'total' => count($rows)
  ]);

} catch (Throwable $e) {
  error_log("VIVIENDA list ERROR: ".$e->getMessage());
  respond_error("Error de servidor", 500);
}
