<?php
declare(strict_types=1);
session_start();
header('Content-Type: application/json; charset=utf-8');

require_once __DIR__.'/../conex.php';
$db = $conn ?? ($conex ?? null);
if (!$db) {
  echo json_encode(['success' => false, 'message' => 'Sin conexión']); exit;
}
mysqli_set_charset($db, 'utf8mb4');

$id = (int)($_POST['localidad'] ?? 0);

$sql = "SELECT idlocalidad, detalle, codigo 
        FROM tb_localidad 
        WHERE idlocalidad = $id AND condicion = 1 
        LIMIT 1";
$res = mysqli_query($db, $sql);

if ($res && $row = mysqli_fetch_assoc($res)) {
  echo json_encode([
    'success' => true,
    'id'      => (int)$row['idlocalidad'],
    'nombre'  => $row['detalle'],
    'codigo'  => $row['codigo'] ?? ''
  ]);
} else {
  echo json_encode(['success' => false, 'message' => 'Localidad no encontrada']);
}
