 unit View.ContactUs;

interface

uses
  System.SysUtils, System.Classes, JS, Web, WEBLib.Graphics, WEBLib.Controls,
  WEBLib.Forms, WEBLib.Dialogs, XData.Web.Client, XData.Web.Connection, Data.DB,
  XData.Web.JsonDataset, XData.Web.Dataset, Vcl.Controls, Vcl.Grids,
  WEBLib.DBCtrls, WEBLib.DB, WEBLib.Grids, Vcl.StdCtrls, WEBLib.StdCtrls,
  WEBLib.ExtCtrls, WEBLib.CDS, WEBLib.REST, WebLib.RegularExpressions, WEBLib.Menus,
  Utils, WEBLib.JSON, App.Config;

type
  TFContactUs = class(TWebForm)
    btnHome: TWebButton;
    btnCompliance: TWebButton;
    btnContactUs: TWebButton;
    btnSubmit: TWebButton;
    edtName: TWebEdit;
    edtEmail: TWebEdit;
    memoMessage: TWebMemo;
    edtSubject: TWebEdit;
    XDataWebConnection1: TXDataWebConnection;
    XDataWebClient1: TXDataWebClient;
    procedure WebFormClose(Sender: TObject; var Action: TCloseAction);
    procedure btnSubmitClick(Sender: TObject);
    procedure XDataWebClient1Error(error: TXDataClientError);
    procedure XDataWebConnection1Error(error: TXDataWebConnectionError);
    procedure XDataWebConnection1Request(Args: TXDataWebConnectionRequest);
    procedure WebFormCreate(Sender: TObject);
  private
    { Private declarations }
    function IsInputValid: Boolean;
    function IsEmailValid(AEmail: String): Boolean;
    [async] procedure SendEmail;
    procedure InitConnection;
  public
    { Public declarations }
  end;

var
  FContactUs: TFContactUs;

implementation

{$R *.dfm}

const
  tstSuccess = 'Email sent successfully';
  tstError = 'Error when attempting to send: ';

procedure TFContactUs.XDataWebConnection1Request(Args: TXDataWebConnectionRequest);
// var
//   basicAuthStr: string;
//   coder: TBase64Encoding;
begin
  // try
  //   coder := TBase64Encoding.Create;
  //   basicAuthStr := coder.Encode( 'admin:password' );
  // finally
  //   coder.Free;
  // end;

  // Args.Request.Headers.SetValue( 'Authorization', 'Basic ' + basicAuthStr );
end;


procedure TFContactUs.btnSubmitClick(Sender: TObject);
begin
  if IsInputValid then
  begin
    ShowSpinner('spinner');

    if XDataWebConnection1.Connected then
    begin
      SendEmail;
    end
    else
    begin
      XDataWebConnection1.Open(
        procedure
        begin
          console.log('Connected to API at ' + XDataWebConnection1.URL);
          SendEmail;
        end
      );
    end;
  end
  else
  begin
    ShowToast('Please complete all fields and ensure the email address is valid.', 'danger');
  end;
end;



procedure TFContactUs.WebFormClose(Sender: TObject; var Action: TCloseAction);
begin
  Action := caFree;
end;


procedure TFContactUs.WebFormCreate(Sender: TObject);
begin
  InitConnection;
end;


procedure TFContactUs.InitConnection;
begin
  LoadConfig(
    procedure(Config: TAppConfig)
    begin
      if Config.ApiUrl <> '' then
        XDataWebConnection1.URL := Config.ApiUrl
      else
        XDataWebConnection1.URL := 'https://webapps.em-sys.net/EFX/';

      XDataWebConnection1.Open(
        procedure
        begin
          console.log('Connected to API at ' + XDataWebConnection1.URL);
        end
      );
    end
  );
end;


function TFContactUs.IsEmailValid(AEmail: String): Boolean;
const
  CPattern = '^\w+([\.-]?w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$';
begin
  Result := TRegEx.IsMatch( AEmail, CPattern );
end;

function TFContactUs.IsInputValid: Boolean;
var
  LEmailValid: Boolean;
  LComplete: Boolean;

begin
  LEmailValid := IsEmailValid( edtEmail.Text );

  LComplete := (edtName.Text <> '') and
  (edtSubject.Text <> '') and
  (edtEmail.Text <> '');

  Result := LEmailValid and LComplete;

end;


procedure TFContactUs.XDataWebConnection1Error(error: TXDataWebConnectionError);
begin
  console.log('Problem with the XDataWebConnection.');
  ShowToast('There was an error. Please contact us by phone.', 'danger');
end;


procedure TFContactUs.XDataWebClient1Error(Error: TXDataClientError);
begin
  console.log('Error: ', Error.ErrorMessage, ' RequestId: ', Error.RequestId, ' Code: ', Error.ErrorCode, ' Request Url: ', Error.RequestUrl);
end;

procedure TFContactUs.SendEmail;
var
  xdcResponse: TXDataClientResponse;
begin
  try
    xdcResponse := await(XDataWebClient1.RawInvokeAsync('IEmailService.SendEmail',
      [edtName.Text, edtEmail.Text, edtSubject.Text, memoMessage.Text]));
    ShowToast('Your message has been sent successfully. Please check your email for a response in the next 48 hours.', 'success');

    // Clears the input fields after successful email sending
    edtName.Text := '';
    edtEmail.Text := '';
    edtSubject.Text := '';
    memoMessage.Text := '';

    // Disconnects after sending the email
    XDataWebConnection1.Connected := False;

  except
    on E: EXDataClientRequestException do
    begin
      console.log('Error in TFContactUs.XDataWebClient1Error: ' + E.Message);
      ShowToast('There was an error. Please contact us by phone.', 'danger');
      // Optionally disconnect even on error if you intend to reset the connection state
      XDataWebConnection1.Connected := False;
    end;
  end;
  HideSpinner('spinner');
end;


initialization
  RegisterClass(TFContactUs);

end.
