unit View.Item.Add;

interface

uses
  System.SysUtils, System.Generics.Collections, System.Classes, JS, Web, WEBLib.Graphics, WEBLib.Controls,
  WEBLib.Forms, WEBLib.Dialogs, WEBLib.Menus, WEBLib.ExtCtrls, WEBLib.StdCtrls,
  WEBLib.JSON, Auth.Service, XData.Web.Client, WebLib.Storage,
  ConnectionModule, App.Types, Vcl.StdCtrls, Vcl.Controls, WEBLib.DBCtrls,
  Data.DB, XData.Web.JsonDataset, XData.Web.Dataset, WEBLib.DB, VCL.TMSFNCTypes, VCL.TMSFNCUtils,
  VCL.TMSFNCGraphics, VCL.TMSFNCGraphicsTypes, VCL.TMSFNCGridCell,
  VCL.TMSFNCGridOptions, VCL.TMSFNCCustomControl, VCL.TMSFNCCustomScrollControl,
  VCL.TMSFNCGridData, VCL.TMSFNCCustomGrid, VCL.TMSFNCGrid, Utils;

type
  TfViewAddItem = class(TWebForm)
    WebLabel1: TWebLabel;
    WebLabel3: TWebLabel;
    edtSearch: TWebEdit;
    TMSFNCGrid1: TTMSFNCGrid;
    btnCancel: TWebButton;
    btnConfirm: TWebButton;
    edtNotification: TWebEdit;
    edtName: TWebEdit;
    XDataWebClient1: TXDataWebClient;
    xdwdsCustomers: TXDataWebDataSet;
    wdsCustomers: TWebDataSource;
    xdwdsCustomersqb_items_id: TStringField;
    xdwdsCustomersqb_item_name: TStringField;
    xdwdsCustomersitem_desc: TStringField;
    xdwdsCustomersstatus: TStringField;
    xdwdsCustomersqb_items_qb_id: TStringField;
    lblEntries: TWebLabel;
    procedure WebFormCreate(Sender: TObject);
    procedure WebFormShow(Sender: TObject);
    procedure TMSFNCGrid1CellClick(Sender: TObject; ACol, ARow: Integer);
    procedure btnConfirmClick(Sender: TObject);
    procedure btnCancelClick(Sender: TObject);
    procedure edtSearchChange(Sender: TObject);
  private
    { Private declarations }
    [async] procedure getItems();
    procedure PopulateGridManually();
    procedure ApplyFilter();
    [async] procedure SendItemToServer();
  var
    mode: string;
  public
    { Public declarations }
    notification: string;
    confirm: Boolean;
    QB_ID, name, description, status: string;
  end;

var
  fViewAddItem: TfViewAddItem;

implementation

{$R *.dfm}

procedure TfViewAddItem.WebFormCreate(Sender: TObject);
begin
  if not DMConnection.ApiConnection.Connected then
   begin
    DMConnection.ApiConnection.OpenAsync;
   end;
end;

procedure TfViewAddItem.WebFormShow(Sender: TObject);
begin
  //Utils.ShowSpinner('spinner');
  if String(Self.Caption).Contains('Add') then
    mode := 'ADD'
  else
    mode := 'UPDATE';
  getItems();
end;

procedure TfViewAddItem.btnCancelClick(Sender: TObject);
begin
  close();
end;

procedure TfViewAddItem.btnConfirmClick(Sender: TObject);
begin
  xdwdsCustomers.Locate('qb_item_name', edtName.Text, []);
  if edtName.Text = '' then
    edtNotification.Text := 'Please Select an Item'
  else if (  ( xdwdsCustomers.FieldByName('qb_items_id').AsString <> '' ) and ( mode = 'ADD' ) ) then
    edtNotification.Text := 'Item Already In Database'
  else
  begin
    QB_ID := xdwdsCustomers.FieldByName('qb_items_qb_id').AsString;
    name := xdwdsCustomers.FieldByName('qb_item_name').AsString;
    description :=  xdwdsCustomers.FieldByName('item_desc').AsString;
    status := xdwdsCustomers.FieldByName('status').AsString;

    confirm := true;
    Close;
  end;
end;

procedure TfViewAddItem.edtSearchChange(Sender: TObject);
begin
  ApplyFilter();
end;

procedure TfViewAddItem.getItems;
var
  xdcResponse: TXDataClientResponse;
  customerList: TJSObject;
  i: integer;
begin
  // Fetch data from XData service
  Utils.ShowSpinner('spinner');
  try
    xdcResponse := await(XDataWebClient1.RawInvokeAsync('ILookupService.getQBItems', []));
    customerList := TJSObject(xdcResponse.Result);

    // Load data into TXDataWebDataset

    xdwdsCustomers.Close;
    xdwdsCustomers.SetJsonData(customerList);
    xdwdsCustomers.Open;

    // Manually populate the grid
    PopulateGridManually;
    //Utils.HideSpinner('spinner');
  except
      on E: EXDataClientRequestException do
      begin
        Close();
        Utils.ShowErrorModal(E.ErrorResult.ErrorMessage);
      end;
    end;
  Utils.HideSpinner('spinner');
end;

procedure TFViewAddItem.PopulateGridManually;
// populates the grid with customers manually.
var
  RowIndex: Integer;
begin
  TMSFNCGrid1.BeginUpdate;
  try
    TMSFNCGrid1.Clear; // Clear any existing data

    // Set up column headers
    TMSFNCGrid1.ColumnCount := 4;
    TMSFNCGrid1.RowCount := 1;
    TMSFNCGrid1.Cells[0, 0] := 'KGOrders ID';
    TMSFNCGrid1.Cells[1, 0] := 'Item Name';
    TMSFNCGrid1.Cells[2, 0] := 'Item Description';
    TMSFNCGrid1.Cells[3, 0] := 'Status';

    // Populate the grid with data from the dataset
    xdwdsCustomers.First;
    RowIndex := 1;

    while not xdwdsCustomers.EOF do
    begin
      TMSFNCGrid1.RowCount := RowIndex + 1;
      TMSFNCGrid1.Cells[0, RowIndex] := xdwdsCustomers.FieldByName('qb_items_id').AsString;
      TMSFNCGrid1.Cells[1, RowIndex] := xdwdsCustomers.FieldByName('qb_item_name').AsString;
      TMSFNCGrid1.Cells[2, RowIndex] := xdwdsCustomers.FieldByName('item_desc').AsString;
      TMSFNCGrid1.Cells[3, RowIndex] := xdwdsCustomers.FieldByName('status').AsString;
      Inc(RowIndex);
      xdwdsCustomers.Next;
    end;

  finally
    TMSFNCGrid1.EndUpdate;
  end;
  lblEntries.Caption := 'Showing ' + IntToStr(TMSFNCGrid1.RowCount - 1) + ' entries...';
  Utils.HideSpinner('spinner');
end;

procedure TfViewAddItem.TMSFNCGrid1CellClick(Sender: TObject; ACol,
  ARow: Integer);
begin
  edtName.Text := TMSFNCGrid1.Cells[1, ARow];
end;

procedure TFViewAddItem.ApplyFilter;
// filters the grid based on search textbox contents.
var
  fd: TTMSFNCGridFilterData;
  i: Integer;
  SearchText: string;
begin
  SearchText := Trim(edtSearch.Text);

  TMSFNCGrid1.RemoveFilter;
  TMSFNCGrid1.Filter.Clear;

  // match on first 3 columns
  for i := 0 to 2 do
  begin
    fd := TMSFNCGrid1.Filter.Add;
    fd.Column := i;
    fd.Condition := '*' + SearchText + '*'; // Match text anywhere in the cell
    fd.CaseSensitive := False; // Make the filter case-insensitive

    // Use foOR for "match any column" logic
    if i > 0 then
      fd.Operation := foOR
    else
      fd.Operation := foNONE; // First filter has no logical operation
  end;

  // Apply the filters to the grid
  TMSFNCGrid1.ApplyFilter;
  lblEntries.Caption := 'Showing ' + IntToStr(TMSFNCGrid1.RowCount - 1) + ' entries...';
end;

procedure TFViewAddItem.SendItemToServer;
var
  ItemJSON: TJSONObject;
  Response: TXDataClientResponse;
  jsObj: TJSObject;
begin
  ItemJSON := TJSONObject.Create;
  ItemJSON.AddPair('qb_item_name', xdwdsCustomers.FieldByName('qb_item_name').AsString);
  ItemJSON.AddPair('item_desc', xdwdsCustomers.FieldByName('item_desc').AsString);
  ItemJSON.AddPair('status', xdwdsCustomers.FieldByName('status').AsString);
  ItemJSON.AddPair('qb_items_qb_id', xdwdsCustomers.FieldByName('qb_items_qb_id').AsString);
  ItemJSON.AddPair('mode', 'ADD');


 // Utils.ShowSpinner('spinner');

  Response := await(XDataWebClient1.RawInvokeAsync('ILookupService.AddItem',
              [ItemJSON.ToString]));

  jsObj := TJSObject(Response.Result);

  notification := string(jsObj['msg']);

 // Utils.HideSpinner('spinner');

  Close();
end;

end.