unit View.OrderEntryWeb;

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;

type
  TFOrderEntryWeb = class(TWebForm)
    WebLabel2: TWebLabel;
    pnlMessage: TWebPanel;
    lblMessage: TWebLabel;
    btnCloseNotification: TWebButton;
    edtCompanyName: TWebDBEdit;
    edtCompanyAccountName: TWebDBEdit;
    edtInQuickBooks: TWebDBEdit;
    XDataWebClient1: TXDataWebClient;
    tmrScrollTop: TWebTimer;
    XDataWebDataSet1: TXDataWebDataSet;
    XDataWebDataSet1ORDER_ID: TIntegerField;
    XDataWebDataSet1COMPANY_ID: TIntegerField;
    XDataWebDataSet1USER_ID: TIntegerField;
    XDataWebDataSet1ORDER_DATE: TDateField;
    XDataWebDataSet1NAME: TStringField;
    XDataWebDataSet1SHORT_NAME: TStringField;
    XDataWebDataSet1staff_fields_ship_via: TStringField;
    XDataWebDataSet1staff_fields_price: TStringField;
    XDataWebDataSet1staff_fields_invoice_to: TStringField;
    XDataWebDataSet1staff_fields_invoice_attention: TStringField;
    XDataWebDataSet1staff_fields_ship_to: TStringField;
    XDataWebDataSet1staff_fields_ship_attention: TStringField;
    XDataWebDataSet1staff_fields_po_number: TStringField;
    XDataWebDataSet1staff_fields_job_name: TStringField;
    XDataWebDataSet1staff_fields_quickbooks_item: TStringField;
    XDataWebDataSet1staff_fields_quantity: TStringField;
    XDataWebDataSet1staff_fields_art_location: TStringField;
    XDataWebDataSet1staff_fields_order_date: TStringField;
    XDataWebDataSet1staff_fields_proof_date: TStringField;
    XDataWebDataSet1staff_fields_ship_date: TStringField;
    XDataWebDataSet1staff_fields_art_due: TStringField;
    XDataWebDataSet1staff_fields_plate_due: TStringField;
    XDataWebDataSet1ADDRESS_LIST: TStringField;
    WebDataSource1: TWebDataSource;
    WebLabel1: TWebLabel;
    dtpOrderDate: TWebDateTimePicker;
    dtpProofDate: TWebDateTimePicker;
    dtpShipDate: TWebDateTimePicker;
    dtpArtDue: TWebDateTimePicker;
    dtpPlateDue: TWebDateTimePicker;
    edtShipVia: TWebDBEdit;
    edtQuantity: TWebDBEdit;
    edtPrice: TWebDBEdit;
    edtInvoiceTo: TWebDBEdit;
    edtPONumber: TWebDBEdit;
    edtJobName: TWebDBEdit;
    WebDBComboBox1: TWebDBComboBox;
    wdsShipTo: TWebDataSource;
    xdwdsShipTo: TXDataWebDataSet;
    xdwdsShipToADDRESS: TStringField;
    WebLabel3: TWebLabel;
    edtBWorColorCopy: TWebDBEdit;
    edtPlates: TWebDBEdit;
    edtDimensionalLayout: TWebDBEdit;
    edtSample: TWebDBEdit;
    edtOther: TWebDBEdit;
    edtEmail: TWebDBEdit;
    edtTotalInchesUsed: TWebDBEdit;
    edtFTP: TWebDBEdit;
    edtSheetsUsed: TWebDBEdit;
    edtInitials: TWebDBEdit;
    WebLabel4: TWebLabel;
    cbPDF: TWebDBCheckBox;
    edtPDFTo: TWebDBEdit;
    dtpPDFDate1: TWebDateTimePicker;
    dtpPDFDate3: TWebDateTimePicker;
    dtpPDFDate2: TWebDateTimePicker;
    cbInkJet: TWebDBCheckBox;
    edtInkJetTo2: TWebDBEdit;
    edtInkJetTo1: TWebDBEdit;
    dtpInkJetDate1: TWebDateTimePicker;
    dtpInkJetDate3: TWebDateTimePicker;
    dtpInkJetDate2: TWebDateTimePicker;
    edtColorContrastTo: TWebDBEdit;
    dtpColorContractDate1: TWebDateTimePicker;
    dtpColorContractDate2: TWebDateTimePicker;
    edtDigitalColorTo: TWebDBEdit;
    edtDigitalColorKey: TWebDBEdit;
    dtpDigitalColorDate: TWebDateTimePicker;
    WebLabel5: TWebLabel;
    edtAniloxInfo: TWebDBEdit;
    edtPressName: TWebDBEdit;
    WebButton1: TWebButton;
    WebLabel6: TWebLabel;
    edtMicroDots: TWebDBEdit;
    edtMicrodotsComments: TWebDBEdit;
    edtCrosshairsComments: TWebDBEdit;
    edtCrosshairs: TWebDBEdit;
    edtColorBarsComments: TWebDBEdit;
    edtColorBars: TWebDBEdit;
    edtPlateOther: TWebDBEdit;
    edtPlateOtherComments: TWebDBEdit;
    WebLabel7: TWebLabel;
    WebLabel8: TWebLabel;
    edtAround: TWebDBEdit;
    edtAccross: TWebDBEdit;
    edtReversePrint: TWebDBEdit;
    edtSurfacePrint: TWebDBEdit;
    edtCutoffDimension: TWebDBEdit;
    edtCylinderRepeat: TWebDBEdit;
    edtPitch: TWebDBEdit;
    edtBleed: TWebDBEdit;
    edtTeeth: TWebDBEdit;
    edtCutback: TWebDBEdit;
    edtMinimumTrapDim: TWebDBEdit;
    edtMaximumTrapDim: TWebDBEdit;
    WebLabel9: TWebLabel;
    edtSize: TWebDBEdit;
    edtBarWidthReduction: TWebDBEdit;
    edtDistortionAmount: TWebDBEdit;
    edtDistortionPercent: TWebDBEdit;
    WebLabel10: TWebLabel;
    edtJobNumber: TWebDBEdit;
    WebLabel11: TWebLabel;
    Comments: TWebDBEdit;
    btnSave: TWebButton;
    btnPDF: TWebButton;
    btnCancel: TWebButton;
    XDataWebDataSet1plates_job_number: TStringField;
    XDataWebDataSet1supplied_by_customer_plates: TStringField;
    XDataWebDataSet1supplied_by_customer_sample: TStringField;
    XDataWebDataSet1supplied_by_customer_dimension: TStringField;
    XDataWebDataSet1supplied_by_customer_other: TStringField;
    XDataWebDataSet1supplied_by_customer_disk: TStringField;
    XDataWebDataSet1supplied_by_customer_e_mail: TStringField;
    XDataWebDataSet1supplied_by_customer_ftp: TStringField;
    XDataWebDataSet1plates_plate_material: TStringField;
    XDataWebDataSet1plates_thickness: TStringField;
    XDataWebDataSet1supplied_by_customer_total_inc: TStringField;
    XDataWebDataSet1supplied_by_customer_sheets_us: TStringField;
    XDataWebDataSet1supplied_by_customer_initials: TStringField;
    XDataWebDataSet1proofing_pdf_to: TStringField;
    XDataWebDataSet1proofing_pdf_date_1: TStringField;
    XDataWebDataSet1proofing_pdf_date_2: TStringField;
    XDataWebDataSet1proofing_pdf_date_3: TStringField;
    XDataWebDataSet1proofing_ink_jet_to: TStringField;
    XDataWebDataSet1proofing_ink_jet_to_2: TStringField;
    XDataWebDataSet1proofing_ink_jet_date_1: TStringField;
    XDataWebDataSet1proofing_ink_jet_date_2: TStringField;
    XDataWebDataSet1proofing_ink_jet_date_3: TStringField;
    XDataWebDataSet1proofing_color_contract: TStringField;
    XDataWebDataSet1proofing_color_contrac_to: TStringField;
    XDataWebDataSet1proofing_color_contrac_date_1: TStringField;
    XDataWebDataSet1proofing_color_contrac_date_2: TStringField;
    XDataWebDataSet1proofing_digital_color_key: TStringField;
    XDataWebDataSet1proofing_digital_color_to: TStringField;
    XDataWebDataSet1proofing_digital_color_date_1: TStringField;
    XDataWebDataSet1quantity_and_colors_press_name: TStringField;
    XDataWebDataSet1quantity_and_colors_anilox_info: TStringField;
    XDataWebDataSet1plate_marks_microdots_comments: TStringField;
    XDataWebDataSet1plate_marks_microdots: TStringField;
    XDataWebDataSet1plate_marks_crosshairs: TStringField;
    XDataWebDataSet1plate_marks_crosshairs_comments: TStringField;
    XDataWebDataSet1plate_marks_color_bars: TStringField;
    XDataWebDataSet1plate_marks_color_bars_comments: TStringField;
    XDataWebDataSet1plate_marks_other: TStringField;
    XDataWebDataSet1plate_marks_other_comments: TStringField;
    XDataWebDataSet1print_orientation_print_orient: TStringField;
    XDataWebDataSet1layout_around: TStringField;
    XDataWebDataSet1layout_accross: TStringField;
    XDataWebDataSet1layout_surface_print: TStringField;
    XDataWebDataSet1layout_reverse_print: TStringField;
    XDataWebDataSet1layout_cylinder_repeat: TStringField;
    XDataWebDataSet1layout_cutoff_dimension: TStringField;
    XDataWebDataSet1layout_pitch: TStringField;
    XDataWebDataSet1layout_teeth: TStringField;
    XDataWebDataSet1layout_bleed: TStringField;
    XDataWebDataSet1layout_minimum_trap_dim: TStringField;
    XDataWebDataSet1layout_maximum_trap_dim: TStringField;
    XDataWebDataSet1upc_size: TStringField;
    XDataWebDataSet1upc_bar_width_reduction: TStringField;
    XDataWebDataSet1general_comments: TStringField;
    XDataWebDataSet1upc_distortion_percent: TStringField;
    XDataWebDataSet1upc_distortion_amount: TStringField;
    XDataWebDataSet1layout_cutback: TStringField;
    XDataWebDataSet1proofing_full_size_ink_jet_for: TBooleanField;
    XDataWebDataSet1proofing_pdf: TBooleanField;
    XDataWebDataSet1quantity_and_colors_qty_colors: TStringField;
    XDataWebDataSet1supplied_by_customer_b_w_or_co: TStringField;
    wcbQBItem: TWebDBComboBox;
    wdsQBItem: TWebDataSource;
    xdwdsQBItem: TXDataWebDataSet;
    xdwdsQBItemname: TStringField;
    WebDBComboBox2: TWebDBComboBox;
    WebDBComboBox3: TWebDBComboBox;
    wcbPrint: TWebDBComboBox;
    WebDBComboBox4: TWebDBComboBox;
    btnCopy: TWebButton;
    btnDelete: TWebButton;
    btnClose: TWebButton;
    edtOrderNum: TWebEdit;
    btn_confirm_delete: TWebButton;
    tmrReturn: TWebTimer;
    btnEdit: TWebButton;
    btnAdd: TWebButton;
    procedure WebFormCreate(Sender: TObject);
    procedure HideNotification();
    procedure ShowNotification(Notification: string);
    procedure WebFormShow(Sender: TObject);
    [async] procedure getOrder(Order_ID: string);
    [async] procedure getCustomer(customerID: string);
    procedure tmrScrollTopTimer(Sender: TObject);
    procedure WebButton1Click(Sender: TObject);
    procedure addColorRow(num, Color, LPI, Size: string);
    procedure btnSaveClick(Sender: TObject);
    [async] procedure AddWebOrder(orderJSON: TJSONObject);
    procedure btnCancelClick(Sender: TObject);
    procedure btnPDFClick(Sender: TObject);
    [async] procedure GenerateReportPDF;
    procedure SendOrderToServer;
    procedure btnCopyClick(Sender: TObject);
    procedure btnCloseClick(Sender: TObject);
    procedure btnDeleteClick(Sender: TObject);
    [async] procedure DelOrder;
    procedure btnCloseNotificationClick(Sender: TObject);
    procedure tmrReturnTimer(Sender: TObject);
    procedure btn_confirm_deleteClick(Sender: TObject);
    function VerifyOrder(): boolean;
    procedure btnAddClick(Sender: TObject);
    procedure btnEditClick(Sender: TObject);
    procedure EditMode();
    procedure XDataWebDataSet1AfterEdit(DataSet: TDataSet);
    procedure dtpOrderDateChange(Sender: TObject);
    procedure ViewMode();
  private
    FAgencyCode: string;
    FCurrentReportType: string;
    FSelectProc: TSelectProc;
    orderID: string;
    customerID: string;
    mode: string;
    notification: string;
    //FJSONProc1: TJSONProc1;
  public
    class function CreateForm(AElementID, orderInfo, customerInfo, mode, info: string): TWebForm;
  end;

var
  FOrderEntryWeb: TFOrderEntryWeb;

implementation

{$R *.dfm}

uses
  View.Home, View.Main, View.AddOrder;

procedure TFOrderEntryWeb.btnSaveClick(Sender: TObject);
begin
  if VerifyOrder() then
  begin
    sendOrderToServer();
    ViewMode();
  end;
  window.scrollTo(0, 0);
end;

function TFOrderEntryWeb.VerifyOrder: Boolean;
var
  input: TJSHTMLInputElement;
begin
  result := true;

  input := TJSHTMLInputElement(document.getElementById('edtcompanyname'));
  if edtCompanyName.Text = '' then
  begin
    input.classList.add('is-invalid');
    result := false;
  end
  else
    input.classList.remove('is-invalid');


  input := TJSHTMLInputElement(document.getElementById('edtaccountcompanyname'));
  if edtCompanyAccountName.Text = '' then
  begin

    input.classList.add('is-invalid');
    result := false;
  end
  else
    input.classList.remove('is-invalid');

  input := TJSHTMLInputElement(document.getElementById('edtinvoiceto'));
  if edtInvoiceTo.Text = '' then
  begin
    input.classList.add('is-invalid');
    result := false;
  end
  else
    input.classList.remove('is-invalid');


  input := TJSHTMLInputElement(document.getElementById('wcbshipto'));
  if WebDBComboBox1.Text = '' then
  begin
    input.classList.add('is-invalid');
    result := false;
  end
  else
    input.classList.remove('is-invalid');

  input := TJSHTMLInputElement(document.getElementById('dtporderdate'));
  if dtpOrderDate.Date = 0 then
  begin
    input.classList.add('is-invalid');
    result := false;
  end
  else
    input.classList.remove('is-invalid');
end;

procedure TFOrderEntryWeb.btnCopyClick(Sender: TObject);
begin
  mode := 'ADD';
  dtpOrderDate.Date := 0;
  dtpProofDate.Date := 0;
  dtpArtDue.Date := 0;
  dtpPlateDue.Date := 0;
  dtpShipDate.Date := 0;
  dtpPDFDate1.Date := 0;
  dtpPDFDate2.Date := 0;
  dtpPDFDate3.Date := 0;
  dtpInkJetDate1.Date := 0;
  dtpInkJetDate2.Date := 0;
  dtpInkJetDate3.Date := 0;
  dtpColorContractDate1.Date := 0;
  dtpColorContractDate2.Date := 0;
  dtpDigitalColorDate.Date := 0;
  edtOrderNum.Text := '';
  EditMode();
  ShowNotification('Success:Order Successfully Copied');
  window.scrollTo(0, 0);
end;

procedure TFOrderEntryWeb.btnDeleteClick(Sender: TObject);
begin
  asm
    var confirmationModal = new bootstrap.Modal(document.getElementById('confirmation_modal'), {
    keyboard: false });
    confirmationModal.show();
  end;
end;

procedure TFOrderEntryWeb.btnEditClick(Sender: TObject);
begin
  EditMode();
end;

procedure TFOrderEntryWeb.EditMode;
begin
  FViewMain.change := true;
  btnCopy.Enabled := false;
  btnPDF.Enabled := false;
  btnDelete.Enabled := false;
  btnClose.Enabled := false;
  btnSave.Enabled := true;
  btnCancel.Enabled := True;
  btnEdit.Enabled := false;
  btnAdd.Enabled := false;
end;

[async] procedure TFOrderEntryWeb.DelOrder();
var
  Response: TXDataClientResponse;
begin
  Response := await(XDataWebClient1.RawInvokeAsync('ILookupService.DelOrder',
              [OrderID, 'web', JS.toString(AuthService.TokenPayload.Properties['user_id'])]));
end;

procedure TFOrderEntryWeb.dtpOrderDateChange(Sender: TObject);
begin
  EditMode();
end;

procedure TFOrderEntryWeb.SendOrderToServer();
// Converts all the information on the page into a JSON to then send to the server
var
  colorList: TJSONArray;
  container: TJSElement;
  colorCollection: TJSHTMLCollection;
  color: TJSHTMLElement;
  I, J: integer;
  colorJSON, orderJSON, colorListJSON: TJSONObject;
  fieldNames: TStringList;
  itemList: TJSNodeList;
  header, value, info: string;
  Field: TField;
  Response: TXDataClientResponse;
begin
  orderJSON := TJSONObject.Create;
  colorList := TJSONArray.Create;
  container := document.getElementById('additionalFields');
  colorCollection := container.children;
  for I := 0 to colorCollection.length - 1 do
  begin
    colorJSON := TJSONObject.Create;
    itemList := colorCollection[I].childNodes;
    for J := 0 to itemList.length - 2 do
    begin
      header := TJSHTMLElement(itemList[J]).children[0].innerText.Replace(':', '').Trim();
      value := TJSHTMLInputElement(TJSHTMLElement(itemList[J]).childNodes[1]).value;
      colorJSON.AddPair(header, value);
    end;
    colorList.Add(colorJSON);
  end;
  colorListJSON := TJSONObject.Create;
  colorListJSON.AddPair('items', colorList);
  XDataWebDataSet1.Edit;

  XDataWebDataSet1quantity_and_colors_qty_colors.Value := colorListJSON.ToString;

  //Convert all dates to strings because I was having less issues with that data type.
  XDataWebDataSet1staff_fields_proof_date.Value := DateTimeToStr(dtpProofDate.Date);
  XDataWebDataSet1staff_fields_ship_date.Value := DateTimeToStr(dtpShipDate.Date);
  XDataWebDataSet1staff_fields_art_due.Value := DateTimeToStr(dtpArtDue.Date);
  XDataWebDataSet1staff_fields_plate_due.Value := DateTimeToStr(dtpPlateDue.Date);
  XDataWebDataSet1staff_fields_order_date.Value := DateTimeToStr(dtpOrderDate.Date);
  XDataWebDataSet1proofing_pdf_date_1.Value := DateTimeToStr(dtpPDFDate1.Date);
  XDataWebDataSet1proofing_pdf_date_2.Value := DateTimeToStr(dtpPDFDate2.Date);
  XDataWebDataSet1proofing_pdf_date_3.Value := DateTimeToStr(dtpPDFDate3.Date);
  XDataWebDataSet1proofing_ink_jet_date_1.Value := DateTimeToStr(dtpInkJetDate1.Date);
  XDataWebDataSet1proofing_ink_jet_date_2.Value := DateTimeToStr(dtpInkJetDate2.Date);
  XDataWebDataSet1proofing_ink_jet_date_3.Value := DateTimeToStr(dtpInkJetDate3.Date);
  XDataWebDataSet1proofing_color_contrac_date_1.Value := DateTimeToStr(dtpColorContractDate1.Date);
  XDataWebDataSet1proofing_color_contrac_date_2.Value := DateTimeToStr(dtpColorContractDate2.Date);
  XDataWebDataSet1proofing_digital_color_date_1.Value := DateTimeToStr(dtpDigitalColorDate.Date);

  XDataWebDataSet1.Post;
  XDataWebDataSet1.First;
  while not XDataWebDataSet1.Eof do
  begin
    for Field in XDataWebDataSet1.Fields do
    begin
      if Field is TStringField then
      begin
        if Field.AsString = '' then
          orderJSON.AddPair(Field.FieldName, '')
        else
          orderJSON.AddPair(Field.FieldName, Field.AsString);  // Add all other fields
      end
      else if Field is TBooleanField then
      begin
        if Field.AsBoolean then
          orderJSON.AddPair(Field.FieldName, 'T')
        else
          orderJSON.AddPair(Field.FieldName, '');
      end;
    end;
    XDataWebDataSet1.Next;
  end;
  orderJSON.AddPair('COMPANY_ID', customerID);
  orderJSON.AddPair('USER_ID', JS.toString(AuthService.TokenPayload.Properties['user_id']));
  orderJSON.AddPair('mode', mode);
  if mode = 'EDIT' then
  begin
    orderJSON.AddPair('ORDER_ID', orderID);
    info := 'Success:Order Successfully Edited';
  end
  else
    info := 'Success:Order Successfully Added';
  AddWebOrder(orderJSON);
  ShowNotification(info);
end;

procedure TFOrderEntryWeb.btnPDFClick(Sender: TObject);
begin
  GenerateReportPDF;
end;

procedure TFOrderEntryWeb.btn_confirm_deleteClick(Sender: TObject);
begin
  if  document.getElementById('btn_confirm_delete').innerText = 'Yes' then
  begin
    FViewMain.change := false;
    if OrderID <> '' then
    begin
      FViewMain.ViewOrderEntryWeb(OrderID, '', 'EDIT', 'Failure:Changes Discarded');
    end
    else
      FViewMain.ViewOrders('');
  end
  else
  begin
    asm
      var confirmationModal = new bootstrap.Modal(document.getElementById('confirmation_modal'), {
      keyboard: false });
      confirmationModal.hide();
      startSpinner();
    end;
    delOrder();
    tmrReturn.Enabled := true;
  end;
end;

procedure TFOrderEntryWeb.GenerateReportPDF;
// sends the search to the server which then sends back a pdf of the results
var
  xdcResponse: TXDataClientResponse;
  searchOptions, pdfURL: string;
  jsObject: TJSObject;
begin

  // Call the server method to generate the PDF
  xdcResponse := await(XDataWebClient1.RawInvokeAsync('ILookupService.GenerateOrderWebPDF', [orderID]));
  jsObject := JS.TJSObject(xdcResponse.Result);
  pdfURL := JS.toString(jsObject.Properties['value']);

  // Open the PDF in a new browser tab without needing a different form
  // This method is much faster too, even for large datasets
  window.open(pdfURL, '_blank');
end;

procedure TFOrderEntryWeb.AddWebOrder(orderJSON: TJSONObject);
// sends the order JSON object to the server
var
  Response: TXDataClientResponse;
  jsObj: TJSObject;
begin
  Response := await(XDataWebClient1.RawInvokeAsync('ILookupService.AddWebOrder',
              [orderJSON.ToString]));
  jsObj := JS.TJSObject(Response.Result);
  if mode = 'ADD' then
    OrderID := String(jsObj.Properties['OrderID']);
  console.log(OrderID);
  mode := 'EDIT';
end;

class function TFOrderEntryWeb.CreateForm(AElementID, orderInfo, customerInfo, mode, info: string): TWebForm;
var
  localMode: string;
begin
  localMode := mode;
  Application.CreateForm(TFOrderEntryWeb, AElementID, Result,
    procedure(AForm: TObject)
    begin
      with TFOrderEntryWeb(AForm) do
      begin
        HideNotification;
        TFOrderEntryWeb(AForm).customerID := customerInfo;
        TFOrderEntryWeb(AForm).orderID := orderInfo;
        TFOrderEntryWeb(AForm).mode := localMode;
        TFOrderEntryWeb(AForm).notification := info;
      end;
    end
  );

end;

procedure TFOrderEntryWeb.addColorRow(num: string; Color: string; LPI: string; Size: string);
// Java script code to add a row of colors when a button is clicked
// all variables are information to be placed in the boxes when loading an order.
// TODO: convert to Delphi
begin
  asm
      const container = document.getElementById('additionalFields');

      // Create a new row for the new fields
      const newRow = document.createElement('div');
      newRow.className = 'row mb-2';

      const labels = ['#', 'Color', 'LPI', 'Size'];
      const values = [num, Color, LPI, Size];
      labels.forEach((label, index) => {
        const col = document.createElement('div');
        col.className = 'col-sm';

        const labelElement = document.createElement('label');
        labelElement.className = 'pe-2';
        labelElement.style.fontWeight = '700';
        labelElement.style.fontSize = '15px';
        labelElement.textContent = label + ':';

        const inputElement = document.createElement('input');
        inputElement.className = 'form-control input-sm';
        inputElement.style.width = '100%';
        inputElement.id =  'input-' + container.childElementCount + '-' + index; // Unique ID based on count
        inputElement.value = values[index];  // Set the value based on the parameter

        col.appendChild(labelElement);
        col.appendChild(inputElement);

        newRow.appendChild(col);
      });

      const removeButtonCol = document.createElement('div');
      removeButtonCol.className = 'col-auto d-flex align-items-center';

      const removeButton = document.createElement('button');
      removeButton.className = 'btn btn-danger btn-sm';
      removeButton.textContent = 'Remove';
      removeButton.addEventListener('click', function() {
        container.removeChild(newRow);
      });

      removeButtonCol.appendChild(removeButton);
      newRow.appendChild(removeButtonCol);

      container.appendChild(newRow);
    end;
end;

procedure TFOrderEntryWeb.WebButton1Click(Sender: TObject);
begin
  addColorRow('','','','');
end;

procedure TFOrderEntryWeb.btnAddClick(Sender: TObject);
var
  newform: TFAddOrder;
  orderType: string;
begin
  newform := TFAddOrder.CreateNew;

  newform.Caption := 'Select Customer and Order Type';
  newForm.Popup := True;
  newForm.Border := fbDialog;

  // used to manage Back button handling to close subform
  window.location.hash := 'subform';

  newform.ShowModal(
    procedure(AValue: TModalResult)
    begin
      if newform.confirm then
      begin
        if newform.cbCorrugatedPlate.Checked then
          orderType := 'corrugated'
        else if newform.cbWebPlate.Checked then
          orderType := 'web'
        else
          orderType := 'cutting';

        if orderType = 'corrugated' then
          FViewMain.ViewOrderEntryCorrugated('', newForm.DBID, 'ADD', '')
        else if orderType = 'web' then
          FViewMain.ViewOrderEntryWeb('', newForm.DBID, 'ADD', '')
        else
          FViewMain.ViewOrderEntryCuttingDie('', newForm.DBID, 'ADD', '');
      end;
    end
  );
end;

procedure TFOrderEntryWeb.btnCancelClick(Sender: TObject);
begin
  document.getElementById('modal_body').innerHTML := 'Are you sure you want to cancel all changes?';
  document.getElementById('btn_confirm_cancel').innerText := 'No';
  document.getElementById('btn_confirm_delete').innerText := 'Yes';
  asm
    var confirmationModal = new bootstrap.Modal(document.getElementById('confirmation_modal'), {
    keyboard: false });
    confirmationModal.show();
  end;
end;

procedure TFOrderEntryWeb.btnCloseClick(Sender: TObject);
begin
  FViewMain.ViewOrders('');
end;

procedure TFOrderEntryWeb.btnCloseNotificationClick(Sender: TObject);
begin
  hideNotification();
end;

procedure TFOrderEntryWeb.WebFormCreate(Sender: TObject);
begin
   if not DMConnection.ApiConnection.Connected then
   begin
    DMConnection.ApiConnection.OpenAsync;
    console.log('report requirements connection open')
   end;
end;

procedure TFOrderEntryWeb.getOrder(Order_ID: string);
// retrieves an order from the server then loads the info into the page
var
  xdcResponse: TXDataClientResponse;
  orderList : TJSObject;
  i: integer;
  data: TJSArray;
  order: TJSObject;
  callListLength: integer;
  tempString, strColorList: string;
  colorObject: TJSObject;
  colorList: TJSArray;
  colorLength: integer;
  color: TJSObject;
  colorJSON: TJSONObject;
  colorListJSON: TJSONArray;
  items: TJSObject;
begin
  xdcResponse := await(XDataWebClient1.RawInvokeAsync('ILookupService.GetWebOrder',
        [Order_ID]));
  order :=  TJSObject(xdcResponse.Result);
  data := TJSArray(order['data']);
  XDataWebDataSet1.Close;
  XDataWebDataSet1.SetJsonData(order);
  XDataWebDataSet1.Open;
  if XDataWebDataSet1quantity_and_colors_qty_colors.Value <> '' then
  begin
  colorObject := TJSObject(TJSJSON.parse(XDataWebDataSet1quantity_and_colors_qty_colors.Value));
  colorList := TJSArray(colorObject['items']);
  for I := 0 to colorList.length -1 do
    begin
      color := TJSObject(colorList[i]);
      addColorRow(String(color['#']), string(color['Color']), string(color['LPI']), string(color['Size']));
    end;
  end;

  // Dates need to be manually set

  if not (XDataWebDataSet1staff_fields_order_date.AsString = '') then
    dtpOrderDate.Date := StrToDateTime(XDataWebDataSet1staff_fields_order_date.Value)
  else
    dtpOrderDate.Date := 0;
  if not (XDataWebDataSet1staff_fields_proof_date.AsString = '') then
    dtpProofDate.Date := StrToDateTime(XDataWebDataSet1staff_fields_proof_date.AsString)
  else
    dtpProofDate.Date := 0;
  if not (XDataWebDataSet1staff_fields_ship_date.AsString = '') then
    dtpShipDate.Date := StrToDateTime(XDataWebDataSet1staff_fields_ship_date.AsString)
  else
    dtpShipDate.Date := 0;
  if not (XDataWebDataSet1staff_fields_art_due.AsString = '') then
    dtpArtDue.Date := StrToDateTime(XDataWebDataSet1staff_fields_art_due.AsString)
  else
    dtpArtDue.Date := 0;
  if not (XDataWebDataSet1staff_fields_plate_due.AsString = '') then
    dtpPlateDue.Date := StrToDateTime(XDataWebDataSet1staff_fields_plate_due.AsString)
  else
    dtpPlateDue.Date := 0;

  if not (XDataWebDataSet1proofing_pdf_date_1.AsString = '') then
    dtpPDFDate1.Date := StrToDateTime(XDataWebDataSet1proofing_pdf_date_1.Value)
  else
    dtpPDFDate1.Date := 0;

  if not (XDataWebDataSet1proofing_pdf_date_2.AsString = '') then
    dtpPDFDate2.Date := StrToDateTime(XDataWebDataSet1proofing_pdf_date_2.Value)
  else
    dtpPDFDate2.Date := 0;

  if not (XDataWebDataSet1proofing_pdf_date_3.AsString = '') then
    dtpPDFDate3.Date := StrToDateTime(XDataWebDataSet1proofing_pdf_date_3.Value)
  else
    dtpPDFDate3.Date := 0;

  if not (XDataWebDataSet1proofing_ink_jet_date_1.AsString = '') then
    dtpInkJetDate1.Date := StrToDateTime(XDataWebDataSet1proofing_ink_jet_date_1.Value)
  else
    dtpInkJetDate1.Date := 0;

  if not (XDataWebDataSet1proofing_ink_jet_date_2.AsString = '') then
    dtpInkJetDate2.Date := StrToDateTime(XDataWebDataSet1proofing_ink_jet_date_2.Value)
  else
    dtpInkJetDate2.Date := 0;

  if not (XDataWebDataSet1proofing_ink_jet_date_3.AsString = '') then
    dtpInkJetDate3.Date := StrToDateTime(XDataWebDataSet1proofing_ink_jet_date_3.Value)
  else
    dtpInkJetDate3.Date := 0;

  if not (XDataWebDataSet1proofing_color_contrac_date_1.AsString = '') then
    dtpColorContractDate1.Date := StrToDateTime(XDataWebDataSet1proofing_color_contrac_date_1.Value)
  else
    dtpColorContractDate1.Date := 0;

  if not (XDataWebDataSet1proofing_color_contrac_date_2.AsString = '') then
    dtpColorContractDate2.Date := StrToDateTime(XDataWebDataSet1proofing_color_contrac_date_2.Value)
  else
    dtpColorContractDate2.Date := 0;

  if not (XDataWebDataSet1proofing_digital_color_date_1.AsString = '') then
    dtpDigitalColorDate.Date := StrToDateTime(XDataWebDataSet1proofing_digital_color_date_1.Value)
  else
    dtpDigitalColorDate.Date := 0;


  if mode = 'EDIT' then
  begin
    CustomerID := XDataWebDataSet1COMPANY_ID.AsString;
    xdwdsShipTo.Close;
    xdwdsShipTo.SetJSONData(order['ADDRESS_LIST']);
    xdwdsShipTo.Open;
  end;

  xdwdsQBItem.Close;
  items := TJSObject(order['ITEMS']);
  xdwdsQBItem.SetJsonData(items['data']);
  xdwdsQBITEM.Open;

end;

procedure TFOrderEntryWeb.getCustomer(customerID: string);
// gets a customer from the database then loads the appropiate fields
var
  xdcResponse: TXDataClientResponse;
  customer : TJSObject;
  address: string;
  items: TJSObject;
begin
  xdcResponse := await(XDataWebClient1.RawInvokeAsync('ILookupService.GetCustomer',
        [customerID]));
  customer :=  TJSObject(xdcResponse.Result);
  XDataWebDataSet1.Close;
  XDataWebDataSet1.SetJsonData(customer);
  XDataWebDataSet1.Open;



  xdwdsShipTo.Close;
  xdwdsShipTo.SetJSONData(customer['ADDRESS_LIST']);
  xdwdsShipTo.Open;

  xdwdsQBItem.Close;
  items := TJSObject(customer['ITEMS']);
  xdwdsQBItem.SetJsonData(items['data']);
  xdwdsQBITEM.Open;

  dtpOrderDate.Date := 0;
  dtpProofDate.Date := 0;
  dtpArtDue.Date := 0;
  dtpPlateDue.Date := 0;
  dtpShipDate.Date := 0;
  dtpPDFDate1.Date := 0;
  dtpPDFDate2.Date := 0;
  dtpPDFDate3.Date := 0;
  dtpInkJetDate1.Date := 0;
  dtpInkJetDate2.Date := 0;
  dtpInkJetDate3.Date := 0;
  dtpColorContractDate1.Date := 0;
  dtpColorContractDate2.Date := 0;
  dtpDigitalColorDate.Date := 0;

end;

procedure TFOrderEntryWeb.WebFormShow(Sender: TObject);
begin
  if mode <> 'ADD' then
  begin
    getOrder(orderID);
    ViewMode();
  end
  else
  begin
    getCustomer(customerID);
    EditMode();
  end;
  edtOrderNum.Text := OrderID;
  if notification = '' then
  begin
    HideNotification;
  end
  else
  begin
    ShowNotification(notification);
  end;
end;

procedure TFOrderEntryWeb.XDataWebDataSet1AfterEdit(DataSet: TDataSet);
begin
  EditMode();
end;

procedure TFOrderEntryWeb.HideNotification;
begin
   pnlMessage.ElementHandle.hidden := True;
end;

procedure TFOrderEntryWeb.ShowNotification(Notification: string);
var
  splitNotification: TArray<string>;
begin
  if Notification <> '' then
  begin
    splitNotification := Notification.Split([':']);
    if(splitNotification[0] = 'Success') then
    begin
      asm
        var messageDiv = document.getElementById('view.login.message');
        messageDiv.classList.remove('alert-danger');
        messageDiv.classList.add('alert-success');
      end;
    end
    else
    begin
      asm
        var messageDiv = document.getElementById('view.login.message');
        messageDiv.classList.remove('alert-success');
        messageDiv.classList.add('alert-danger');
      end;
    end;
    lblMessage.Caption := splitNotification[1];
    pnlMessage.ElementHandle.hidden := False;
  end;
end;


procedure TFOrderEntryWeb.tmrReturnTimer(Sender: TObject);
begin
  asm
    endSpinner();
  end;
  tmrReturn.Enabled := false;
  FViewMain.ViewOrders('Success: Order Successfully Deleted');
end;

procedure TFOrderEntryWeb.tmrScrollTopTimer(Sender: TObject);
begin
  tmrScrollTop.Enabled := False;
  window.scrollTo(0, 0);
end;

procedure TFOrderEntryWeb.ViewMode;
begin
  btnPDF.Enabled := true;
  btnDelete.Enabled := true;
  btnClose.Enabled := true;
  btnCopy.Enabled := true;
  btnSave.Enabled := false;
  btnCancel.Enabled := false;
  btnEdit.Enabled := true;
  btnAdd.Enabled := true;
  FViewMain.change := false;
end;


end.