unit rOrders;

interface

uses
  System.SysUtils, System.Classes, frxClass, frxExportBaseDialog, frxExportPDF,
  Data.DB, DBAccess, Uni, UniProvider, MySQLUniProvider, System.IniFiles, Vcl.Forms,
  MemDS, frxDBSet, frxTableObject, frCoreClasses, Common.Logging, System.IOUtils, JSON;

type
  TrptOrders = class(TDataModule)
    frxOrders: TfrxReport;
    frxPDFExport1: TfrxPDFExport;
    ucKG: TUniConnection;
    uqOrders: TUniQuery;
    frxDBOrders: TfrxDBDataset;
    uqOrdersORDER_ID: TLongWordField;
    uqOrdersLoc: TStringField;
    uqOrdersCOMPANY_NAME: TStringField;
    uqOrdersJOB_NAME: TStringField;
    uqOrdersORDER_DATE: TDateTimeField;
    uqOrdersORDER_TYPE: TStringField;
    uqOrdersPROOF_DUE: TDateField;
    uqOrdersPROOF_DONE: TDateTimeField;
    uqOrdersART_DUE: TDateField;
    uqOrdersART_DONE: TDateTimeField;
    uqOrdersPLATE_DUE: TDateField;
    uqOrdersPLATE_DONE: TDateTimeField;
    uqOrdersMOUNT_DUE: TDateField;
    uqOrdersMOUNT_DONE: TDateTimeField;
    uqOrdersSHIP_DUE: TDateField;
    uqOrdersSHIP_DONE: TDateTimeField;
    uqOrdersPRICE: TFloatField;
    uqOrdersQB_REF_NUM: TStringField;
    uqOrdersCOLORS: TStringField;
    uqColors: TUniQuery;
    procedure DataModuleCreate(Sender: TObject);
    procedure uqOrdersCalcFields(DataSet: TDataSet);

  private
    function getColorCount(colors: string): string;

  public
    function PrepareReport(SQL: string): string;
    function GeneratePDF: string;
  end;

var
  rptOrders: TrptOrders;

implementation

uses
  uLibrary, Common.Config;

{%CLASSGROUP 'Vcl.Controls.TControl'}

{$R *.dfm}

procedure TrptOrders.DataModuleCreate(Sender: TObject);
begin
  Logger.Log( 3, 'TAuthDatabase.DataModuleCreate' );
  LoadDatabaseSettings( ucKG, 'kgOrdersServer.ini' );
  try
    ucKG.Connect;
  except
    on E: Exception do
    begin
      Logger.Log(3, '--TrptOrders.DataModuleCreate -Error connecting to database: ' + E.Message);
    end;
  end;
end;


function TrptOrders.PrepareReport(SQL: string): string;
begin
  Logger.Log(5, 'Generated SQL for Prepare Report: ' + SQL);

  uqOrders.Close;
  uqOrders.SQL.Text := SQL;
  uqOrders.Open;


  result := GeneratePDF;

  Logger.Log(5, 'Report preparation complete.');
end;



procedure TrptOrders.uqOrdersCalcFields(DataSet: TDataSet);
var
  ColorType: string;
  SQL: string;
  OrderID: LongWord;
  jsonStr: string;
begin
  OrderID := uqOrdersORDER_ID.AsInteger;
  if uqOrdersORDER_TYPE.AsString = 'web_plate' then
  begin
    ColorType := 'quantity_and_colors_qty_colors';
    SQL := 'SELECT ' + ColorType + ' FROM web_plate_orders WHERE order_id = ' + IntToStr(OrderID);
  end
  else
  begin
    ColorType := 'colors_colors';
    SQL := 'SELECT ' + ColorType + ' FROM corrugated_plate_orders WHERE order_id = ' + IntToStr(OrderID);
  end;

  uqColors.Close;
  uqColors.SQL.Text := SQL;
  try
    uqColors.Open;
    jsonStr := uqColors.FieldByName(ColorType).AsString;
    DataSet.FieldByName('COLORS').AsString := getColorCount(jsonStr);
  finally
    uqColors.Close; // Ensure it is closed
  end;
end;

//create new field called color count
function TrptOrders.getColorCount(colors: string): string;
var
  colorObject: TJSONObject;
  colorList: TJSONArray;
begin
  if colors = '' then
    result := '0'
  else
  begin
    colorObject := TJSONObject.ParseJSONValue(colors) as TJSONObject;
    try
      colorList := TJSONArray(colorObject.GetValue('items'));
      result := IntToStr(colorList.Count);
    finally
      colorObject.Free;
    end;
  end;
end;

function TrptOrders.GeneratePDF: string;
var
  ReportDir, ReportFileName: string;
  reportURL: string;
begin
  ReportDir := ServerConfig.reportsFolder;

  if not DirectoryExists(ReportDir) then
  begin
    ForceDirectories(ReportDir);
    Logger.Log(5, 'Reports directory created: ' + ReportDir);
  end;
  reportURL :=  'reports\' + FormatDateTime('yyyymmdd_hhnnss', Now) + '.pdf';

  ReportFileName := reportDir + reportUrl;

  frxPDFExport1.FileName := ReportFileName;
  frxPDFExport1.ShowDialog := False;
  try
    frxOrders.PrepareReport;
    frxOrders.Export(frxPDFExport1);
    //frxOrders.ShowPreparedReport;
  finally
     frxOrders.Clear; // Clears the report to avoid memory bloat
  end;

  Logger.Log(5, 'PDF saved to: ' + ReportFileName);
  result := reportURL;
end;

end.

