// Order Entry page of Corruguated Orders. Used for both editting and adding
// orders.
unit View.OrderEntryCorrugated;

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
  TFOrderEntryCorrugated = class(TWebForm)
    pnlMessage: TWebPanel;
    lblMessage: TWebLabel;
    btnCloseNotification: TWebButton;
    dtpOrderDate: TWebDateTimePicker;
    dtpProofDate: TWebDateTimePicker;
    dtpShipDate: TWebDateTimePicker;
    WebLabel1: TWebLabel;
    WebLabel2: TWebLabel;
    dtpArtDue: TWebDateTimePicker;
    dtpPlateDue: TWebDateTimePicker;
    dtpMountDue: TWebDateTimePicker;
    WebLabel3: TWebLabel;
    WebLabel4: TWebLabel;
    WebLabel5: TWebLabel;
    WebLabel6: TWebLabel;
    WebButton1: TWebButton;
    WebLabel7: TWebLabel;
    dtpApprovedDate: TWebDateTimePicker;
    WebLabel8: TWebLabel;
    WebLabel9: TWebLabel;
    edtCompanyName: TWebDBEdit;
    edtCompanyAccountName: TWebDBEdit;
    edtInQuickBooks: TWebDBEdit;
    edtShipVia: TWebDBEdit;
    edtQuantity: TWebDBEdit;
    edtPrice: TWebDBEdit;
    edtInvoiceTo: TWebDBEdit;
    edtPONumber: TWebDBEdit;
    edtJobName: TWebDBEdit;
    edtOther: TWebDBEdit;
    edtCADFile: TWebDBEdit;
    edtAroundNo: TWebDBEdit;
    edtAcrossNo: TWebDBEdit;
    edtDieCutNo: TWebDBEdit;
    edtRSCD: TWebDBEdit;
    edtRSCW: TWebDBEdit;
    edtRSCL: TWebDBEdit;
    edtCustomAdhesive: TWebDBEdit;
    edtCustomBacking: TWebDBEdit;
    edtStandardSetup: TWebDBEdit;
    edtStripMount: TWebDBEdit;
    edtLoose: TWebDBEdit;
    edtRSCStyle: TWebDBEdit;
    edtProofOther: TWebDBEdit;
    edtProofShipTo: TWebDBEdit;
    edtEmailAttn: TWebDBEdit;
    edtProofEmail: TWebDBEdit;
    edtFaxAttn: TWebDBEdit;
    edtFax: TWebDBEdit;
    edtClemson: TWebDBEdit;
    edtCrossHairs: TWebDBEdit;
    edtMachineIndent: TWebDBEdit;
    edtCylinderSize: TWebDBEdit;
    edtJobNumber: TWebDBEdit;
    cbArtApprovedAsIs: TWebDBCheckBox;
    cbPDFFile: TWebDBCheckBox;
    cbWideFormat: TWebDBCheckBox;
    cbPrintCard: TWebDBCheckBox;
    cbFullSizePanel: TWebDBCheckBox;
    XDataWebClient1: TXDataWebClient;
    edtSpecialInstructions: TWebDBEdit;
    tmrScrollTop: TWebTimer;
    XDataWebDataSet1: TXDataWebDataSet;
    WebDataSource1: TWebDataSource;
    btnSave: TWebButton;
    XDataWebDataSet1ORDER_ID: TIntegerField;
    XDataWebDataSet1COMPANY_ID: TIntegerField;
    XDataWebDataSet1USER_ID: TIntegerField;
    XDataWebDataSet1ORDER_STATUS: TStringField;
    XDataWebDataSet1SCHED_JSON: 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;
    XDataWebDataSet1ORDER_DATE: TDateField;
    XDataWebDataSet1START_DATE: TDateField;
    XDataWebDataSet1END_DATE: TDateField;
    XDataWebDataSet1plates_job_number: TStringField;
    XDataWebDataSet1supplied_by_customer_dimension: TStringField;
    XDataWebDataSet1supplied_by_customer_e_mail: TStringField;
    XDataWebDataSet1supplied_by_customer_ftp: TStringField;
    XDataWebDataSet1supplied_by_customer_other: TStringField;
    XDataWebDataSet1supplied_by_customer_existing_: TStringField;
    XDataWebDataSet1supplied_by_customer_ref_art_p: TStringField;
    XDataWebDataSet1supplied_by_customer_ref_art_a: TStringField;
    XDataWebDataSet1cut_die_cutdier: TStringField;
    XDataWebDataSet1cut_die_cutdieb: TStringField;
    XDataWebDataSet1cut_die_cutdief: TStringField;
    XDataWebDataSet1cut_die_cutdierkr: TStringField;
    XDataWebDataSet1cut_die_cutdiefkr: TStringField;
    XDataWebDataSet1cut_die_cad_file: TStringField;
    XDataWebDataSet1cut_die_attached: TStringField;
    XDataWebDataSet1cut_die_boxpol250: TStringField;
    XDataWebDataSet1cut_die_boxpol155: TStringField;
    XDataWebDataSet1cut_die_boxpol125: TStringField;
    XDataWebDataSet1cut_die_brub: TStringField;
    XDataWebDataSet1proofing_fax: TStringField;
    XDataWebDataSet1proofing_fax_attn: TStringField;
    XDataWebDataSet1proofing_e_mail: TStringField;
    XDataWebDataSet1proofing_ship_to: TStringField;
    XDataWebDataSet1proofing_other: TStringField;
    XDataWebDataSet1proofing_changes_required: TStringField;
    XDataWebDataSet1proofing_changes_date: TDateField;
    XDataWebDataSet1layout_rsc_l: TStringField;
    XDataWebDataSet1layout_rcs_w: TStringField;
    XDataWebDataSet1layout_rcs_d: TStringField;
    XDataWebDataSet1layout_die_cut_no: TStringField;
    XDataWebDataSet1layout_accross_no: TStringField;
    XDataWebDataSet1layout_around_no: TStringField;
    XDataWebDataSet1layout_cad_file: TStringField;
    XDataWebDataSet1colors_cylinder_size: TStringField;
    XDataWebDataSet1colors_machine_ident: TStringField;
    XDataWebDataSet1mounting_standard_setup: TStringField;
    XDataWebDataSet1mounting_custom_backing: TStringField;
    XDataWebDataSet1mounting_custom_adhesive: TStringField;
    XDataWebDataSet1colors_cross_hairs: TStringField;
    XDataWebDataSet1colors_clemson: TStringField;
    XDataWebDataSet1plates_thickness: TStringField;
    XDataWebDataSet1plates_plate_material: TStringField;
    XDataWebDataSet1general_special_instructions: TStringField;
    XDataWebDataSet1colors_colors: TStringField;
    XDataWebDataSet1staff_fields_quickbooks_item: TStringField;
    XDataWebDataSet1staff_fields_quantity: TStringField;
    XDataWebDataSet1layout_rsc_style: TStringField;
    XDataWebDataSet1staff_fields_art_location: TStringField;
    XDataWebDataSet1NAME: TStringField;
    XDataWebDataSet1SHORT_NAME: TStringField;
    XDataWebDataSet1supplied_by_customer_b_w_copy: TBooleanField;
    XDataWebDataSet1supplied_by_customer_color_copy: TBooleanField;
    XDataWebDataSet1supplied_by_customer_plates: TBooleanField;
    XDataWebDataSet1supplied_by_customer_sample_ca: TBooleanField;
    XDataWebDataSet1supplied_by_customer_disk_or_cd: TBooleanField;
    XDataWebDataSet1mounting_loose: TStringField;
    XDataWebDataSet1mounting_sticky_bak: TBooleanField;
    XDataWebDataSet1mounting_full_mount: TBooleanField;
    XDataWebDataSet1mounting_strip_mount: TStringField;
    XDataWebDataSet1layout_excalibur_die: TBooleanField;
    XDataWebDataSet1proofing_full_size_panel: TBooleanField;
    XDataWebDataSet1proofing_print_card: TBooleanField;
    XDataWebDataSet1proofing_wide_format: TBooleanField;
    XDataWebDataSet1proofing_pdf_file: TBooleanField;
    XDataWebDataSet1proofing_art_approved_as_is: TBooleanField;
    XDataWebDataSet1proofing_e_mail_attn: TStringField;
    XDataWebDataSet1proofing_approved_date: 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;
    XDataWebDataSet1staff_fields_mount_due: TStringField;
    cbRefArtAPDF: TWebCheckBox;
    cbRefArtPrintCard: TWebCheckBox;
    cbExistingCuttingDie: TWebCheckBox;
    cbFTP: TWebCheckBox;
    cbSampleCarton: TWebCheckBox;
    cbPlates: TWebCheckBox;
    cbColorCopy: TWebCheckBox;
    cbStripMount: TWebCheckBox;
    cbFullMount: TWebCheckBox;
    cbStickyBak: TWebCheckBox;
    cbLoose: TWebCheckBox;
    cbExcaliburDie: TWebCheckBox;
    XDataWebDataSet1ADDRESS_LIST: TStringField;
    wdsShipTo: TWebDataSource;
    xdwdsShipTo: TXDataWebDataSet;
    xdwdsShipToADDRESS: TStringField;
    WebDBComboBox1: TWebDBComboBox;
    cbEmail: TWebCheckBox;
    XDataWebDataSet1supplied_by_customer_order_date: TStringField;
    btnCancel: TWebButton;
    WebDBComboBox2: TWebDBComboBox;
    wdsQBItem: TWebDataSource;
    xdwdsQBItem: TXDataWebDataSet;
    xdwdsQBItemname: TStringField;
    WebDBComboBox3: TWebDBComboBox;
    WebDBComboBox4: TWebDBComboBox;
    btnPDF: TWebButton;
    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 AddCorrugatedOrder(orderJSON: TJSONObject);
    [async] procedure GenerateReportPDF;
    [async] procedure DelOrder();
    procedure btnCancelClick(Sender: TObject);
    procedure btnPDFClick(Sender: TObject);
    procedure btnCopyClick(Sender: TObject);
    procedure sendOrderToServer();
    procedure btnCloseClick(Sender: TObject);
    procedure btnCloseNotificationClick(Sender: TObject);
    procedure btnDeleteClick(Sender: TObject);
    procedure btn_confirm_deleteClick(Sender: TObject);
    procedure tmrReturnTimer(Sender: TObject);
    function VerifyOrder(): boolean;
    procedure XDataWebDataSet1AfterEdit(DataSet: TDataSet);
    procedure xdwdsShipToAfterEdit(DataSet: TDataSet);
    procedure dtpApprovedDateChange(Sender: TObject);
    procedure dtpMountDueChange(Sender: TObject);
    procedure dtpPlateDueChange(Sender: TObject);
    procedure dtpShipDateChange(Sender: TObject);
    procedure dtpProofDateChange(Sender: TObject);
    procedure dtpOrderDateChange(Sender: TObject);
    procedure EditMode();
    procedure btnEditClick(Sender: TObject);
    procedure btnAddClick(Sender: TObject);
    procedure xdwdsQBItemAfterEdit(DataSet: TDataSet);
    procedure ViewMode();
  private
    FAgencyCode: string;
    FCurrentReportType: string;
    FSelectProc: TSelectProc;
    orderID: string;
    customerID: string;
    mode: string;
    changed: boolean;
    notification: string;
    //FJSONProc1: TJSONProc1;
  public
    class function CreateForm(AElementID, orderInfo, customerInfo, mode, info: string): TWebForm;
  end;

var
  FOrderEntryCorrugated: TFOrderEntryCorrugated;

implementation

{$R *.dfm}

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

procedure TFOrderEntryCorrugated.sendOrderToServer();
var
  colorList: TJSONArray;
  container: TJSElement;
  colorCollection: TJSHTMLCollection;
  color: TJSHTMLElement;
  I, J: integer;
  colorJSON, orderJSON, colorListJSON: TJSONObject;
  fieldNames: TStringList;
  itemList: TJSNodeList;
  header, value: 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;

  XDataWebDataSet1colors_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_mount_due.Value := DateTimeToStr(dtpMountDue.Date);
  XDataWebDataSet1staff_fields_plate_due.Value := DateTimeToStr(dtpPlateDue.Date);
  XDataWebDataSet1staff_fields_order_date.Value := DateTimeToStr(dtpOrderDate.Date);
  XDataWebDataSet1proofing_approved_date.Value := DateTimeToStr(dtpApprovedDate.Date);

  // Convert all check boxes to strings because the database stores them as strings
  if cbFTP.Checked then
    XDataWebDataSet1supplied_by_customer_ftp.AsString := 'T'
  else
    XDataWebDataSet1supplied_by_customer_ftp.AsString := '';
  if cbExistingCuttingDie.Checked then
    XDataWebDataSet1supplied_by_customer_existing_.AsString := 'T'
  else
    XDataWebDataSet1supplied_by_customer_existing_.AsString := '';
  if cbRefArtPrintCard.Checked then
    XDataWebDataSet1supplied_by_customer_ref_art_p.AsString := 'T'
  else
    XDataWebDataSet1supplied_by_customer_ref_art_p.AsString := '';
  if cbRefArtAPDF.Checked then
    XDataWebDataSet1supplied_by_customer_ref_art_a.AsString := 'T'
  else
    XDataWebDataSet1supplied_by_customer_ref_art_a.AsString := '';
  if cbColorCopy.Checked then
    XDataWebDataSet1supplied_by_customer_color_copy.AsString := 'T'
  else
    XDataWebDataSet1supplied_by_customer_color_copy.AsString := '';
  if cbPlates.Checked then
    XDataWebDataSet1supplied_by_customer_plates.AsString := 'T'
  else
    XDataWebDataSet1supplied_by_customer_plates.AsString := '';
  if cbSampleCarton.Checked then
    XDataWebDataSet1supplied_by_customer_sample_ca.AsString := 'T'
  else
    XDataWebDataSet1supplied_by_customer_sample_ca.AsString := '';
  if cbEmail.Checked then
     XDataWebDataSet1supplied_by_customer_e_mail.AsString := 'T'
  else
    XDataWebDataSet1supplied_by_customer_e_mail.AsString := '';

  // layout

  if cbExcaliburDie.Checked then
    XDataWebDataSet1layout_excalibur_die.AsString := 'T'
  else
    XDataWebDataSet1layout_excalibur_die.AsString := '';

  // proofing

  if cbPDFFile.Checked then
    XDataWebDataSet1proofing_pdf_file.AsString := 'T'
  else
    XDataWebDataSet1proofing_pdf_file.AsString := '';

  // Mounting
  if cbStickyBak.Checked then
    XDataWebDataSet1mounting_sticky_bak.AsString := 'T'
  else
    XDataWebDataSet1mounting_sticky_bak.AsString := '';

  if cbStickyBak.Checked then
    XDataWebDataSet1mounting_full_mount.AsString := 'T'
  else
    XDataWebDataSet1mounting_full_mount.AsString := '';

  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
    orderJSON.AddPair('ORDER_ID', orderID);

  if mode = 'ADD' then
    ShowNotification('Success:Order Added Successfully!')
  else
    ShowNotification('Success:Order Edited Successfully');
  AddCorrugatedOrder(orderJSON);

end;

procedure TFOrderEntryCorrugated.btnSaveClick(Sender: TObject);
// Converts all the information on the page into a JSON to then send to the server
begin
  if VerifyOrder() then
  begin
    sendOrderToServer();
    ViewMode();
  end;
end;

function TFOrderEntryCorrugated.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 TFOrderEntryCorrugated.btnCopyClick(Sender: TObject);
begin
  mode := 'ADD';
  window.scrollTo(0, 0);
  dtpOrderDate.Date := 0;
  dtpProofDate.Date := 0;
  dtpArtDue.Date := 0;
  dtpPlateDue.Date := 0;
  dtpMountDue.Date := 0;
  dtpShipDate.Date := 0;
  dtpApprovedDate.Date := 0;
  edtOrderNum.Text := '';
  EditMode();
  ShowNotification('Success:Order Successfully Copied');
  window.scrollTo(0, 0);
end;

procedure TFOrderEntryCorrugated.btnDeleteClick(Sender: TObject);
begin
  document.getElementById('modal_body').innerHTML := 'Are you sure you want to delete this order?';
  document.getElementById('btn_confirm_cancel').innerText := 'Cancel';
  document.getElementById('btn_confirm_delete').innerText := 'Delete';
  asm
    var confirmationModal = new bootstrap.Modal(document.getElementById('confirmation_modal'), {
    keyboard: false });
    confirmationModal.show();
  end;
end;

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

procedure TFOrderEntryCorrugated.btnPDFClick(Sender: TObject);
begin
  if mode = 'EDIT' then
    GenerateReportPDF
  else
    showNotification('Failure:Cannot Generate PDF when Adding an Order');
end;

procedure TFOrderEntryCorrugated.btn_confirm_deleteClick(Sender: TObject);
begin
  if  document.getElementById('btn_confirm_delete').innerText = 'Yes' then
  begin
    FViewMain.change := false;
    if OrderID <> '' then
    begin
      FViewMain.ViewOrderEntryCorrugated(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;

[async] procedure TFOrderEntryCorrugated.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.GenerateOrderCorrugatedPDF', [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 TFOrderEntryCorrugated.AddCorrugatedOrder(orderJSON: TJSONObject);
// sends the order JSON object to the server
var
  Response: TXDataClientResponse;
  jsObj: TJSObject;
begin
  Response := await(XDataWebClient1.RawInvokeAsync('ILookupService.AddCorrugatedOrder',
              [orderJSON.ToString]));
  jsObj := JS.TJSObject(Response.Result);
  if mode = 'ADD' then
    OrderID := String(jsObj.Properties['OrderID']);
  mode := 'EDIT';
end;

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

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

end;

procedure TFOrderEntryCorrugated.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 TFOrderEntryCorrugated.WebButton1Click(Sender: TObject);
begin
  addColorRow('','','','');
end;

procedure TFOrderEntryCorrugated.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 TFOrderEntryCorrugated.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 TFOrderEntryCorrugated.btnCloseClick(Sender: TObject);
begin
  FViewMain.ViewOrders('');
end;

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

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

procedure TFOrderEntryCorrugated.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.GetOrder',
        [Order_ID]));
  order :=  TJSObject(xdcResponse.Result);
  data := TJSArray(order['data']);
  XDataWebDataSet1.Close;
  XDataWebDataSet1.SetJsonData(order);
  XDataWebDataSet1.Open;
  if XDataWebDataSet1colors_colors.Value <> '' then
  begin
  colorObject := TJSObject(TJSJSON.parse(XDataWebDataSet1colors_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;

  // Check boxes and 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 (XDataWebDataSet1staff_fields_mount_due.AsString = '') then
    dtpMountDue.Date := StrToDateTime(XDataWebDataSet1staff_fields_mount_due.AsString)
  else
    dtpMountDue.Date := 0;
  if not (XDataWebDataSet1proofing_approved_date.AsString = '') then
    dtpApprovedDate.Date := StrToDateTime(XDataWebDataSet1proofing_approved_date.AsString)
  else
    dtpApprovedDate.Date := 0;

  if XDataWebDataSet1supplied_by_customer_existing_.AsString = 'T'  then
    cbExistingCuttingDie.Checked := true
  else
    cbExistingCuttingDie.Checked := false;
  if XDataWebDataSet1supplied_by_customer_ref_art_a.AsString = 'T'  then
    cbRefArtAPDF.Checked := true
  else
    cbRefArtAPDF.Checked := false;
  if XDataWebDataSet1supplied_by_customer_ref_art_p.AsString = 'T'  then
    cbRefArtPrintCard.Checked := true
  else
    cbRefArtPrintCard.Checked := false;

  // Supplied by customers check boxes

  if XDataWebDataSet1supplied_by_customer_color_copy.AsBoolean then
    cbColorCopy.Checked := true
  else
    cbColorCopy.checked := false;

  if XDataWebDataSet1supplied_by_customer_ftp.AsString <> '' then
  begin
    cbFTP.Checked := true;
  end
  else
    cbFTP.Checked := false;

  if XDataWebDataSet1supplied_by_customer_plates.AsBoolean then
    cbPlates.Checked := true
  else
    cbPlates.Checked := false;

  if XDataWebDataSet1supplied_by_customer_sample_ca.AsBoolean then
    cbSampleCarton.Checked := true
  else
    cbSampleCarton.Checked := false;

  if XDataWebDataSet1supplied_by_customer_e_mail.AsBoolean then
    cbEmail.Checked := true
  else
    cbSampleCarton.Checked := false;

  // layout

  if XDataWebDataSet1layout_excalibur_die.AsBoolean then
    cbExcaliburDie.Checked := true
  else
    cbExcaliburDie.Checked := false;


  // Mounting check boxes
  if XDataWebDataSet1mounting_loose.AsString <> '' then
    cbLoose.Checked := true
  else
    cbLoose.Checked := false;

  if XDataWebDataSet1mounting_sticky_bak.AsString <> '' then
    cbStickyBak.Checked := true
  else
    cbStickyBak.Checked := false;

  if XDataWebDataSet1mounting_full_mount.AsString <> '' then
    cbFullMount.Checked := true
  else
    cbFullMount.Checked := false;

  if XDataWebDataSet1mounting_strip_mount.AsString <> '' then
    cbStripMount.Checked := true
  else
    cbStripMount.Checked := false;

  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 TFOrderEntryCorrugated.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;
  dtpMountDue.Date := 0;
  dtpShipDate.Date := 0;
  dtpApprovedDate.Date := 0;
end;

procedure TFOrderEntryCorrugated.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 TFOrderEntryCorrugated.XDataWebDataSet1AfterEdit(DataSet: TDataSet);
begin
  EditMode();
end;

procedure TFOrderEntryCorrugated.xdwdsQBItemAfterEdit(DataSet: TDataSet);
begin
  EditMode();
end;

procedure TFOrderEntryCorrugated.xdwdsShipToAfterEdit(DataSet: TDataSet);
begin
  EditMode();
end;

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

procedure TFOrderEntryCorrugated.ShowNotification(Notification: string);
var
  splitNotification: TArray<string>;
begin
  console.log(notification);
  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;
    console.log(splitNotification[1]) ;
    lblMessage.Caption := splitNotification[1];
    pnlMessage.ElementHandle.hidden := False;
  end;
end;


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

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

procedure TFOrderEntryCorrugated.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;

procedure TFOrderEntryCorrugated.dtpApprovedDateChange(Sender: TObject);
begin
  EditMode();
end;

procedure TFOrderEntryCorrugated.dtpMountDueChange(Sender: TObject);
begin
  EditMode();
end;

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

procedure TFOrderEntryCorrugated.dtpPlateDueChange(Sender: TObject);
begin
  EditMode();
end;

procedure TFOrderEntryCorrugated.dtpProofDateChange(Sender: TObject);
begin
  EditMode();
end;

procedure TFOrderEntryCorrugated.dtpShipDateChange(Sender: TObject);
begin
  EditMode();
end;

procedure TFOrderEntryCorrugated.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;

initialization
  RegisterClass(TFOrderEntryCorrugated);

end.

