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

require_once __DIR__ . '/../../odbconexion/odbconexion.php';

try {
  $db = (new odbconexion())->openconection();
  $db->set_charset("utf8mb4");

  $sql = "SELECT 
            Id_Clientes,
            Nombre_Completo,
            Apellido_Paterno,
            Apellido_Materno,
            RFC,
            Razon_Social_Persona_Moral
          FROM clientes
          ORDER BY Id_Clientes DESC";

  $res = $db->query($sql);
  $out = [];

  while($row = $res->fetch_assoc()){
    $nombre = trim(($row['Nombre_Completo'] ?? '') . ' ' . ($row['Apellido_Paterno'] ?? '') . ' ' . ($row['Apellido_Materno'] ?? ''));
    $razon  = trim($row['Razon_Social_Persona_Moral'] ?? '');
    $rfc    = trim($row['RFC'] ?? '');

    $label = $razon !== '' ? $razon : ($nombre !== '' ? $nombre : ('Cliente #' . $row['Id_Clientes']));
    if($rfc !== '') $label .= " — $rfc";

    $out[] = [
      "id" => (int)$row['Id_Clientes'],
      "text" => $label
    ];
  }

  echo json_encode(["ok"=>true, "data"=>$out], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e){
  echo json_encode(["ok"=>false, "msg"=>"Error: ".$e->getMessage()], JSON_UNESCAPED_UNICODE);
}
