unit uEnviosTransaherClient;

{
  uEnviosTransaherClient.pas
  Implementación Transaher Smart Logistics del cliente de envíos genérico.

  Descripción:
    Implementa la integración Web Service con Transaher según la especificación
    técnica oficial (Integración Web Service):
      1. Alta de expedición:
         Endpoint: awsprcsatsoap.aspx (SOAP 1.1)
         Operación: wsPrcSATSOAP.Execute (Ediprocod=20)
      2. Anulación / Baja de expedición:
         Endpoint: awsexpbaja.aspx (SOAP 1.1)
         Operación: wsExpBaja.Execute
      3. Consulta de estados / Tracking:
         Token: wsgetToken.svc (SOAP 1.1)
         Información: wsInformacionTransporte.svc (SOAP 1.1)
      4. Etiquetado oficial:
         Código de barras Code 128 de 24 caracteres:
           - 5 dígitos fijos: 10 + Expctrcod (3 dígitos centro origen, ej. 10451)
           - 9 dígitos: Nº expedición con ceros a la izquierda
           - 3 dígitos: Bulto parcial (001, 002...)
           - 5 dígitos: Código postal destino (si Portugal, 4 dígitos + 9)
           - 2 dígitos fijos: 01
}

interface

uses
  System.SysUtils, System.Classes, System.Net.HttpClient, System.Net.URLClient,
  System.NetEncoding, uEnviosTypes;

type
  // Información de retorno detallada de una expedición Transaher
  TTransaherExpedicionInfo = record
    CodExpedicion     : string;
    Holding           : string;
    Seccion           : string;
    Centro            : string;
    FechaExpedicion   : string;
    AreaDisCod        : string;
    AreaDisDsc        : string;
    CentroDestino     : string;
    AreaDestino       : string;
    TrackingNumber    : string;
    NombreDestinatario: string;
    DirDestinatario   : string;
    CPDestinatario    : string;
    PobDestinatario   : string;
    Bultos            : Integer;
    Peso              : Double;
    Observaciones     : string;
    AlbaranOrdenante  : string;
    AlbaranRemitente  : string;
    CentroEditor      : string;
    NumeroRecogida    : string;
    Incoterm          : string;
  end;

  TTransaherEnviosClient = class
  private
    FConfig          : TEnviosConfig;
    FURLBase         : string; // Para awsprcsatsoap.aspx y awsexpbaja.aspx
    FURLBridge       : string; // Para wsgetToken.svc y wsInformacionTransporte.svc
    FToken           : string;
    FTokenTime       : TDateTime;
    FLastExpInfo     : TTransaherExpedicionInfo;
    FCachedLabelRef  : string;
    FCachedLabelBytes: TBytes;
    FLastRequestXML  : string;
    FLastResponseXML : string;

    function PostSOAP(const AURL, AAction, ABody: string): string;
    function ExtractNode(const AXML, ANodeName: string): string;
    function XmlEscape(const AText: string): string;
    function CleanXmlString(const AXML: string): string;
    function CleanPipe(const AText: string): string;
    function GetAuthToken(out AError: string): string;
    function DescargarEtiquetasWS(const ACodExpedicion, AHolding, ASeccion, ACentro: string;
      out AError: string): TBytes;
    function BuildBarcode24(const ACentroOrigen, ACodExpedicion: string;
      ABultoIndex: Integer; const ACP: string): string;
    function ParseTransaherDate(const ADateStr: string): TDateTime;
    function MapTransaherSituacionToGeneric(const ASituacion: string): Integer;
    function GenerarEtiquetaFastReport(const AInfo: TTransaherExpedicionInfo;
      ABultoNum: Integer; const ABarcode24: string): TBytes;
    function GenerarEtiquetaZPL(const AInfo: TTransaherExpedicionInfo;
      ABultoNum: Integer; const ABarcode24: string): string;
    function ConvertirZplAPdf(const AZplBytes: TBytes): TBytes;
    procedure CargarExpedicionDesdeBD(const ACodExp: string);
  public
    constructor Create(const AConfig: TEnviosConfig);
    destructor Destroy; override;

    function Login: Boolean;
    function GrabaEnvio(const AParams: TEnvioParams): TEnvioResult;
    function GrabaRecogida(const AParams: TRecogidaParams): TRecogidaResult;
    function GetEtiqueta(const ARef: string; APDF: Boolean = True): TBytes;
    function GetEstados(const ARef: string): TArray<TEstadoEnvio>;
    function AnulaEnvio(const ARef: string; out AMsg: string): Boolean;
    function ImprimirEtiquetaTermica(const ARef: string; const AImpresora: string;
      out AError: string; AGirar180: Boolean; AHorizontal: Boolean): Boolean; overload;
    function ImprimirEtiquetaTermica(const ARef: string; const AImpresora: string;
      out AError: string; AGirar180: Boolean): Boolean; overload;
    function ImprimirEtiquetaTermica(const ARef: string; const AImpresora: string;
      out AError: string): Boolean; overload;
    function ImprimirEtiquetaTermica(const ARef: string; out AError: string): Boolean; overload;

    class function GetAppLogDir: string; static;
    class function GetLogFilePath: string; static;
    class procedure AbrirArchivoLog; static;
    class procedure AbrirCarpetaLogs; static;
    class procedure LogSOAPTraffic(const AOperacion, AURL, AAction,
      ARequestBody, AResponseBody, AError: string); static;
    class procedure AppendTextToFile(const AFilePath, AText: string); static;
    class procedure SaveRawStringToFile(const AFilePath, AText: string); static;

    property LastExpInfo: TTransaherExpedicionInfo read FLastExpInfo;
    property LastRequestXML: string read FLastRequestXML;
    property LastResponseXML: string read FLastResponseXML;
  end;

implementation

uses
  Winapi.Windows, Winapi.ShellAPI, System.IOUtils, System.DateUtils, System.NetConsts,
  System.RegularExpressions, Data.DB, FireDAC.Stan.Param, FireDAC.Comp.Client,
  frxClass, frxExportPDF, frxBarcode, uPdfRotateService, dmg_Main;

const
  NS_SOAPENV = 'http://schemas.xmlsoap.org/soap/envelope/';

// ---------------------------------------------------------------------------
constructor TTransaherEnviosClient.Create(const AConfig: TEnviosConfig);
var
  LBaseURL, LBridgeURL: string;
begin
  inherited Create;
  FConfig := AConfig;

  if AConfig.Entorno then
  begin
    LBaseURL   := Trim(AConfig.UrlPruebas);
    if LBaseURL = '' then
      LBaseURL := 'https://clientes.transaher.es/mclient_test';
    LBridgeURL := 'https://clientes.transaher.es/mbridge_test';
  end
  else
  begin
    LBaseURL   := Trim(AConfig.UrlProduccion);
    if LBaseURL = '' then
      LBaseURL := 'https://clientes.transaher.es/mclient';
    LBridgeURL := 'https://clientes.transaher.es/mbridge';
  end;

  if LBaseURL.EndsWith('/') then
    Delete(LBaseURL, Length(LBaseURL), 1);
  if LBridgeURL.EndsWith('/') then
    Delete(LBridgeURL, Length(LBridgeURL), 1);

  FURLBase   := LBaseURL;
  FURLBridge := LBridgeURL;
  FToken     := '';
  FTokenTime := 0;
  FCachedLabelRef := '';
  SetLength(FCachedLabelBytes, 0);
end;

destructor TTransaherEnviosClient.Destroy;
begin
  inherited;
end;

// ---------------------------------------------------------------------------
function TTransaherEnviosClient.XmlEscape(const AText: string): string;
begin
  Result := AText
    .Replace('&',  '&amp;',  [rfReplaceAll])
    .Replace('<',  '&lt;',   [rfReplaceAll])
    .Replace('>',  '&gt;',   [rfReplaceAll])
    .Replace('"',  '&quot;', [rfReplaceAll])
    .Replace('''', '&apos;', [rfReplaceAll]);
end;

// ---------------------------------------------------------------------------
function TTransaherEnviosClient.CleanXmlString(const AXML: string): string;
begin
  Result := AXML
    .Replace('&lt;',   '<', [rfReplaceAll])
    .Replace('&gt;',   '>', [rfReplaceAll])
    .Replace('&quot;', '"', [rfReplaceAll])
    .Replace('&amp;',  '&', [rfReplaceAll])
    .Replace('&apos;', '''', [rfReplaceAll]);
end;

// ---------------------------------------------------------------------------
function TTransaherEnviosClient.ExtractNode(const AXML, ANodeName: string): string;
var
  LOpenTagWithPrefix, LOpenTagShort: string;
  LPosOpen, LStart, LPosClose, LEndTag: Integer;
  LXMLUpper, LNodeUpper, LCloseContent: string;
begin
  Result := '';
  if (AXML = '') or (ANodeName = '') then Exit;

  LXMLUpper  := UpperCase(AXML);
  LNodeUpper := UpperCase(ANodeName);

  // 1. Apertura: busca con prefijo ':NODO>' o con atributos ':NODO '
  LOpenTagWithPrefix := ':' + LNodeUpper + '>';
  LPosOpen := Pos(LOpenTagWithPrefix, LXMLUpper);
  if LPosOpen > 0 then
    LStart := LPosOpen + Length(LOpenTagWithPrefix)
  else
  begin
    LOpenTagWithPrefix := ':' + LNodeUpper + ' ';
    LPosOpen := Pos(LOpenTagWithPrefix, LXMLUpper);
    if LPosOpen > 0 then
    begin
      LStart := Pos('>', LXMLUpper, LPosOpen);
      if LStart > 0 then Inc(LStart) else Exit;
    end
    else
    begin
      // Apertura sin prefijo: '<NODO>' o '<NODO '
      LOpenTagShort := '<' + LNodeUpper + '>';
      LPosOpen := Pos(LOpenTagShort, LXMLUpper);
      if LPosOpen > 0 then
        LStart := LPosOpen + Length(LOpenTagShort)
      else
      begin
        LOpenTagShort := '<' + LNodeUpper + ' ';
        LPosOpen := Pos(LOpenTagShort, LXMLUpper);
        if LPosOpen > 0 then
        begin
          LStart := Pos('>', LXMLUpper, LPosOpen);
          if LStart > 0 then Inc(LStart) else Exit;
        end
        else
          Exit;
      end;
    end;
  end;

  // 2. Cierre: busca '</' y verifica que la etiqueta de cierre corresponda al nodo (ej. '</a:NODO>' o '</NODO>')
  LPosClose := Pos('</', LXMLUpper, LStart);
  while LPosClose > 0 do
  begin
    LEndTag := Pos('>', LXMLUpper, LPosClose);
    if LEndTag > LPosClose then
    begin
      LCloseContent := Copy(LXMLUpper, LPosClose + 2, LEndTag - (LPosClose + 2));
      if (LCloseContent = LNodeUpper) or LCloseContent.EndsWith(':' + LNodeUpper) then
      begin
        Result := Copy(AXML, LStart, LPosClose - LStart);
        Exit;
      end;
    end;
    LPosClose := Pos('</', LXMLUpper, LPosClose + 2);
  end;
end;

// ---------------------------------------------------------------------------
function TTransaherEnviosClient.CleanPipe(const AText: string): string;
begin
  Result := StringReplace(Trim(AText), '|', ' ', [rfReplaceAll]);
end;

// ---------------------------------------------------------------------------
class function TTransaherEnviosClient.GetAppLogDir: string;
var
  LAppDir: string;
begin
  LAppDir := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0)));
  Result := LAppDir + 'logs';
  if not DirectoryExists(Result) then
    ForceDirectories(Result);
end;

// ---------------------------------------------------------------------------
class function TTransaherEnviosClient.GetLogFilePath: string;
begin
  Result := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'transaher_ws.log';
end;

// ---------------------------------------------------------------------------
class procedure TTransaherEnviosClient.AbrirArchivoLog;
var
  LFile: string;
begin
  LFile := GetLogFilePath;
  if not FileExists(LFile) then
    LFile := IncludeTrailingPathDelimiter(GetAppLogDir) + 'transaher_' + FormatDateTime('yyyy-mm-dd', Now) + '.log';

  if FileExists(LFile) then
    ShellExecute(0, 'open', PChar(LFile), nil, nil, SW_SHOWNORMAL)
  else
    AbrirCarpetaLogs;
end;

// ---------------------------------------------------------------------------
class procedure TTransaherEnviosClient.AbrirCarpetaLogs;
var
  LDir: string;
begin
  LDir := GetAppLogDir;
  ShellExecute(0, 'open', PChar(LDir), nil, nil, SW_SHOWNORMAL);
end;

// ---------------------------------------------------------------------------
class procedure TTransaherEnviosClient.AppendTextToFile(const AFilePath, AText: string);
var
  LStream: TFileStream;
  LBytes: TBytes;
begin
  try
    if not FileExists(AFilePath) then
    begin
      LStream := TFileStream.Create(AFilePath, fmCreate or fmShareDenyNone);
      try
        LBytes := TEncoding.UTF8.GetPreamble;
        if Length(LBytes) > 0 then
          LStream.WriteBuffer(LBytes[0], Length(LBytes));
        LBytes := TEncoding.UTF8.GetBytes(AText);
        if Length(LBytes) > 0 then
          LStream.WriteBuffer(LBytes[0], Length(LBytes));
      finally
        LStream.Free;
      end;
    end
    else
    begin
      LStream := TFileStream.Create(AFilePath, fmOpenWrite or fmShareDenyNone);
      try
        LStream.Seek(0, soEnd);
        LBytes := TEncoding.UTF8.GetBytes(AText);
        if Length(LBytes) > 0 then
          LStream.WriteBuffer(LBytes[0], Length(LBytes));
      finally
        LStream.Free;
      end;
    end;
  except
  end;
end;

// ---------------------------------------------------------------------------
class procedure TTransaherEnviosClient.SaveRawStringToFile(const AFilePath, AText: string);
var
  LStream: TFileStream;
  LBytes: TBytes;
begin
  try
    LStream := TFileStream.Create(AFilePath, fmCreate or fmShareDenyNone);
    try
      LBytes := TEncoding.UTF8.GetPreamble;
      if Length(LBytes) > 0 then
        LStream.WriteBuffer(LBytes[0], Length(LBytes));
      LBytes := TEncoding.UTF8.GetBytes(AText);
      if Length(LBytes) > 0 then
        LStream.WriteBuffer(LBytes[0], Length(LBytes));
    finally
      LStream.Free;
    end;
  except
  end;
end;

// ---------------------------------------------------------------------------
class procedure TTransaherEnviosClient.LogSOAPTraffic(const AOperacion, AURL, AAction,
  ARequestBody, AResponseBody, AError: string);
var
  LLogDir, LDailyLogPath, LMainLogPath: string;
  LEntry: TStringList;
  LOperName: string;
begin
  try
    LLogDir := GetAppLogDir;
    LDailyLogPath := IncludeTrailingPathDelimiter(LLogDir) + 'transaher_' + FormatDateTime('yyyy-mm-dd', Now) + '.log';
    LMainLogPath := GetLogFilePath;

    if Pos('AWSPRCSATSOAP', UpperCase(AAction + ' ' + AURL)) > 0 then
      LOperName := 'SOLICITUD DE RECOGIDA / ENVÍO (awsprcsatsoap.aspx)'
    else if Pos('WSETIEXP', UpperCase(AAction + ' ' + AURL)) > 0 then
      LOperName := 'PETICIÓN DE ETIQUETA (wsetiexpsoap.svc)'
    else if Pos('WSGETTOKEN', UpperCase(AAction + ' ' + AURL)) > 0 then
      LOperName := 'PETICIÓN DE TOKEN DE AUTENTICACIÓN (wsgetToken.svc)'
    else if Pos('AWSEXPBAJA', UpperCase(AAction + ' ' + AURL)) > 0 then
      LOperName := 'ANULACIÓN / BAJA DE EXPEDICIÓN (awsexpbaja.aspx)'
    else if Pos('WSINFORMACIONTRANSPORTE', UpperCase(AAction + ' ' + AURL)) > 0 then
      LOperName := 'CONSULTA DE ESTADOS / SEGUIMIENTO (wsInformacionTransporte.svc)'
    else
      LOperName := AOperacion;

    LEntry := TStringList.Create;
    try
      LEntry.Add('================================================================================');
      LEntry.Add('FECHA / HORA : ' + FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', Now));
      LEntry.Add('OPERACIÓN    : ' + LOperName);
      LEntry.Add('URL          : ' + AURL);
      LEntry.Add('SOAPACTION   : ' + AAction);
      if Trim(AError) <> '' then
        LEntry.Add('ESTADO       : [ERROR] ' + AError)
      else
        LEntry.Add('ESTADO       : [CORRECTO]');
      LEntry.Add('--------------------------------------------------------------------------------');
      LEntry.Add('>>> TRAMA ENVIADA (SOAP REQUEST XML) >>>');
      LEntry.Add(Trim(ARequestBody));
      LEntry.Add('--------------------------------------------------------------------------------');
      LEntry.Add('<<< TRAMA RECIBIDA (SOAP RESPONSE XML) <<<');
      if Trim(AResponseBody) <> '' then
        LEntry.Add(Trim(AResponseBody))
      else
        LEntry.Add('(Sin respuesta recibida)');
      LEntry.Add('================================================================================');
      LEntry.Add('');

      // 1. Guardar en log diario dentro de logs/
      AppendTextToFile(LDailyLogPath, LEntry.Text);

      // 2. Guardar en log acumulativo transaher_ws.log en la raíz de la aplicación
      AppendTextToFile(LMainLogPath, LEntry.Text);

      // 3. Guardar archivos XML individuales de la última petición para facilitar el envío a soporte técnico
      if Pos('AWSPRCSATSOAP', UpperCase(AAction + ' ' + AURL)) > 0 then
      begin
        SaveRawStringToFile(IncludeTrailingPathDelimiter(LLogDir) + 'transaher_ultimo_envio_request.xml', ARequestBody);
        SaveRawStringToFile(IncludeTrailingPathDelimiter(LLogDir) + 'transaher_ultimo_envio_response.xml', AResponseBody);
      end
      else if Pos('WSETIEXP', UpperCase(AAction + ' ' + AURL)) > 0 then
      begin
        SaveRawStringToFile(IncludeTrailingPathDelimiter(LLogDir) + 'transaher_ultima_etiqueta_request.xml', ARequestBody);
        SaveRawStringToFile(IncludeTrailingPathDelimiter(LLogDir) + 'transaher_ultima_etiqueta_response.xml', AResponseBody);
      end
      else if Pos('WSGETTOKEN', UpperCase(AAction + ' ' + AURL)) > 0 then
      begin
        SaveRawStringToFile(IncludeTrailingPathDelimiter(LLogDir) + 'transaher_ultimo_token_request.xml', ARequestBody);
        SaveRawStringToFile(IncludeTrailingPathDelimiter(LLogDir) + 'transaher_ultimo_token_response.xml', AResponseBody);
      end;
    finally
      LEntry.Free;
    end;
  except
  end;
end;

// ---------------------------------------------------------------------------
function TTransaherEnviosClient.PostSOAP(const AURL, AAction, ABody: string): string;
var
  LClient   : THTTPClient;
  LRequest  : TStringStream;
  LResponse : IHTTPResponse;
  LStatus   : Integer;
  LErrorMsg : string;
begin
  Result := '';
  LErrorMsg := '';
  FLastRequestXML := ABody;
  FLastResponseXML := '';

  LClient := THTTPClient.Create;
  try
    LClient.ConnectionTimeout := 15000;
    LClient.ResponseTimeout   := 30000;
    LClient.CustomHeaders['SOAPAction'] := AAction;
    LClient.ContentType := 'text/xml;charset=utf-8';

    LRequest := TStringStream.Create(ABody, TEncoding.UTF8);
    try
      try
        LResponse := LClient.Post(AURL, LRequest);
        LStatus := LResponse.StatusCode;
        Result := LResponse.ContentAsString(TEncoding.UTF8);
        FLastResponseXML := Result;

        if (LStatus < 200) or (LStatus >= 300) then
        begin
          LErrorMsg := Format('Error HTTP %d (%s)', [LStatus, LResponse.StatusText]);
          LogSOAPTraffic(AAction, AURL, AAction, ABody, Result, LErrorMsg);
          raise Exception.CreateFmt('Error HTTP %d comunicando con Transaher: %s',
            [LStatus, LResponse.StatusText]);
        end;

        LogSOAPTraffic(AAction, AURL, AAction, ABody, Result, '');
      except
        on E: Exception do
        begin
          if LErrorMsg = '' then
            LErrorMsg := E.Message;
          LogSOAPTraffic(AAction, AURL, AAction, ABody, Result, LErrorMsg);
          raise;
        end;
      end;
    finally
      LRequest.Free;
    end;
  finally
    LClient.Free;
  end;
end;

// ---------------------------------------------------------------------------
function TTransaherEnviosClient.GetAuthToken(out AError: string): string;
var
  LURL, LBody, LResponse: string;
  LErrCode, LErrDesc, LToken: string;
begin
  AError := '';
  // Reutilizar token si se obtuvo hace menos de 18 minutos (caduca a los 20 min)
  if (FToken <> '') and (MinutesBetween(Now, FTokenTime) < 18) then
  begin
    Result := FToken;
    Exit;
  end;

  LURL := FURLBridge + '/wsgetToken.svc';
  LBody :=
    '<?xml version="1.0" encoding="utf-8"?>' +
    '<soapenv:Envelope xmlns:soapenv="' + NS_SOAPENV + '" xmlns:wsg="MWSBridge.wsgettoken_services">' +
    '<soapenv:Header/>' +
    '<soapenv:Body>' +
    '  <wsg:execute>' +
    '    <wsg:CodigoHolding>0</wsg:CodigoHolding>' +
    '    <wsg:CodigoCliente>' + XmlEscape(Trim(FConfig.CodCliente)) + '</wsg:CodigoCliente>' +
    '    <wsg:PasswordCliente>' + XmlEscape(Trim(FConfig.Password)) + '</wsg:PasswordCliente>' +
    '  </wsg:execute>' +
    '</soapenv:Body>' +
    '</soapenv:Envelope>';

  try
    LResponse := PostSOAP(LURL, 'MWSBridge.wsgettoken_services/wsgettoken_services/execute', LBody);
  except
    on E: Exception do
    begin
      AError := 'Error al contactar wsgetToken de Transaher: ' + E.Message;
      Result := '';
      Exit;
    end;
  end;

  LErrCode := ExtractNode(LResponse, 'errCode');
  LErrDesc := ExtractNode(LResponse, 'errDesc');
  LToken   := ExtractNode(LResponse, 'Token');

  if (LErrCode <> '') and (LErrCode <> '0') then
  begin
    AError := Format('Transaher wsgetToken devolvió error %s: %s', [LErrCode, LErrDesc]);
    Result := '';
    Exit;
  end;

  if LToken = '' then
  begin
    AError := 'No se recibió token de autenticación de Transaher.';
    Result := '';
    Exit;
  end;

  FToken := LToken;
  FTokenTime := Now;
  Result := FToken;
end;

// ---------------------------------------------------------------------------
function TTransaherEnviosClient.Login: Boolean;
var
  LError: string;
  LToken: string;
begin
  // Validamos credenciales llamando al servicio de autenticación wsgetToken
  LToken := GetAuthToken(LError);
  Result := (LToken <> '') and (LError = '');
end;

// ---------------------------------------------------------------------------
function TTransaherEnviosClient.BuildBarcode24(const ACentroOrigen, ACodExpedicion: string;
  ABultoIndex: Integer; const ACP: string): string;
var
  LFixedPrefix : string;
  LExpedicionStr: string;
  LBultoStr    : string;
  LCPStr       : string;
  LCleanCP     : string;
  LCtrNum      : Integer;
begin
  // 1. Primeros 5 caracteres: '10' + 3 dígitos centro origen (ej: '10451')
  if TryStrToInt(Trim(ACentroOrigen), LCtrNum) then
    LFixedPrefix := '10' + Format('%.3d', [LCtrNum])
  else
    LFixedPrefix := '10451';

  // 2. 9 dígitos: expedición completada con ceros a la izquierda
  LExpedicionStr := StringReplace(Trim(ACodExpedicion), ' ', '', [rfReplaceAll]);
  if Length(LExpedicionStr) < 9 then
    LExpedicionStr := StringOfChar('0', 9 - Length(LExpedicionStr)) + LExpedicionStr
  else if Length(LExpedicionStr) > 9 then
    LExpedicionStr := Copy(LExpedicionStr, Length(LExpedicionStr) - 8, 9);

  // 3. 3 dígitos: número de bulto relativo (001, 002...)
  if ABultoIndex < 1 then ABultoIndex := 1;
  LBultoStr := Format('%.3d', [ABultoIndex]);

  // 4. 5 dígitos para código postal:
  // Si es Portugal (4 dígitos o contiene '-'), se utiliza los 4 primeros + '9'
  LCleanCP := StringReplace(Trim(ACP), ' ', '', [rfReplaceAll]);
  LCleanCP := StringReplace(LCleanCP, '-', '', [rfReplaceAll]);
  if Length(LCleanCP) = 4 then
    LCPStr := LCleanCP + '9'
  else if Length(LCleanCP) >= 5 then
    LCPStr := Copy(LCleanCP, 1, 5)
  else
    LCPStr := Copy(LCleanCP + '00000', 1, 5);

  // 5. 2 dígitos fijos finales: '01'
  Result := LFixedPrefix + LExpedicionStr + LBultoStr + LCPStr + '01';
end;

// ---------------------------------------------------------------------------
function TTransaherEnviosClient.ParseTransaherDate(const ADateStr: string): TDateTime;
var
  LParts: TArray<string>;
  LDay, LMonth, LYear: Integer;
begin
  Result := 0;
  LParts := ADateStr.Split(['/']);
  if Length(LParts) = 3 then
  begin
    if TryStrToInt(LParts[0], LDay) and
       TryStrToInt(LParts[1], LMonth) and
       TryStrToInt(LParts[2], LYear) then
    begin
      if LYear < 100 then Inc(LYear, 2000);
      try
        Result := EncodeDate(LYear, LMonth, LDay);
      except
        Result := 0;
      end;
    end;
  end;
end;

// ---------------------------------------------------------------------------
function TTransaherEnviosClient.MapTransaherSituacionToGeneric(const ASituacion: string): Integer;
var
  LUpper: string;
begin
  LUpper := UpperCase(Trim(ASituacion));
  if Pos('ENTREG', LUpper) > 0 then Result := ENV_EST_ENTREGADO
  else if Pos('REPARTO', LUpper) > 0 then Result := ENV_EST_REPARTO
  else if Pos('TRANSITO', LUpper) > 0 then Result := ENV_EST_TRANSITO
  else if Pos('DESTINO', LUpper) > 0 then Result := ENV_EST_TRANSITO
  else if Pos('ORIGEN', LUpper) > 0 then Result := ENV_EST_TRANSITO
  else if Pos('RECEPCION', LUpper) > 0 then Result := ENV_EST_DOCUMENTADO
  else if Pos('DOCUMENT', LUpper) > 0 then Result := ENV_EST_DOCUMENTADO
  else if Pos('ETIQUET', LUpper) > 0 then Result := ENV_EST_DOCUMENTADO
  else if Pos('INCIDEN', LUpper) > 0 then Result := ENV_EST_INCIDENCIA
  else if Pos('DEVUEL', LUpper) > 0 then Result := ENV_EST_DEVUELTO
  else if Pos('ANULA', LUpper) > 0 then Result := ENV_EST_DEVUELTO
  else Result := ENV_EST_TRANSITO;
end;

// ---------------------------------------------------------------------------
function TTransaherEnviosClient.GrabaEnvio(const AParams: TEnvioParams): TEnvioResult;
var
  LURL, LBody, LResponse: string;
  LDatosEntrada: string;
  LCodPais: string;
  LPesoStr: string;
  LFormatSettings: TFormatSettings;
  LRespuestaRaw, LCleanXML: string;
  LErrCod, LErrDsc: string;
  LObs1, LObs2: string;
  LNumCliente: string;
  LNumBultos: Integer;
begin
  Result := Default(TEnvioResult);
  Result.OK := False;

  LNumCliente := Trim(FConfig.CodCliente);
  if LNumCliente = '' then
  begin
    Result.Error := 'El código de cliente de Transaher no está configurado.';
    Exit;
  end;

  // Código de país Transaher: 011 = España, 010 = Portugal
  if (AParams.CodPais = 'PT') or (AParams.CodPais = '010') then
    LCodPais := '010'
  else
    LCodPais := '011';

  LNumBultos := AParams.NumBultos;
  if LNumBultos < 1 then LNumBultos := 1;

  LFormatSettings := TFormatSettings.Create;
  LFormatSettings.DecimalSeparator := ','; // Transaher doc pág 2: Formato 12345,123
  if AParams.Peso <= 0 then
    LPesoStr := '1,00'
  else
    LPesoStr := FormatFloat('0.00', AParams.Peso, LFormatSettings);

  LObs1 := Copy(Trim(AParams.Observaciones), 1, 70);
  LObs2 := '';
  if Length(Trim(AParams.Observaciones)) > 70 then
    LObs2 := Copy(Trim(AParams.Observaciones), 71, 70);

  // Construir registro de 18 campos delimitados por '|' según especificación oficial:
  // 1: NOMBRE DESTINATARIO (max 40)
  // 2: DIRECCIÓN DESTINATARIO (max 50)
  // 3: CÓDIGO PAÍS (011 España / 010 Portugal)
  // 4: CÓDIGO POSTAL POBLACIÓN (max 5)
  // 5: CÓDIGO REPETICIÓN POSTAL (vacío)
  // 6: NOMBRE POBLACIÓN DESTINATARIO (max 45)
  // 7: REFERENCIA INTERNA / Nº ALBARÁN (max 20)
  // 8: TIPO PORTES (1 Pagados / 2 Debidos)
  // 9: OBSERVACIONES 1 (max 70)
  // 10: OBSERVACIONES 2 (max 70)
  // 11: NÚMERO DE BULTOS (max 4)
  // 12: PESO EN KILOS (max 8)
  // 13: VOLUMEN (opcional)
  // 14: VALOR ASEGURADO (opcional)
  // 15: VALOR REEMBOLSO (opcional)
  // 16: EMAIL DESTINATARIO (max 50)
  // 17: TELÉFONO DESTINATARIO (max 15)
  // 18: REFERENCIA REMITENTE (max 20)
  var LProtocolo: string := Trim(FConfig.CodAgencia);
  if LProtocolo = '' then LProtocolo := '15'; // Protocolo 15 asignado por Transaher en datos de acceso

  LDatosEntrada :=
    Copy(CleanPipe(AParams.NomDes), 1, 40) + '|' +
    Copy(CleanPipe(AParams.DirDes), 1, 50) + '|' +
    LCodPais + '|' +
    Copy(CleanPipe(AParams.CPDes), 1, 5) + '|' +
    '|' + // Repetición postal
    Copy(CleanPipe(AParams.PobDes), 1, 45) + '|' +
    Copy(CleanPipe(AParams.Referencia), 1, 20) + '|' +
    '1|' + // 1 = Pagados
    CleanPipe(LObs1) + '|' +
    CleanPipe(LObs2) + '|' +
    IntToStr(LNumBultos) + '|' +
    LPesoStr + '|' +
    '|' + // Volumen
    '|' + // Asegurado
    '|' + // Reembolso
    Copy(CleanPipe(AParams.EmailDes), 1, 50) + '|' +
    Copy(CleanPipe(AParams.TlfDes), 1, 15) + '|' +
    Copy(CleanPipe(AParams.Referencia), 1, 20);

  LURL := FURLBase + '/awsprcsatsoap.aspx';
  LBody :=
    '<?xml version="1.0" encoding="utf-8"?>' +
    '<soapenv:Envelope xmlns:soapenv="' + NS_SOAPENV + '" xmlns:mtr="MTRANS_WEB">' +
    '<soapenv:Header/>' +
    '<soapenv:Body>' +
    '  <mtr:wsPrcSATSOAP.Execute>' +
    '    <mtr:Clicod>' + XmlEscape(LNumCliente) + '</mtr:Clicod>' +
    '    <mtr:Clipsw>' + XmlEscape(Trim(FConfig.Password)) + '</mtr:Clipsw>' +
    '    <mtr:Ediprocod>' + XmlEscape(LProtocolo) + '</mtr:Ediprocod>' +
    '    <mtr:Datosentrada>' + XmlEscape(LDatosEntrada) + '</mtr:Datosentrada>' +
    '  </mtr:wsPrcSATSOAP.Execute>' +
    '</soapenv:Body>' +
    '</soapenv:Envelope>';

  try
    LResponse := PostSOAP(LURL, 'MTRANS_WEBaction/AWSPRCSATSOAP.Execute', LBody);
  except
    on E: Exception do
    begin
      Result.Error := 'Error al comunicarse con Transaher (alta): ' + E.Message;
      Exit;
    end;
  end;

  LRespuestaRaw := ExtractNode(LResponse, 'Respuesta');
  LCleanXML := CleanXmlString(LRespuestaRaw);

  LErrCod := ExtractNode(LCleanXML, 'ErrCod');
  LErrDsc := ExtractNode(LCleanXML, 'ErrDsc');

  if (LErrCod <> '') and (LErrCod <> '0') then
  begin
    // Si Transaher avisa de que ya existe una expedición para esta orden/referencia,
    // recuperar el número de expedición existente y considerarlo alta satisfactoria
    // Ejemplo: "AVISO(14):[613.190] Ya existe Expedición 8661169 con Ref.Ord.: 613.190"
    if (Pos('Ya existe Expedici', LErrDsc) > 0) or (Pos('Ya existe', LErrDsc) > 0) then
    begin
      var LMatchExp := TRegEx.Match(LErrDsc, 'Expedici[oó]n\s+(\d+)', [roIgnoreCase]);
      if LMatchExp.Success then
      begin
        FLastExpInfo.CodExpedicion      := LMatchExp.Groups[1].Value;
        FLastExpInfo.Holding            := '0';
        FLastExpInfo.Seccion            := '10';
        FLastExpInfo.Centro             := '31';
        FLastExpInfo.FechaExpedicion    := FormatDateTime('yyyy-mm-dd', Now);
        FLastExpInfo.AreaDisCod         := '';
        FLastExpInfo.AreaDisDsc         := '';
        FLastExpInfo.CentroDestino      := '';
        FLastExpInfo.AreaDestino        := '';
        FLastExpInfo.TrackingNumber     := FLastExpInfo.CodExpedicion;
        FLastExpInfo.NombreDestinatario := AParams.NomDes;
        FLastExpInfo.DirDestinatario    := AParams.DirDes;
        FLastExpInfo.CPDestinatario     := AParams.CPDes;
        FLastExpInfo.PobDestinatario    := AParams.PobDes;
        FLastExpInfo.Bultos             := LNumBultos;
        FLastExpInfo.Peso               := AParams.Peso;
        FLastExpInfo.Observaciones      := AParams.Observaciones;
        FLastExpInfo.AlbaranOrdenante   := AParams.Referencia;
        FLastExpInfo.AlbaranRemitente   := AParams.Referencia;

        Result.OK                   := True;
        Result.AlbaranTransportista := FLastExpInfo.CodExpedicion;
        Result.GuidTransportista    := Format('%s/%s/%s/%s', [
          FLastExpInfo.Holding, FLastExpInfo.Seccion, FLastExpInfo.Centro, FLastExpInfo.CodExpedicion]);
        Result.CodAgeDestino        := FLastExpInfo.Centro;
        Result.FechaEntrega         := Now;
        Result.TipoEnvio            := 'ESTANDAR';

        FCachedLabelRef := Result.AlbaranTransportista;
        SetLength(FCachedLabelBytes, 0);
        Exit;
      end;
    end;

    Result.Error := Format('Transaher devolvió error %s: %s', [LErrCod, LErrDsc]);
    Exit;
  end;

  // Extraer datos de la expedición creada
  FLastExpInfo.CodExpedicion      := ExtractNode(LCleanXML, 'CodExpedicion');
  FLastExpInfo.Holding            := ExtractNode(LCleanXML, 'Holding');
  FLastExpInfo.Seccion            := ExtractNode(LCleanXML, 'Seccion');
  FLastExpInfo.Centro             := ExtractNode(LCleanXML, 'Centro');
  FLastExpInfo.FechaExpedicion    := ExtractNode(LCleanXML, 'Fecha_Expedicion');
  FLastExpInfo.AreaDisCod         := ExtractNode(LCleanXML, 'Area_Dis_Cod');
  FLastExpInfo.AreaDisDsc         := ExtractNode(LCleanXML, 'Area_Dis_Dsc');
  FLastExpInfo.CentroDestino      := ExtractNode(LCleanXML, 'Centro_Destino');
  FLastExpInfo.AreaDestino        := ExtractNode(LCleanXML, 'Area_Destino');
  FLastExpInfo.TrackingNumber     := ExtractNode(LCleanXML, 'TrackingNumber');
  FLastExpInfo.CentroEditor       := ExtractNode(LCleanXML, 'Centro_Editor');
  FLastExpInfo.NumeroRecogida     := ExtractNode(LCleanXML, 'Numero_Recogida');
  FLastExpInfo.Incoterm           := ExtractNode(LCleanXML, 'Descripcion_Incoterm');
  FLastExpInfo.NombreDestinatario := AParams.NomDes;
  FLastExpInfo.DirDestinatario    := AParams.DirDes;
  FLastExpInfo.CPDestinatario     := AParams.CPDes;
  FLastExpInfo.PobDestinatario    := AParams.PobDes;
  FLastExpInfo.Bultos             := LNumBultos;
  FLastExpInfo.Peso               := AParams.Peso;
  FLastExpInfo.Observaciones      := AParams.Observaciones;
  FLastExpInfo.AlbaranOrdenante   := AParams.Referencia;
  FLastExpInfo.AlbaranRemitente   := AParams.Referencia;

  if FLastExpInfo.CodExpedicion = '' then
  begin
    Result.Error := 'No se recibió número de expedición de Transaher: ' + LCleanXML;
    Exit;
  end;

  Result.OK                  := True;
  Result.AlbaranTransportista := FLastExpInfo.CodExpedicion;
  Result.GuidTransportista   := Format('%s/%s/%s/%s', [
    FLastExpInfo.Holding, FLastExpInfo.Seccion, FLastExpInfo.Centro, FLastExpInfo.CodExpedicion]);
  Result.CodAgeDestino       := FLastExpInfo.CentroDestino;
  Result.FechaEntrega        := ParseTransaherDate(FLastExpInfo.FechaExpedicion);
  Result.TipoEnvio           := 'ESTANDAR';

  FCachedLabelRef := Result.AlbaranTransportista;
  SetLength(FCachedLabelBytes, 0);
end;

// ---------------------------------------------------------------------------
function TTransaherEnviosClient.GrabaRecogida(const AParams: TRecogidaParams): TRecogidaResult;
var
  LEnvioParams: TEnvioParams;
  LEnvioResult: TEnvioResult;
begin
  Result := Default(TRecogidaResult);
  Result.OK := False;

  // En Transaher el alta de expedición cubre tanto entrega como recogida (con portes pagados/debidos)
  LEnvioParams.NomOri        := AParams.NomOri;
  LEnvioParams.DirOri        := AParams.TipoViaOri + ' ' + AParams.DirOri + ' ' + AParams.NumOri;
  LEnvioParams.PobOri        := FConfig.PobRemitente;
  LEnvioParams.CPOri         := AParams.CPOri;
  LEnvioParams.TlfOri        := AParams.TlfOri;
  LEnvioParams.NomDes        := AParams.NomDes;
  LEnvioParams.DirDes        := AParams.TipoViaDes + ' ' + AParams.DirDes + ' ' + AParams.NumDes;
  LEnvioParams.PobDes        := AParams.PobDes;
  LEnvioParams.CPDes         := AParams.CPDes;
  LEnvioParams.TlfDes        := AParams.TlfDes;
  LEnvioParams.CodPais       := 'ES';
  LEnvioParams.CodTipoServ   := AParams.CodTipoServ;
  LEnvioParams.NumBultos     := AParams.NumBultos;
  LEnvioParams.Referencia    := AParams.Referencia;
  LEnvioParams.Observaciones := AParams.Observaciones;
  LEnvioParams.Peso          := 1.0;
  LEnvioParams.EmailDes      := AParams.EmailDes;
  LEnvioParams.MovilDes      := AParams.MovilDes;

  LEnvioResult := GrabaEnvio(LEnvioParams);
  if LEnvioResult.OK then
  begin
    Result.OK                := True;
    Result.CodRecogida       := LEnvioResult.AlbaranTransportista;
    Result.GuidTransportista := LEnvioResult.GuidTransportista;
    Result.FechaAlta         := Now;
    Result.CodAgeOrigen      := FLastExpInfo.Centro;
    Result.CodAgeDestino     := LEnvioResult.CodAgeDestino;
  end
  else
  begin
    Result.OK    := False;
    Result.Error := LEnvioResult.Error;
  end;
end;

// ---------------------------------------------------------------------------
function TTransaherEnviosClient.AnulaEnvio(const ARef: string; out AMsg: string): Boolean;
var
  LURL, LBody, LResponse: string;
  LCodExp: string;
  LExpCtrCod: string;
  LErrCod, LErrDesc: string;
begin
  Result := False;
  AMsg := '';

  LCodExp := Trim(ARef);
  if LCodExp = '' then
  begin
    AMsg := 'El número de expedición a anular está vacío.';
    Exit;
  end;

  LExpCtrCod := Trim(FConfig.CodAgencia);
  if LExpCtrCod = '' then
    LExpCtrCod := '451'; // Centro origen por defecto (Toledo/Madrid)

  LURL := FURLBase + '/awsexpbaja.aspx';
  LBody :=
    '<?xml version="1.0" encoding="utf-8"?>' +
    '<soapenv:Envelope xmlns:soapenv="' + NS_SOAPENV + '" xmlns:mtr="MTRANS_WEB">' +
    '<soapenv:Header/>' +
    '<soapenv:Body>' +
    '  <mtr:wsExpBaja.Execute>' +
    '    <mtr:Clicod>' + XmlEscape(Trim(FConfig.CodCliente)) + '</mtr:Clicod>' +
    '    <mtr:Clipsw>' + XmlEscape(Trim(FConfig.Password)) + '</mtr:Clipsw>' +
    '    <mtr:Holcod>0</mtr:Holcod>' +
    '    <mtr:Seccod>10</mtr:Seccod>' +
    '    <mtr:Expctrcod>' + XmlEscape(LExpCtrCod) + '</mtr:Expctrcod>' +
    '    <mtr:Expcod>' + XmlEscape(LCodExp) + '</mtr:Expcod>' +
    '  </mtr:wsExpBaja.Execute>' +
    '</soapenv:Body>' +
    '</soapenv:Envelope>';

  try
    LResponse := PostSOAP(LURL, 'MTRANS_WEBaction/AWSEXPBAJA.Execute', LBody);
  except
    on E: Exception do
    begin
      AMsg := 'Error al contactar con el servicio de baja de Transaher: ' + E.Message;
      Exit;
    end;
  end;

  LErrCod  := ExtractNode(LResponse, 'Errcod');
  LErrDesc := ExtractNode(LResponse, 'Errdesc');

  if LErrCod = '0' then
  begin
    Result := True;
    AMsg := 'Expedición ' + LCodExp + ' anulada correctamente en Transaher.';
  end
  else
  begin
    case StrToIntDef(LErrCod, -1) of
      1: AMsg := 'Error 1: Expedición inexistente en Transaher.';
      2: AMsg := 'Error 2: Situación de la expedición incorrecta (ya no se puede anular porque ya ha salido a reparto o tránsito).';
      3: AMsg := 'Error 3: Situación web incorrecta.';
    else
      AMsg := Format('Error %s al anular en Transaher: %s', [LErrCod, LErrDesc]);
    end;
  end;
end;

// ---------------------------------------------------------------------------
function TTransaherEnviosClient.GetEstados(const ARef: string): TArray<TEstadoEnvio>;
var
  LToken, LError: string;
  LURL, LBody, LResponse: string;
  LCtrCod: string;
  LSituacion, LTracking, LEvtDesc: string;
  LCount: Integer;
begin
  SetLength(Result, 0);

  LToken := GetAuthToken(LError);
  if LToken = '' then
    raise Exception.Create('Error de autenticación con Transaher: ' + LError);

  LCtrCod := Trim(FConfig.CodAgencia);
  if LCtrCod = '' then LCtrCod := '451';

  LURL := FURLBridge + '/wsInformacionTransporte.svc';
  LBody :=
    '<?xml version="1.0" encoding="utf-8"?>' +
    '<soapenv:Envelope xmlns:soapenv="' + NS_SOAPENV + '" xmlns:wsi="MWSBridge.wsinformaciontransporte_services" xmlns:mws="MWSBridge">' +
    '<soapenv:Header/>' +
    '<soapenv:Body>' +
    '  <wsi:execute>' +
    '    <wsi:Token>' + XmlEscape(LToken) + '</wsi:Token>' +
    '    <wsi:InfoTrnFiltros>' +
    '      <mws:Holding>0</mws:Holding>' +
    '      <mws:Seccion>10</mws:Seccion>' +
    '      <mws:Empresa>1</mws:Empresa>' +
    '      <mws:Centro>' + XmlEscape(LCtrCod) + '</mws:Centro>' +
    '      <mws:NumeroExpedicion>' + XmlEscape(Trim(ARef)) + '</mws:NumeroExpedicion>' +
    '      <mws:Info_Exp>S</mws:Info_Exp>' +
    '      <mws:Info_Ent>S</mws:Info_Ent>' +
    '      <mws:Info_Exp_Evt>S</mws:Info_Exp_Evt>' +
    '    </wsi:InfoTrnFiltros>' +
    '  </wsi:execute>' +
    '</soapenv:Body>' +
    '</soapenv:Envelope>';

  try
    LResponse := PostSOAP(LURL, 'MWSBridge.wsinformaciontransporte_services/wsinformaciontransporte_services/execute', LBody);
  except
    on E: Exception do
      raise Exception.CreateFmt('Error al consultar estados en Transaher: %s', [E.Message]);
  end;

  LSituacion := ExtractNode(LResponse, 'Situacion');
  LTracking  := ExtractNode(LResponse, 'TrackingNumber');
  LEvtDesc   := ExtractNode(LResponse, 'SituacionDescripcion');

  LCount := 0;
  if LSituacion <> '' then
  begin
    SetLength(Result, 1);
    Result[0].IdEstado    := 0;
    Result[0].Codigo      := MapTransaherSituacionToGeneric(LSituacion);
    Result[0].Descripcion := 'Transaher: ' + LSituacion;
    if LEvtDesc <> '' then
      Result[0].Descripcion := Result[0].Descripcion + ' - ' + LEvtDesc;
    Result[0].FechaHora   := Now;
    Result[0].CodUsuario  := LTracking;
    Inc(LCount);
  end;

  if LCount = 0 then
  begin
    // Si la expedición fue documentada recientemente pero no tiene eventos aún
    SetLength(Result, 1);
    Result[0].IdEstado    := 0;
    Result[0].Codigo      := ENV_EST_DOCUMENTADO;
    Result[0].Descripcion := 'Expedición documentada en Transaher (pdte. recogida)';
    Result[0].FechaHora   := Now;
    Result[0].CodUsuario  := ARef;
  end;
end;

// ---------------------------------------------------------------------------
function TTransaherEnviosClient.GenerarEtiquetaZPL(const AInfo: TTransaherExpedicionInfo;
  ABultoNum: Integer; const ABarcode24: string): string;
var
  LTotalBultos: Integer;
  LCentroOriStr, LRecogidaStr, LIncotermStr, LDistStr, LCentroDestStr, LRutaStr, LZRNumStr: string;
begin
  LTotalBultos := AInfo.Bultos;
  if LTotalBultos < 1 then LTotalBultos := 1;

  LCentroOriStr := Trim(AInfo.Centro + ' ' + AInfo.CentroEditor);
  if LCentroOriStr = '' then LCentroOriStr := Trim(FConfig.CodAgencia + ' ' + FConfig.PobRemitente);
  if LCentroOriStr = '' then LCentroOriStr := '31 ALICANTE';

  if (AInfo.NumeroRecogida <> '') and (AInfo.NumeroRecogida <> '0') then
    LRecogidaStr := 'Rec ' + AInfo.NumeroRecogida
  else
    LRecogidaStr := '';

  LIncotermStr := Trim(AInfo.Incoterm);
  if LIncotermStr = '' then LIncotermStr := 'PAGADOS';

  LDistStr := Trim(AInfo.AreaDestino);
  if Pos('(', LDistStr) > 0 then
    LDistStr := Trim(Copy(LDistStr, 1, Pos('(', LDistStr) - 1));
  if LDistStr = '' then LDistStr := 'VALENCIA';

  LCentroDestStr := Trim(AInfo.CentroDestino + ' ' + AInfo.AreaDestino);
  if LCentroDestStr = '' then LCentroDestStr := '461 VALENCIA (TTE';

  LRutaStr := 'IA';
  LZRNumStr := Trim(AInfo.AreaDisCod);
  if LZRNumStr = '' then LZRNumStr := '2019';

  // Formato ZPL estándar 100x150 mm idéntico a la etiqueta oficial Web de Transaher
  Result :=
    '^XA' + sLineBreak +
    '^PW800' + sLineBreak +
    '^LL1200' + sLineBreak +
    '^LH0,0' + sLineBreak +
    // 1. Centro origen y Recogida
    '^FO40,30^A0N,36,36^FD' + LCentroOriStr + '^FS' + sLineBreak +
    '^FO550,34^A0N,28,28^FD' + LRecogidaStr + '^FS' + sLineBreak +
    // 2. Código de barras Code 128
    '^FO50,75^BY3,2,110^BCN,110,Y,N,N^FD' + ABarcode24 + '^FS' + sLineBreak +
    '^FO40,240^GB720,2,2^FS' + sLineBreak +
    // 3. Fecha, Kilos, Bultos
    '^FO40,255^A0N,26,26^FDFecha: ' + FormatDateTime('dd/mm/yy', Now) + '^FS' + sLineBreak +
    '^FO40,290^A0N,26,26^FDKilos: ' + FormatFloat('0.000', AInfo.Peso) + '^FS' + sLineBreak +
    '^FO480,255^A0N,38,38^FDBULTOS:   ' + IntToStr(ABultoNum) + ' / ' + IntToStr(LTotalBultos) + '^FS' + sLineBreak +
    '^FO40,335^GB720,1,1^FS' + sLineBreak +
    // 4. Remitente y Observaciones
    '^FO40,348^A0N,24,24^FDREMITENTE: ' + FConfig.NomRemitente + '^FS' + sLineBreak +
    '^FO40,380^A0N,24,24^FDOBSERVACIONES:^FS' + sLineBreak +
    '^FO40,410^A0N,22,22^FD' + Copy(AInfo.Observaciones, 1, 65) + '^FS' + sLineBreak +
    '^FO40,440^GB720,2,2^FS' + sLineBreak +
    // 5. Pedido / Ref / Portes y Distribución / Expedición
    '^FO40,455^A0N,24,24^FDPEDIDO: ' + AInfo.AlbaranOrdenante + '^FS' + sLineBreak +
    '^FO260,455^A0N,24,24^FDREF.: ' + AInfo.AlbaranRemitente + '^FS' + sLineBreak +
    '^FO550,455^A0N,24,24^FD' + LIncotermStr + '^FS' + sLineBreak +
    '^FO40,490^GB720,1,1^FS' + sLineBreak +
    '^FO40,505^A0N,24,24^FDDistribución: ' + LDistStr + '^FS' + sLineBreak +
    '^FO510,498^A0N,44,44^FD' + AInfo.CodExpedicion + '^FS' + sLineBreak +
    '^FO40,555^GB720,2,2^FS' + sLineBreak +
    // 6. Consignatario
    '^FO40,570^A0N,26,26^FDCONSIGNATARIO: ' + AInfo.NombreDestinatario + '^FS' + sLineBreak +
    '^FO40,605^A0N,26,26^FD' + AInfo.DirDestinatario + '^FS' + sLineBreak +
    '^FO40,640^A0N,36,36^FD' + Trim(AInfo.CPDestinatario + ' - ' + AInfo.PobDestinatario) + '^FS' + sLineBreak +
    '^FO40,685^A0N,26,26^FDZ.R.: ' + Trim(AInfo.AreaDisCod + '  ' + AInfo.AreaDisDsc) + '^FS' + sLineBreak +
    '^FO40,725^GB720,2,2^FS' + sLineBreak +
    // 7. Ruta / Centro / Zona Reparto
    '^FO50,740^A0N,20,20^FDRuta^FS' + sLineBreak +
    '^FO50,770^A0N,38,38^FD' + LRutaStr + '^FS' + sLineBreak +
    '^FO180,760^A0N,38,38^FD' + LCentroDestStr + '^FS' + sLineBreak +
    '^FO560,740^A0N,20,20^FDZona Reparto^FS' + sLineBreak +
    '^FO560,770^A0N,38,38^FD' + LZRNumStr + '^FS' + sLineBreak +
    '^FO40,820^GB720,2,2^FS' + sLineBreak +
    '^XZ' + sLineBreak;
end;

// ---------------------------------------------------------------------------
function TTransaherEnviosClient.GenerarEtiquetaFastReport(const AInfo: TTransaherExpedicionInfo;
  ABultoNum: Integer; const ABarcode24: string): TBytes;
var
  LFrxReport: TfrxReport;
  LPdfExport: TfrxPDFExport;
  LBarcode: TfrxBarCodeView;
  LTemplatePath: string;
  LTempPdf: string;
  LTotalBultos: Integer;
begin
  SetLength(Result, 0);

  LTemplatePath := ExtractFilePath(ParamStr(0)) + 'reportes\EtiquetaTransaher.fr3';
  if not FileExists(LTemplatePath) then
    LTemplatePath := 'c:\fuentes\proyectos delphi\RAUL_ASENCIO\GESTION\reportes\EtiquetaTransaher.fr3';

  if not FileExists(LTemplatePath) then
    Exit;

  LTotalBultos := AInfo.Bultos;
  if LTotalBultos < 1 then LTotalBultos := 1;

  LTempPdf := GetEnvironmentVariable('TEMP') + '\Transaher_' +
              StringReplace(AInfo.CodExpedicion, '/', '_', [rfReplaceAll]) +
              '_' + IntToStr(ABultoNum) + '_' + FormatDateTime('hhnnsszzz', Now) + '.pdf';

  LFrxReport := TfrxReport.Create(nil);
  LPdfExport := TfrxPDFExport.Create(nil);
  try
    LFrxReport.LoadFromFile(LTemplatePath);

    LBarcode := LFrxReport.FindObject('Barcode1') as TfrxBarCodeView;
    if Assigned(LBarcode) then
    begin
      LBarcode.Expression := '';
      LBarcode.Text := ABarcode24;
    end;

    var LCentroOriStr: string := Trim(AInfo.Centro + ' ' + AInfo.CentroEditor);
    if LCentroOriStr = '' then
      LCentroOriStr := Trim(FConfig.CodAgencia + ' ' + FConfig.PobRemitente);
    if LCentroOriStr = '' then
      LCentroOriStr := '31 ALICANTE';

    var LRecogidaStr: string := '';
    if (AInfo.NumeroRecogida <> '') and (AInfo.NumeroRecogida <> '0') then
      LRecogidaStr := 'Rec ' + AInfo.NumeroRecogida
    else
      LRecogidaStr := '';

    var LIncotermStr: string := Trim(AInfo.Incoterm);
    if LIncotermStr = '' then LIncotermStr := 'PAGADOS';

    var LDistStr: string := Trim(AInfo.AreaDestino);
    if Pos('(', LDistStr) > 0 then
      LDistStr := Trim(Copy(LDistStr, 1, Pos('(', LDistStr) - 1));
    if LDistStr = '' then LDistStr := 'VALENCIA';

    var LCentroDestStr: string := Trim(AInfo.CentroDestino + ' ' + AInfo.AreaDestino);
    if LCentroDestStr = '' then LCentroDestStr := '461 VALENCIA (TTE';

    var LRutaStr: string := 'IA';
    var LZRNumStr: string := Trim(AInfo.AreaDisCod);
    if LZRNumStr = '' then LZRNumStr := '2019';

    // Asignar variables al informe FastReport exactamente como en la Web oficial de Transaher
    LFrxReport.Variables['ValCentroOri']    := '''' + LCentroOriStr + '''';
    LFrxReport.Variables['ValRecogida']     := '''' + LRecogidaStr + '''';
    LFrxReport.Variables['ValBarcode24']    := '''' + ABarcode24 + '''';
    LFrxReport.Variables['ValFecha']        := '''' + FormatDateTime('dd/mm/yy', Now) + '''';
    LFrxReport.Variables['ValPeso']         := '''' + FormatFloat('0.000', AInfo.Peso) + '''';
    LFrxReport.Variables['ValBultos']       := '''' + IntToStr(ABultoNum) + ' / ' + IntToStr(LTotalBultos) + '''';
    LFrxReport.Variables['ValRemName']      := '''' + FConfig.NomRemitente + '''';
    LFrxReport.Variables['ValObs']          := '''' + AInfo.Observaciones + '''';
    LFrxReport.Variables['ValPedido']       := '''' + AInfo.AlbaranOrdenante + '''';
    LFrxReport.Variables['ValRef']          := '''' + AInfo.AlbaranRemitente + '''';
    LFrxReport.Variables['ValPortes']       := '''' + LIncotermStr + '''';
    LFrxReport.Variables['ValDistribucion'] := '''' + LDistStr + '''';
    LFrxReport.Variables['ValExpedicion']   := '''' + AInfo.CodExpedicion + '''';
    LFrxReport.Variables['ValDestName']     := '''' + AInfo.NombreDestinatario + '''';
    LFrxReport.Variables['ValDestDir']      := '''' + AInfo.DirDestinatario + '''';
    LFrxReport.Variables['ValDestCP']       := '''' + Trim(AInfo.CPDestinatario + ' - ' + AInfo.PobDestinatario) + '''';
    LFrxReport.Variables['ValZR']           := '''' + Trim(AInfo.AreaDisCod + '  ' + AInfo.AreaDisDsc) + '''';
    LFrxReport.Variables['ValRuta']         := '''' + LRutaStr + '''';
    LFrxReport.Variables['ValCentroDest']   := '''' + LCentroDestStr + '''';
    LFrxReport.Variables['ValZRNum']        := '''' + LZRNumStr + '''';

    LPdfExport.ShowDialog       := False;
    LPdfExport.ShowProgress     := False;
    LPdfExport.OpenAfterExport  := False;
    LPdfExport.FileName         := LTempPdf;
    LPdfExport.Background       := True;
    LPdfExport.EmbeddedFonts    := True;
    LPdfExport.EmbedFontsIfProtected := True;
    LPdfExport.Compressed       := False;

    LFrxReport.EngineOptions.UseFileCache := False;
    if LFrxReport.PrepareReport(True) then
    begin
      LFrxReport.Export(LPdfExport);
      if FileExists(LTempPdf) then
      begin
        Result := TFile.ReadAllBytes(LTempPdf);
        try TFile.Delete(LTempPdf); except end;
      end;
    end;
  finally
    LPdfExport.Free;
    LFrxReport.Free;
  end;
end;

// ---------------------------------------------------------------------------
function TTransaherEnviosClient.DescargarEtiquetasWS(const ACodExpedicion, AHolding, ASeccion, ACentro: string;
  out AError: string): TBytes;
var
  LToken, LURL, LBody, LResponse: string;
  LHol, LSec, LCtr, LCod: string;
  LDataB64, LHasError, LDescError: string;
begin
  SetLength(Result, 0);
  AError := '';

  LToken := GetAuthToken(AError);
  if LToken = '' then
    Exit;

  LHol := Trim(AHolding);
  if LHol = '' then LHol := '0';
  LSec := Trim(ASeccion);
  if LSec = '' then LSec := '10';

  LCtr := Trim(ACentro);
  if (LCtr = '') or (Length(LCtr) < 3) then
  begin
    if Trim(FLastExpInfo.Centro) <> '' then
      LCtr := Trim(FLastExpInfo.Centro)
    else
      LCtr := '451';
  end;

  LCod := Trim(ACodExpedicion);
  if LCod = '' then
  begin
    AError := 'El código de expedición para descargar etiquetas está vacío.';
    Exit;
  end;

  // Transaher requiere código numérico de 9 posiciones con ceros a la izquierda
  var LNumExp: Int64;
  if TryStrToInt64(LCod, LNumExp) then
    LCod := Format('%.9d', [LNumExp]);

  LURL := FURLBridge + '/wsetiexpsoap.svc';
  LBody :=
    '<?xml version="1.0" encoding="utf-8"?>' +
    '<soapenv:Envelope xmlns:soapenv="' + NS_SOAPENV + '" xmlns:mws="MWSBridge.wsetiexpsoap_services" xmlns:mwsb="MWSBridge">' +
    '<soapenv:Header/>' +
    '<soapenv:Body>' +
    '  <mws:execute>' +
    '    <mws:Token>' + XmlEscape(LToken) + '</mws:Token>' +
    '    <mws:wsEtiExpParams>' +
    '      <mwsb:PosicionInicialImpresion>1</mwsb:PosicionInicialImpresion>' +
    '      <mwsb:Expediciones>' +
    '        <mwsb:wsEtiExpSOAPParams.Expedicion>' +
    '          <mwsb:Holding>' + XmlEscape(LHol) + '</mwsb:Holding>' +
    '          <mwsb:Seccion>' + XmlEscape(LSec) + '</mwsb:Seccion>' +
    '          <mwsb:Centro>' + XmlEscape(LCtr) + '</mwsb:Centro>' +
    '          <mwsb:Codigo>' + XmlEscape(LCod) + '</mwsb:Codigo>' +
    '          <mwsb:Bultos>1</mwsb:Bultos>' +
    '        </mwsb:wsEtiExpSOAPParams.Expedicion>' +
    '      </mwsb:Expediciones>' +
    '    </mws:wsEtiExpParams>' +
    '  </mws:execute>' +
    '</soapenv:Body>' +
    '</soapenv:Envelope>';

  try
    LResponse := PostSOAP(LURL, 'MWSBridge.wsetiexpsoap_services/wsetiexpsoap_services/execute', LBody);
  except
    on E: Exception do
    begin
      AError := 'Error al contactar con el servicio wsetiexpsoap de Transaher: ' + E.Message;
      Exit;
    end;
  end;

  LHasError := ExtractNode(LResponse, 'HasError');
  if SameText(LHasError, 'true') then
  begin
    LDescError := ExtractNode(LResponse, 'Description');
    if LDescError = '' then LDescError := ExtractNode(LResponse, 'Name');
    AError := 'Transaher wsetiexpsoap devolvió error: ' + LDescError;
    // Si no devolvió PDF, salimos para que pueda intentar el fallback local
  end;

  LDataB64 := ExtractNode(LResponse, 'Data');
  if LDataB64 <> '' then
  begin
    try
      Result := TNetEncoding.Base64.DecodeStringToBytes(LDataB64);
      AError := '';
    except
      on E: Exception do
        AError := 'Error al decodificar PDF de etiquetas Base64: ' + E.Message;
    end;
  end;
end;

// ---------------------------------------------------------------------------
function TTransaherEnviosClient.ConvertirZplAPdf(const AZplBytes: TBytes): TBytes;
var
  LHttp: THTTPClient;
  LReqStream, LRespStream: TMemoryStream;
  LResp: IHTTPResponse;
begin
  SetLength(Result, 0);
  if Length(AZplBytes) = 0 then Exit;

  LHttp := THTTPClient.Create;
  LReqStream := TMemoryStream.Create;
  LRespStream := TMemoryStream.Create;
  try
    LHttp.ConnectionTimeout := 8000;
    LHttp.ResponseTimeout   := 15000;
    LHttp.CustomHeaders['Accept'] := 'application/pdf';

    LReqStream.WriteBuffer(AZplBytes[0], Length(AZplBytes));
    LReqStream.Position := 0;

    try
      LResp := LHttp.Post('http://api.labelary.com/v1/printers/8dpmm/labels/4x6/0/', LReqStream, LRespStream);
      if (LResp <> nil) and (LResp.StatusCode = 200) and (LRespStream.Size > 100) then
      begin
        SetLength(Result, LRespStream.Size);
        LRespStream.Position := 0;
        LRespStream.ReadBuffer(Result[0], LRespStream.Size);

        // Verificar que empiece por %PDF ($25, $50, $44, $46)
        if (Length(Result) >= 4) and (Result[0] = $25) and (Result[1] = $50) and (Result[2] = $44) and (Result[3] = $46) then
          Exit
        else
          SetLength(Result, 0);
      end;
    except
      SetLength(Result, 0);
    end;
  finally
    LRespStream.Free;
    LReqStream.Free;
    LHttp.Free;
  end;
end;

procedure TTransaherEnviosClient.CargarExpedicionDesdeBD(const ACodExp: string);
var
  LQry: TFDQuery;
begin
  if (ACodExp = '') or SameText(FLastExpInfo.CodExpedicion, ACodExp) then
    Exit;

  if not Assigned(dmgMain) or not Assigned(dmgMain.dbConn) or not dmgMain.dbConn.Connected then
    Exit;

  try
    LQry := TFDQuery.Create(nil);
    try
      LQry.Connection := dmgMain.dbConn;
      LQry.SQL.Text :=
        'SELECT r.id, r.cod_recogida, r.guid_transportista, r.referencia, r.num_bultos, ' +
        '       r.persona_contacto, r.direccion, r.cp, r.poblacion, r.telefono, r.observaciones, ' +
        '       r.fecha_recogida ' +
        'FROM ge_envios_recogidas r ' +
        'WHERE r.cod_recogida = :c1 OR r.guid_transportista LIKE :c2 ' +
        'ORDER BY r.id DESC LIMIT 1';
      LQry.ParamByName('c1').AsString := ACodExp;
      LQry.ParamByName('c2').AsString := '%' + ACodExp + '%';
      LQry.Open;

      if not LQry.IsEmpty then
      begin
        FLastExpInfo.CodExpedicion      := ACodExp;
        FLastExpInfo.Holding            := '0';
        FLastExpInfo.Seccion            := '10';
        FLastExpInfo.Centro             := '31';
        FLastExpInfo.CentroEditor       := 'ALICANTE';
        FLastExpInfo.NumeroRecogida     := '';
        FLastExpInfo.Incoterm           := 'PAGADOS';
        FLastExpInfo.NombreDestinatario := LQry.FieldByName('persona_contacto').AsString;
        FLastExpInfo.DirDestinatario    := LQry.FieldByName('direccion').AsString;
        FLastExpInfo.CPDestinatario     := LQry.FieldByName('cp').AsString;
        FLastExpInfo.PobDestinatario    := LQry.FieldByName('poblacion').AsString;
        FLastExpInfo.Observaciones      := LQry.FieldByName('observaciones').AsString;
        FLastExpInfo.Bultos             := LQry.FieldByName('num_bultos').AsInteger;
        if FLastExpInfo.Bultos < 1 then FLastExpInfo.Bultos := 1;
        FLastExpInfo.Peso               := 1.0;
        FLastExpInfo.AlbaranOrdenante   := LQry.FieldByName('referencia').AsString;
        FLastExpInfo.AlbaranRemitente   := LQry.FieldByName('referencia').AsString;
        FLastExpInfo.AreaDisCod         := '2019';
        FLastExpInfo.AreaDisDsc         := LQry.FieldByName('poblacion').AsString;
        FLastExpInfo.CentroDestino      := '461';
        FLastExpInfo.AreaDestino        := 'VALENCIA (TTE)';
      end;
    finally
      LQry.Free;
    end;
  except
    // Fallback silencioso si falla la consulta
  end;
end;

// ---------------------------------------------------------------------------
function TTransaherEnviosClient.GetEtiqueta(const ARef: string; APDF: Boolean): TBytes;
var
  LBarcode24: string;
  LZpl: string;
  LCtrCod, LHol, LSec, LCodExp: string;
  LWsBytes: TBytes;
  LWsError: string;
  LParts: TArray<string>;
begin
  if (FCachedLabelRef <> '') and SameText(FCachedLabelRef, ARef) and
     (Length(FCachedLabelBytes) > 0) then
  begin
    Result := FCachedLabelBytes;
    Exit;
  end;

  // Extraer Holding, Seccion, Centro y Codigo si ARef viene en formato compuesto (Holding/Seccion/Centro/Codigo)
  LHol    := FLastExpInfo.Holding;
  LSec    := FLastExpInfo.Seccion;
  LCtrCod := FLastExpInfo.Centro;
  LCodExp := Trim(ARef);

  if Pos('/', ARef) > 0 then
  begin
    LParts := ARef.Split(['/']);
    if Length(LParts) = 4 then
    begin
      LHol    := LParts[0];
      LSec    := LParts[1];
      LCtrCod := LParts[2];
      LCodExp := LParts[3];
    end
    else if Length(LParts) = 2 then
    begin
      LCtrCod := LParts[0];
      LCodExp := LParts[1];
    end;
  end;

  if LHol = '' then LHol := '0';
  if LSec = '' then LSec := '10';
  if LCtrCod = '' then LCtrCod := FConfig.CodAgencia;
  if LCtrCod = '' then LCtrCod := '451';

  // Si no tenemos los datos en memoria para esta expedición, recuperarlos de la BD
  CargarExpedicionDesdeBD(LCodExp);

  if APDF then
  begin
    // 1. Generar la etiqueta oficial homologada (idéntica al portal Web de Transaher) mediante FastReport
    LBarcode24 := BuildBarcode24(LCtrCod, LCodExp, 1, FLastExpInfo.CPDestinatario);
    Result := GenerarEtiquetaFastReport(FLastExpInfo, 1, LBarcode24);
    if Length(Result) > 0 then
    begin
      FCachedLabelRef   := ARef;
      FCachedLabelBytes := Result;
      Exit;
    end;

    // 2. Fallback: Si FastReport no estuviera disponible, intentar descarga vía Web Service
    LWsBytes := DescargarEtiquetasWS(LCodExp, LHol, LSec, LCtrCod, LWsError);
    if Length(LWsBytes) > 0 then
    begin
      if (Length(LWsBytes) >= 4) and (LWsBytes[0] = $25) and (LWsBytes[1] = $50) and (LWsBytes[2] = $44) and (LWsBytes[3] = $46) then
        Result := LWsBytes
      else
        Result := ConvertirZplAPdf(LWsBytes);

      if Length(Result) > 0 then
      begin
        FCachedLabelRef   := ARef;
        FCachedLabelBytes := Result;
        Exit;
      end;
    end;
  end
  else
  begin
    // Modo Térmica (ZPL):
    LBarcode24 := BuildBarcode24(LCtrCod, LCodExp, 1, FLastExpInfo.CPDestinatario);
    LZpl := GenerarEtiquetaZPL(FLastExpInfo, 1, LBarcode24);
    Result := TEncoding.UTF8.GetBytes(LZpl);
  end;
end;

// ---------------------------------------------------------------------------
function TTransaherEnviosClient.ImprimirEtiquetaTermica(const ARef: string;
  const AImpresora: string; out AError: string; AGirar180: Boolean;
  AHorizontal: Boolean): Boolean;
var
  LBytes: TBytes;
  LPdfPath, LPrinterName: string;
  LFS: TFileStream;
  LRet: NativeUInt;
  LDegrees: Integer;
begin
  Result := False;
  AError := '';
  LPrinterName := Trim(AImpresora);

  try
    LBytes := GetEtiqueta(ARef, True);
    if Length(LBytes) = 0 then
    begin
      AError := 'No se pudieron generar los datos de la etiqueta de Transaher para ' + ARef + '.';
      Exit;
    end;

    LPdfPath := GetEnvironmentVariable('TEMP') + '\Etiqueta_Transaher_' +
                StringReplace(ARef, '/', '_', [rfReplaceAll]) + '_' +
                FormatDateTime('yyyymmddhhnnss', Now) + '.pdf';

    LFS := TFileStream.Create(LPdfPath, fmCreate);
    try
      LFS.WriteBuffer(LBytes[0], Length(LBytes));
    finally
      LFS.Free;
    end;

    if AHorizontal then
    begin
      if AGirar180 then LDegrees := 270 else LDegrees := 90;
    end
    else
    begin
      if AGirar180 then LDegrees := 180 else LDegrees := 0;
    end;

    if LDegrees <> 0 then
      TPdfRotateService.RotarPdfArchivoGrados(LPdfPath, LDegrees);

    if LPrinterName <> '' then
    begin
      LRet := ShellExecute(0, 'printto', PChar(LPdfPath), PChar('"' + LPrinterName + '"'), nil, SW_HIDE);
      if LRet > 32 then
        Result := True
      else
        AError := 'Error al enviar la impresión a la impresora "' + LPrinterName + '".';
    end
    else
    begin
      ShellExecute(0, 'open', PChar(LPdfPath), nil, nil, SW_SHOWNORMAL);
      Result := True;
    end;
  except
    on E: Exception do
      AError := E.Message;
  end;
end;

function TTransaherEnviosClient.ImprimirEtiquetaTermica(const ARef: string;
  const AImpresora: string; out AError: string; AGirar180: Boolean): Boolean;
begin
  Result := ImprimirEtiquetaTermica(ARef, AImpresora, AError, AGirar180, True);
end;

function TTransaherEnviosClient.ImprimirEtiquetaTermica(const ARef: string;
  const AImpresora: string; out AError: string): Boolean;
begin
  Result := ImprimirEtiquetaTermica(ARef, AImpresora, AError, True, True);
end;

function TTransaherEnviosClient.ImprimirEtiquetaTermica(const ARef: string;
  out AError: string): Boolean;
begin
  Result := ImprimirEtiquetaTermica(ARef, '', AError, True, True);
end;

end.
