<?php
// php/geolocalizacion_comunitaria/search_person.php
declare(strict_types=1);
require_once __DIR__ . '/_bootstrap.php';

$u = gcomm_user();

try {
  gcomm_ensure_tables($pdo);

  $src = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST' ? read_json_body() : $_GET;
  $q = gcomm_s($src['q'] ?? '');
  if ($q === '') {
    json_response(['ok' => true, 'data' => []]);
  }

  $rutKey = normalize_rut($q);
  $where = [];
  $params = [];

  if ($rutKey !== '') {
    $where[] = fp_sql_normalized_rut_expr('u.rut') . ' LIKE :rut';
    $params[':rut'] = fp_normalize_run_key($rutKey) . '%';
  }

  $where[] = "(
    COALESCE(u.nombres, '') LIKE :q
    OR COALESCE(u.apellidos, '') LIKE :q
    OR CONCAT(COALESCE(u.nombres,''), ' ', COALESCE(u.apellidos,'')) LIKE :q
    OR CONCAT(COALESCE(u.apellidos,''), ' ', COALESCE(u.nombres,'')) LIKE :q
    OR COALESCE(u.direccion, '') LIKE :q
    OR COALESCE(u.celular, '') LIKE :q
  )";
  $params[':q'] = '%' . $q . '%';

  $sql = "SELECT
      u.rut,
      u.nombres,
      u.apellidos,
      CONCAT(COALESCE(u.nombres,''), ' ', COALESCE(u.apellidos,'')) AS nombre_completo,
      u.genero,
      u.edad,
      u.direccion,
      u.latitud,
      u.longitud,
      u.sector,
      u.sectorizacion,
      u.celular,
      u.telefonos,
      s.nombre_sector,
      z.nombre_sectorizacion
    FROM usuarios u
    LEFT JOIN sectores s ON s.id = u.sector
    LEFT JOIN sectorizacion z ON z.id = u.sectorizacion
    WHERE " . implode(' OR ', $where) . "
    ORDER BY u.apellidos ASC, u.nombres ASC
    LIMIT 15";

  $st = $pdo->prepare($sql);
  foreach ($params as $k => $v) $st->bindValue($k, $v);
  $st->execute();

  json_response(['ok' => true, 'data' => $st->fetchAll(PDO::FETCH_ASSOC)]);
} catch (Throwable $e) {
  error_log('GEO COM SEARCH PERSON ERROR: ' . $e->getMessage());
  json_response(['ok' => false, 'message' => 'Error buscando persona.'], 500);
}
