unit uWooCommerceClient;

interface

uses
  System.SysUtils, System.Classes, System.Net.HttpClient, System.Net.URLClient,
  System.JSON, System.NetEncoding, System.IOUtils, Data.DB, FireDAC.Comp.Client,
  FireDAC.Stan.Param;

type
  TWooCommerceClient = class
  private
    class function LoadConfig(AEmpresaId: Integer; out AUrl, AKey, ASecret: string): Boolean;
    class function NormalizeBaseUrl(const AUrl: string): string;
  public
    class function HasConfig(AEmpresaId: Integer): Boolean;
    class function TestConnection(AEmpresaId: Integer; var AErrorMsg: string): Boolean;
    class function UpdateOrderStatus(AEmpresaId: Integer; AOrderId: Int64; const ANewStatus: string; var AErrorMsg: string): Boolean;
    class function GetOrderKey(AEmpresaId: Integer; AOrderId: Int64; out AOrderKey: string; var AErrorMsg: string): Boolean;
    class function DownloadInvoicePDF(AEmpresaId: Integer; AOrderId: Int64; const ADestPath: string; var AErrorMsg: string; AOrderKey: string = ''): Boolean;
    class function OpenInvoicePDF(AEmpresaId: Integer; AOrderId: Int64; var AErrorMsg: string; AOrderKey: string = ''): Boolean;
  end;

implementation

uses
  Winapi.Windows, Winapi.ShellAPI, dmg_Main;

// ---------------------------------------------------------------------------
class function TWooCommerceClient.NormalizeBaseUrl(const AUrl: string): string;
begin
  Result := Trim(AUrl);
  if Result = '' then
    Result := 'https://raulasencio.es'
  else
  begin
    if not (Result.StartsWith('http://', True) or Result.StartsWith('https://', True)) then
      Result := 'https://' + Result;
    if Result.EndsWith('/') then
      Result := Copy(Result, 1, Length(Result) - 1);
  end;
end;

// ---------------------------------------------------------------------------
class function TWooCommerceClient.LoadConfig(AEmpresaId: Integer; out AUrl, AKey, ASecret: string): Boolean;
var
  Qry: TFDQuery;
begin
  Result := False;
  AUrl := 'https://raulasencio.es';
  AKey := '';
  ASecret := '';

  if AEmpresaId <= 0 then
    AEmpresaId := StrToIntDef(dmgMain.CurrentCompanyId, 1);

  Qry := TFDQuery.Create(nil);
  try
    Qry.Connection := dmgMain.dbConn;
    Qry.SQL.Text := 'SELECT wc_url, wc_key, wc_secret FROM ge_empresas WHERE id = :id';
    Qry.ParamByName('id').AsInteger := AEmpresaId;
    Qry.Open;
    if not Qry.IsEmpty then
    begin
      if (Qry.FindField('wc_url') <> nil) and (Trim(Qry.FieldByName('wc_url').AsString) <> '') then
        AUrl := NormalizeBaseUrl(Qry.FieldByName('wc_url').AsString);

      if Qry.FindField('wc_key') <> nil then
        AKey := Trim(Qry.FieldByName('wc_key').AsString);

      if Qry.FindField('wc_secret') <> nil then
        ASecret := Trim(Qry.FieldByName('wc_secret').AsString);

      Result := (AKey <> '') and (ASecret <> '');
    end;
  except
    Result := False;
  end;
  Qry.Free;
end;

// ---------------------------------------------------------------------------
class function TWooCommerceClient.HasConfig(AEmpresaId: Integer): Boolean;
var
  LUrl, LKey, LSec: string;
begin
  Result := LoadConfig(AEmpresaId, LUrl, LKey, LSec);
end;

// ---------------------------------------------------------------------------
class function TWooCommerceClient.TestConnection(AEmpresaId: Integer; var AErrorMsg: string): Boolean;
var
  LUrl, LKey, LSecret, LEndpoint: string;
  LClient: THTTPClient;
  LResponse: IHTTPResponse;
begin
  Result := False;
  AErrorMsg := '';

  if not LoadConfig(AEmpresaId, LUrl, LKey, LSecret) then
  begin
    AErrorMsg := 'La empresa no tiene configuradas las claves REST API de WooCommerce (wc_key, wc_secret) en ge_empresas.';
    Exit;
  end;

  LClient := THTTPClient.Create;
  try
    LClient.ConnectionTimeout := 8000;
    LClient.ResponseTimeout := 10000;
    LClient.UserAgent := 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) DelphiGest/1.0';

    LEndpoint := Format('%s/wp-json/wc/v3/orders?per_page=1&consumer_key=%s&consumer_secret=%s', [LUrl, LKey, LSecret]);
    LResponse := LClient.Get(LEndpoint);

    if LResponse.StatusCode = 200 then
      Result := True
    else
      AErrorMsg := Format('Error HTTP %d: %s', [LResponse.StatusCode, LResponse.StatusText]);
  except
    on E: Exception do
      AErrorMsg := 'Excepción conectando con WooCommerce REST API: ' + E.Message;
  end;
  LClient.Free;
end;

// ---------------------------------------------------------------------------
class function TWooCommerceClient.UpdateOrderStatus(AEmpresaId: Integer; AOrderId: Int64; const ANewStatus: string; var AErrorMsg: string): Boolean;
var
  LUrl, LKey, LSecret, LEndpoint: string;
  LClient: THTTPClient;
  LReqStream, LRespStream: TStringStream;
  LResponse: IHTTPResponse;
  LJsonBody: string;
  LCleanStatus: string;
begin
  Result := False;
  AErrorMsg := '';

  if not LoadConfig(AEmpresaId, LUrl, LKey, LSecret) then
  begin
    AErrorMsg := 'No están configuradas las credenciales REST API de WooCommerce para la empresa.';
    Exit;
  end;

  LCleanStatus := LowerCase(Trim(ANewStatus));
  if LCleanStatus.StartsWith('wc-') then
    LCleanStatus := Copy(LCleanStatus, 4, Length(LCleanStatus));

  LJsonBody := Format('{"status":"%s"}', [LCleanStatus]);

  LClient := THTTPClient.Create;
  LReqStream := TStringStream.Create(LJsonBody, TEncoding.UTF8);
  LRespStream := TStringStream.Create('', TEncoding.UTF8);
  try
    LClient.ContentType := 'application/json';
    LClient.ConnectionTimeout := 10000;
    LClient.ResponseTimeout := 15000;
    LClient.UserAgent := 'DelphiGest/1.0 (WooCommerce Client)';

    LEndpoint := Format('%s/wp-json/wc/v3/orders/%d?consumer_key=%s&consumer_secret=%s', [LUrl, AOrderId, LKey, LSecret]);
    LResponse := LClient.Put(LEndpoint, LReqStream, LRespStream);

    if (LResponse.StatusCode >= 200) and (LResponse.StatusCode < 300) then
      Result := True
    else
      AErrorMsg := Format('Error HTTP %d actualizando pedido %d: %s', [LResponse.StatusCode, AOrderId, LRespStream.DataString]);
  except
    on E: Exception do
      AErrorMsg := Format('Fallo en petición REST API (Pedido %d): %s', [AOrderId, E.Message]);
  end;
  LRespStream.Free;
  LReqStream.Free;
  LClient.Free;
end;

// ---------------------------------------------------------------------------
class function TWooCommerceClient.GetOrderKey(AEmpresaId: Integer; AOrderId: Int64; out AOrderKey: string; var AErrorMsg: string): Boolean;
var
  LUrl, LKey, LSecret, LEndpoint: string;
  LClient: THTTPClient;
  LResponse: IHTTPResponse;
  LJson: TJSONObject;
begin
  Result := False;
  AOrderKey := '';
  AErrorMsg := '';

  if not LoadConfig(AEmpresaId, LUrl, LKey, LSecret) then
  begin
    AErrorMsg := 'No están configuradas las credenciales REST API de WooCommerce.';
    Exit;
  end;

  LClient := THTTPClient.Create;
  try
    LClient.ConnectionTimeout := 8000;
    LClient.ResponseTimeout := 10000;
    LClient.UserAgent := 'DelphiGest/1.0';

    LEndpoint := Format('%s/wp-json/wc/v3/orders/%d?consumer_key=%s&consumer_secret=%s', [LUrl, AOrderId, LKey, LSecret]);
    LResponse := LClient.Get(LEndpoint);

    if LResponse.StatusCode = 200 then
    begin
      LJson := TJSONObject.ParseJSONValue(LResponse.ContentAsString(TEncoding.UTF8)) as TJSONObject;
      if Assigned(LJson) then
      begin
        try
          if LJson.GetValue('order_key') <> nil then
          begin
            AOrderKey := LJson.GetValue('order_key').Value;
            Result := AOrderKey <> '';
          end;
        finally
          LJson.Free;
        end;
      end;
      if not Result then
        AErrorMsg := 'El pedido web no devolvió una order_key válida.';
    end
    else
      AErrorMsg := Format('Error HTTP %d obteniendo order_key: %s', [LResponse.StatusCode, LResponse.StatusText]);
  except
    on E: Exception do
      AErrorMsg := 'Excepción al consultar order_key: ' + E.Message;
  end;
  LClient.Free;
end;

// ---------------------------------------------------------------------------
class function TWooCommerceClient.DownloadInvoicePDF(AEmpresaId: Integer; AOrderId: Int64; const ADestPath: string; var AErrorMsg: string; AOrderKey: string = ''): Boolean;
var
  LUrl, LKey, LSecret, LEndpoint: string;
  LClient: THTTPClient;
  LFileStream: TFileStream;
  LResponse: IHTTPResponse;
  LHeaderBytes: TBytes;
  LHeaderStr: string;
begin
  Result := False;
  AErrorMsg := '';

  if not LoadConfig(AEmpresaId, LUrl, LKey, LSecret) then
  begin
    AErrorMsg := 'No están configuradas las credenciales de WooCommerce en la empresa.';
    Exit;
  end;

  // Si no se proporcionó la order_key, obtenerla vía REST API
  if Trim(AOrderKey) = '' then
  begin
    if not GetOrderKey(AEmpresaId, AOrderId, AOrderKey, AErrorMsg) then
      Exit;
  end;

  ForceDirectories(ExtractFileDir(ADestPath));

  LClient := THTTPClient.Create;
  LFileStream := TFileStream.Create(ADestPath, fmCreate);
  try
    LClient.ConnectionTimeout := 10000;
    LClient.ResponseTimeout := 25000;
    LClient.UserAgent := 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) DelphiGest/1.0';

    LEndpoint := Format('%s/wp-admin/admin-ajax.php?action=generate_wpo_wcpdf&document_type=invoice&order_ids=%d&order_key=%s',
                        [LUrl, AOrderId, AOrderKey]);

    LResponse := LClient.Get(LEndpoint, LFileStream);

    if LResponse.StatusCode = 200 then
    begin
      // Validar que el archivo descargado sea realmente un PDF (cabecera %PDF-)
      LFileStream.Position := 0;
      SetLength(LHeaderBytes, 5);
      if (LFileStream.Size >= 5) and (LFileStream.Read(LHeaderBytes[0], 5) = 5) then
      begin
        LHeaderStr := TEncoding.ANSI.GetString(LHeaderBytes);
        if LHeaderStr.StartsWith('%PDF') then
          Result := True
        else
          AErrorMsg := 'El servidor web devolvió una respuesta que no es un archivo PDF válido.';
      end
      else
        AErrorMsg := 'El archivo PDF recibido está vacío.';
    end
    else
      AErrorMsg := Format('Error HTTP %d al descargar factura: %s', [LResponse.StatusCode, LResponse.StatusText]);
  except
    on E: Exception do
      AErrorMsg := 'Excepción al descargar factura PDF: ' + E.Message;
  end;
  LFileStream.Free;
  LClient.Free;

  // Si no fue exitoso, eliminar archivo temporal/incompleto
  if not Result and FileExists(ADestPath) then
    System.SysUtils.DeleteFile(ADestPath);
end;

// ---------------------------------------------------------------------------
class function TWooCommerceClient.OpenInvoicePDF(AEmpresaId: Integer; AOrderId: Int64; var AErrorMsg: string; AOrderKey: string = ''): Boolean;
var
  LTempPath, LFileName: string;
begin
  LTempPath := IncludeTrailingPathDelimiter(TPath.GetTempPath);
  LFileName := Format('%sFactura_Web_%d.pdf', [LTempPath, AOrderId]);

  Result := DownloadInvoicePDF(AEmpresaId, AOrderId, LFileName, AErrorMsg, AOrderKey);
  if Result then
  begin
    ShellExecute(0, 'open', PChar(LFileName), nil, nil, SW_SHOWNORMAL);
  end;
end;

end.
