unit View.ContactUs;

interface

uses
  System.SysUtils, System.Classes, WEBLib.Graphics, WEBLib.Forms, Vcl.StdCtrls,
  WEBLib.StdCtrls, Vcl.Controls, WEBLib.Dialogs, Vcl.Imaging.pngimage,
  WEBLib.ExtCtrls, WEBLib.Controls, Web, JS, WEBLib.Menus, WEBLib.WebCtrls,
  XData.Web.Connection, XData.Web.Client, Data.DB,
  XData.Web.JsonDataset, XData.Web.Dataset, Vcl.Grids,
  WEBLib.DBCtrls, WEBLib.DB, WEBLib.Grids, WEBLib.CDS, WEBLib.REST, Utils,
  WEBLib.WebTools, System.NetEncoding, WEBLib.RegularExpressions,
  WEBLib.Toast, XData.Web.Request, XData.Web.Response;

type
  TFContactUs = class(TWebForm)
    btnHome: TWebButton;
    btnAboutUs: TWebButton;
    btnContactUs: TWebButton;
    btnRecordsManagement: TWebButton;
    btnCustomSoftware: TWebButton;
    btnAboutUsFooter: TWebButton;
    btnHomeFooter: TWebButton;
    btnContactUsFooter: TWebButton;
    edtName: TWebEdit;
    edtEmail: TWebEdit;
    edtSubject: TWebEdit;
    memoMessage: TWebMemo;
    XDataWebConnection1: TXDataWebConnection;
    XDataWebClient1: TXDataWebClient;
    btnSubmit: TWebButton;
    btnPublicSafety: TWebButton;

    procedure btnHomeClick(Sender: TObject);
    procedure btnAboutUsClick(Sender: TObject);
    procedure btnContactUsClick(Sender: TObject);
    procedure btnRecordsManagementClick(Sender: TObject);
    procedure btnCustomSoftwareClick(Sender: TObject);
    procedure btnPublicSafetyClick(Sender: TObject);
    procedure btnSubmitClick(Sender: TObject);
    procedure XDataWebConnection1Connect(Sender: TObject);
    procedure XDataWebClient1Error(error: TXDataClientError);
    procedure XDataWebConnection1Error(error: TXDataWebConnectionError);
    procedure WebFormCreate(Sender: TObject);
    procedure WebFormClose(Sender: TObject; var Action: TCloseAction);
  private
    { Private declarations }
    function IsInputValid: Boolean;
    function IsEmailValid(AEmail: String): Boolean;
    [async] procedure SendEmail;
    [async] procedure InitializeConnection;
  public
    procedure NavScrollSizing;
  end;

var
  FContactUs: TFContactUs;

implementation

{$R *.dfm}

uses
View.AboutUs,
View.Home,
View.CustomSoftware,
View.PublicSafety,
View.RecordsManagement;


procedure TFContactUs.WebFormCreate(Sender: TObject);
begin
  Application.ThemeColor := clTMSWEB;
  NavScrollSizing;
  InitializeConnection;
end;

[async] procedure TFContactUs.InitializeConnection;
var
  Conn: TXDataWebConnection;
  Resp: IHttpResponse;
  Obj: TJSObject;
begin
  try
    Conn := TXDataWebConnection.Create(nil);
    Resp := await(Conn.SendRequestAsync(THttpRequest.Create('config/config.json')));
    Obj := TJSObject(TJSJSON.parse(Resp.ContentAsText));

    XDataWebConnection1.URL := string(Obj['ApiUrl']);
    XDataWebClient1.Connection := XDataWebConnection1;

    console.log('XData connection initialized with URL: ', XDataWebConnection1.URL);
  except
    on E: Exception do
    begin
      ShowMessage('Failed to load configuration or initialize XData: ' + E.Message);
    end;
  end;
end;


procedure TFContactUs.NavScrollSizing;
begin
  asm
    window.addEventListener('scroll', function() {
      var navbar = document.querySelector('.em-navbar-wrap .navbar');
      var logo = document.querySelector('.em-brand img');
      var scrollDistance = 50; // Adjust based on your preference

      if (window.scrollY > scrollDistance) {
        navbar.classList.add('scrolled');
        logo.classList.add('scrolled-logo');
      } else {
        navbar.classList.remove('scrolled');
        logo.classList.remove('scrolled-logo');
      }
    });
  end;
end;

procedure TFContactUs.btnSubmitClick(Sender: TObject);
begin
  if IsInputValid then
  begin
    XDataWebConnection1.Connected := True;
  end
  else
    ShowMessage('Please complete all fields and ensure the email address is valid.');
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
  ShowMessage('Error Connecting to XData Server');
end;


procedure TFContactUs.XDataWebConnection1Connect(Sender: TObject);
begin
  console.log('Connected to XData server, Sending Email');
  SendEmail();
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('IApiService.SendEmail',
      [edtName.Text, edtEmail.Text, edtSubject.Text, memoMessage.Text]));
    ShowMessage('Your message has been sent successfully. Please check your email for a response in the next 48 hours.');
    // 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
      ShowMessage('Error when attempting to send: ' + E.Message);
      // Optionally disconnect even on error if you intend to reset the connection state
      XDataWebConnection1.Connected := False;
    end;
  end;
end;

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


procedure TFContactUs.btnCustomSoftwareClick(Sender: TObject);
begin
  Close;
  Application.CreateForm(TFCustomSoftware, FCustomSoftware);
end;


procedure TFContactUs.btnRecordsManagementClick(Sender: TObject);
begin
  Close;
  Application.CreateForm(TFRecordsManagement, FRecordsManagement);
end;


procedure TFContactUs.btnPublicSafetyClick(Sender: TObject);
begin
  Close;
  Application.CreateForm(TFPublicSafety, FPublicSafety);
end;


procedure TFContactUs.btnContactUsClick(Sender: TObject);
begin
  Close;
  Application.CreateForm(TFContactUs, FContactUs);
end;


procedure TFContactUs.btnAboutUsClick(Sender: TObject);
begin
  Close;
  Application.CreateForm(TFAboutUs, FAboutUs);
end;


procedure TFContactUs.btnHomeClick(Sender: TObject);
begin
  Close;
  Application.CreateForm(TFHome, FHome);
end;


initialization
  RegisterClass(TFContactUs);

end.    