unit Main;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, Menus, StdCtrls, ExtCtrls, ComCtrls, jpeg, Buttons, rpgraphicex,HTMLHelpapi;

type
  TfrmMain = class(TForm)
    Mainmnu: TMainMenu;
    System: TMenuItem;
    mnuLogIn: TMenuItem;
    mnuLogOut: TMenuItem;
    N1: TMenuItem;
    mnuExit: TMenuItem;
    Manage: TMenuItem;
    Account: TMenuItem;
    particulars2: TMenuItem;
    View: TMenuItem;
    History1: TMenuItem;
    Help: TMenuItem;
    About: TMenuItem;
    Services: TMenuItem;
    StatusBar1: TStatusBar;
    Timer1: TTimer;
    Services1: TMenuItem;
    HeaderControl1: THeaderControl;
    imgMain: TImage;
    gbLogin: TGroupBox;
    Panel1: TPanel;
    Image1: TImage;
    Label1: TLabel;
    txtUname: TEdit;
    Label2: TLabel;
    txtPass: TEdit;
    btnLogin: TBitBtn;
    btnCancel: TBitBtn;
    Reports: TMenuItem;
    Daily1: TMenuItem;
    submnuMyProfile: TMenuItem;
    submnuAllAcc: TMenuItem;
    Help1: TMenuItem;
    axPayer1: TMenuItem;
    
    procedure mnuLogInClick(Sender: TObject);
    procedure Client1Click(Sender: TObject);
    procedure mnuExitClick(Sender: TObject);
    procedure particulars2Click(Sender: TObject);
    procedure History1Click(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure Timer1Timer(Sender: TObject);
    procedure Services1Click(Sender: TObject);
    procedure mnuLogOutClick(Sender: TObject);
    procedure connectDb;
    procedure FormShow(Sender: TObject);
    procedure AboutClick(Sender: TObject);
    procedure GuideClick(Sender: TObject);
    procedure btnLoginClick(Sender: TObject);
    procedure btnCancelClick(Sender: TObject);
    procedure txtUnameKeyPress(Sender: TObject; var Key: Char);
    procedure txtPassKeyPress(Sender: TObject; var Key: Char);
    procedure logIn();
    procedure Clear();
    procedure dsplayStatus();
    procedure Daily1Click(Sender: TObject);
    procedure Weekly1Click(Sender: TObject);
    procedure MyProfile1Click(Sender: TObject);
    procedure submnuMyProfileClick(Sender: TObject);
    procedure submnuAllAccClick(Sender: TObject);
    procedure SetTrackingNumber1Click(Sender: TObject);
    procedure SetTrackingNumber2Click(Sender: TObject);
    procedure writeDB();
    procedure Help1Click(Sender: TObject);
    procedure axPayer1Click(Sender: TObject);


  private
    { Private declarations }
  public
    { Public declarations }
    username:string;
    password:string;
    fullname:string;
    access:string;
    status:string;
    pk:string;
    path:String;
    rep:String;
  end;

  type
   TWordTriple = Array[0..2] of Word;
    function FileEncrypt(InFile, OutFile: String; Key: TWordTriple): boolean;
    function FileDecrypt(InFile, OutFile: String; Key: TWordTriple): boolean;
    function TextEncrypt(const s: string; Key: TWordTriple): string;
    function TextDecrypt(const s: string; Key: TWordTriple): string;
    function MemoryEncrypt(Src: Pointer; SrcSize: Cardinal; Target: Pointer; TargetSize: Cardinal; Key:TWordTriple): boolean;
    function MemoryDecrypt(Src: Pointer; SrcSize: Cardinal; Target: Pointer; TargetSize: Cardinal; Key:TWordTriple): boolean;


var
  frmMain: TfrmMain;

  sysDate : TDateTime;
  Date : string;

implementation

uses LogIn, AccountInformation, Particulars, History,
   DM, Services, AboutCRATS, Guide, TaxPayerDetails, DailyReport, WeeklyReport, Profile,
  Report,SetTracking, SetTrackName, DBConfig, taxPayerForm;

{$R *.dfm}

function MemoryEncrypt(Src: Pointer; SrcSize: Cardinal; Target: Pointer; TargetSize: Cardinal; Key: TWordTriple): boolean;
var
  pIn, pOut: ^byte;
  i : Cardinal;
begin
    if SrcSize = TargetSize then
    begin
        pIn := Src;
        pOut := Target;
        for i := 1 to SrcSize do
        begin
          pOut^ := pIn^ xor (Key[2] shr 8);
          Key[2] := Byte(pIn^ + Key[2]) * Key[0] + Key[1];
          inc(pIn);
          inc(pOut);
        end;
              Result := True;
    end else
              Result := False;
end;

function MemoryDecrypt(Src: Pointer; SrcSize: Cardinal; Target: Pointer; TargetSize: Cardinal; Key: TWordTriple): boolean;
var
  pIn, pOut: ^byte;
  i : Cardinal;
begin
  if SrcSize = TargetSize then
  begin
    pIn := Src;
    pOut := Target;
    for i := 1 to SrcSize do
    begin
      pOut^ := pIn^ xor (Key[2] shr 8);
      Key[2] := byte(pOut^ + Key[2]) * Key[0] + Key[1];
      inc(pIn);
      inc(pOut);
    end;
    Result := True;
  end else
    Result := False;
end;

function TextCrypt(const s: string; Key: TWordTriple; Encrypt: Boolean): string;
var
  bOK: Boolean;
begin
  SetLength(Result, Length(s));
  if Encrypt then
    bOK := MemoryEncrypt(PChar(s), Length(s), PChar(Result), Length(Result), Key)
  else
    bOK := MemoryDecrypt(PChar(s), Length(s), PChar(Result), Length(Result), Key);
  if not bOK then Result := '';
end;

function FileCrypt(InFile, OutFile: String; Key: TWordTriple; Encrypt: Boolean): boolean;
var
  MIn, MOut: TMemoryStream;
begin
  MIn := TMemoryStream.Create;
  MOut := TMemoryStream.Create;
  Try
    MIn.LoadFromFile(InFile);
    MOut.SetSize(MIn.Size);
    if Encrypt then
      Result := MemoryEncrypt(MIn.Memory, MIn.Size, MOut.Memory, MOut.Size, Key)
    else
      Result := MemoryDecrypt(MIn.Memory, MIn.Size, MOut.Memory, MOut.Size, Key);
    MOut.SaveToFile(OutFile);
  finally
    MOut.Free;
    MIn.Free;
  end;
end;
function TextEncrypt(const s: string; Key: TWordTriple): string;
begin
  Result := TextCrypt(s, Key, True);
end;

function TextDecrypt(const s: string; Key: TWordTriple): string;
begin
  Result := TextCrypt(s, Key, False);
end;

function FileEncrypt(InFile, OutFile: String; Key: TWordTriple): boolean;
begin
  Result := FileCrypt(InFile, OutFile, Key, True);
end;

function FileDecrypt(InFile, OutFile: String; Key: TWordTriple): boolean;
begin
  Result := FileCrypt(InFile, OutFile, Key, False);
end;

procedure TfrmMain.connectDb;
var dbName, dbPass : String;
    dbPath : TextFile;
    lbDate:string;
begin
    Try
        AssignFile(dbPath,'CRATS.ini') ;
        Reset(dbPath);
        ReadLn(dbPath, dbName);
        DModule.DB.DatabaseName := dbName;
        ReadLn(dbPath, dbPass);
        DModule.DB.PassWord := dbPass;
            DateTimeToString(DateTime, 'dddddd',now());
            lbDate:=DateTime;
            StatusBar1.Panels.Items[2].Text:='Date: ' + DateToStr(now);
        DModule.DB.Connected := true;
        CloseFile(dbPath);
    Except
        ON e: Exception do begin
            ShowMessage('Error: Database file not found or contains wrong configuration. Module will now close. ');
            {if MessageDlg('Do you want to check error?',mtConfirmation,[mbYes,mbNo],0)=mrYes then begin
               frmDBConfig.show;
            end
            else
              Close;  }
        end
    end;

end;
procedure TfrmMain.writeDB();
var dbPath:TextFile;
begin
        AssignFile(dbPath,'CRATS.ini');
        Rewrite(dbPath);
        Writeln(dbPath,path+'\CRATS.FDB');
        Writeln(dbPath,'masterkey');
        CloseFile(dbPath);
end;
procedure TfrmMain.FormShow(Sender: TObject);
begin
        path:=GetCurrentDir;
        rep:=GetCurrentDir+'\reports\';
        writeDB;
        connectDb;
end;
procedure TfrmMain.Timer1Timer(Sender: TObject);
begin
    StatusBar1.Panels.Items[3].Text:='Time: '+TimeToStr(Now);
end;

procedure TfrmMain.mnuLogInClick(Sender: TObject);
begin
    gbLogin.Visible := True;
    txtUname.SetFocus;
end;

procedure TfrmMain.Client1Click(Sender: TObject);
begin
    frmUserInformation.showModal;
end;

procedure TfrmMain.mnuExitClick(Sender: TObject);
begin
    if MessageDlg('Do you want to close this application?',mtConfirmation,[mbYes, mbNo], 0)= mrYes then
       application.Terminate
    else

end;

procedure TfrmMain.particulars2Click(Sender: TObject);
begin
      frmParticularss.Show;
end;


procedure TfrmMain.History1Click(Sender: TObject);
begin
    frmHistory.showModal;
end;

procedure TfrmMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
    if MessageDlg('Do you want close this application?',mtConfirmation,[mbYes, mbNo], 0)= mrYes then
      Exit
    else
      Action:=caNone; //do nothing
end;

procedure TfrmMain.Services1Click(Sender: TObject);
begin
     frmServices.Show;
end;
procedure TfrmMain.mnuLogOutClick(Sender: TObject);
begin
      if MessageDlg('Do you want to log out?',mtConfirmation,[mbYes,mbNo],0)= mrYes then begin
        frmMain.StatusBar1.Panels.Items[0].Text:= 'Log Out';
        frmMain.StatusBar1.Panels.Items[1].Text:= 'Log Out';
        frmMain.mnuLogIn.Enabled:=true;
        frmMain.mnuLogOut.Enabled:=false;
        frmMain.Services.Enabled:=false;
        frmMain.View.Enabled:=false;
        frmMain.Manage.Enabled:=False;
        frmMain.Reports.Enabled:=False;
      end
end;

procedure TfrmMain.AboutClick(Sender: TObject);
begin
      frmAboutCRATS.showModal;
end;

procedure TfrmMain.GuideClick(Sender: TObject);
begin
    frmGuide.showmodal;

end;

procedure TfrmMain.btnLoginClick(Sender: TObject);
begin
      dsplayStatus();
      logIn();
      frmMain.mnuLogOut.Enabled:=true;
      frmMain.mnuLogIn.Enabled:=False;
      if(access = 'Administrator') AND (status = '1')then begin
          frmMain.Services.Enabled:=true;
          frmMain.Manage.Enabled:=true;
          frmMain.View.Enabled:=true;
          frmMain.Reports.Enabled:=True;
          frmTaxPayerDetails.gbTaxPayerDetails.Enabled:=False;

      end
      else if (access <> 'Administrator') AND (status = '1') then begin
          frmMain.submnuAllAcc.Enabled:=false;
          frmMain.Services.Enabled:=true;
          frmMain.Manage.Enabled:=true;
          frmMain.Particulars2.Enabled:=false;
          frmMain.View.Enabled:=true;
          frmMain.Reports.Enabled:= True;
          frmTaxPayerDetails.gbTaxPayerDetails.Enabled:=False;
          frmTaxPayerDetails.btnEdit.Visible:= False;
          frmTaxPayerDetails.btnCancel.Visible:=False;
      end
      else begin
         frmMain.mnuLogIn.Enabled:=True;
      end
end;

procedure TfrmMain.btnCancelClick(Sender: TObject);
begin
      Clear();
      gbLogin.Visible := False;
end;

procedure TfrmMain.logIn();
var
    endec:TWordTriple;
begin
    endec[0]:=1000;
    endec[1]:=9292;
    endec[2]:=3333;

    if(username <> trim(txtUname.Text)) or (password <> Trim(TextEncrypt(txtPass.Text, endec))) or (status='0') then
    begin
        MessageDlg('Invalid Username or Password.'+#13#10+' Or maybe account has been DeActivated.'+#13#10+' Please contact the administrator to ReActivate your account',mtError,[mbOK],0);
    end
    else if(txtUname.Text= '') then
    begin
        MessageDlg('Field(s) required',mtError,[mbOK],0);
        txtUname.SetFocus;
    end
    else if(txtPass.Text= '') then
    begin
        MessageDlg('Field(s) required',mtError,[mbOK],0);
        txtPass.SetFocus;
    end

    else begin 

    if DModule.TR.InTransaction then
       DModule.TR.Commit;

        DModule.QR.SQL.Clear();
        DModule.QR.SQL.Add('SELECT * ');
        DModule.QR.SQL.Add('FROM usersInfo WHERE Username =:a AND uPAssword=:b');
        DModule.QR.Prepare;
        DModule.QR.open();
          username := DModule.QR.Fields.AsString[5];
          password := DModule.QR.Fields.AsString[6];
          status   := DModule.QR.Fields.AsString[10];

    if DModule.TR.InTransaction then
        DModule.TR.Commit;
    dsplayStatus();
    StatusBar1.Panels.Items[0].Text := ''+ access;
    StatusBar1.Panels.Items[1].Text:= ''+ fullname ;
    Clear;
    gbLogin.Visible := False;
    end
end;

procedure TfrmMain.Clear();
begin
    txtUname.Clear;
    txtPass.Clear;
end;

procedure TfrmMain.dsplayStatus();
  var endec:TWordTriple;
begin
    endec[0]:=1000;
    endec[1]:=9292;
    endec[2]:=3333;

      if DModule.TR.InTransaction then //if naai open nga connection kanang wla na close ang connection
       DModule.TR.Commit;            //e close or e commit niya

    DModule.QR.SQL.Clear();
    DModule.QR.SQL.Add('SELECT * ');
    DModule.QR.SQL.Add('FROM usersInfo WHERE Username =:a AND uPAssword=:b');
      DModule.QR.Params.AsString[0]:= Trim(txtUname.Text);
      DModule.QR.Params.AsString[1]:=Trim(TextEncrypt(txtPass.Text, endec));
    DModule.QR.Prepare;
    DModule.QR.open();

   username := DModule.QR.Fields.AsString[5];
   password:= DModule.QR.Fields.AsString[6];
   fullname := DModule.QR.Fields.AsString[1];
   access:=DModule.QR.Fields.AsString[8];
   status   := DModule.QR.Fields.AsString[10];
   pk:= DModule.QR.Fields.AsString[0];

    if DModule.TR.InTransaction then
        DModule.TR.Commit;

end;

//KEYPRESS
procedure TfrmMain.txtUnameKeyPress(Sender: TObject; var Key: Char);
begin
      if Key = #13 then begin
        SelectNext(Sender as tWinControl, True, True );
      if Sender = txtUname then
        btnLogin.Click; // let the button click itself
        Key := #0;
      end;
end;

procedure TfrmMain.txtPassKeyPress(Sender: TObject; var Key: Char);
begin
      if Key = #13 then begin
        SelectNext(Sender as tWinControl, True, True );
      if Sender = txtPass then
        btnLogin.Click; // let the button click itself
        Key := #0;
      end;
end;

procedure TfrmMain.Daily1Click(Sender: TObject);
begin
         frmReport.ShowModal;
end;

procedure TfrmMain.Weekly1Click(Sender: TObject);
begin
      frmWeeklyReport.Show;
end;

procedure TfrmMain.MyProfile1Click(Sender: TObject);
begin
  frmProfile.ShowModal;
end;

procedure TfrmMain.submnuMyProfileClick(Sender: TObject);
begin
      frmProfile.ShowModal;
end;

procedure TfrmMain.submnuAllAccClick(Sender: TObject);
begin
      frmUserInformation.showModal;
end;

procedure TfrmMain.SetTrackingNumber1Click(Sender: TObject);
begin
      frmSetTrackName.ShowModal;
end;

procedure TfrmMain.SetTrackingNumber2Click(Sender: TObject);
begin
      frmSetTracking.ShowModal;
end;

procedure TfrmMain.Help1Click(Sender: TObject);
begin
      HtmlHelpShowContents;
end;

procedure TfrmMain.axPayer1Click(Sender: TObject);
begin
      frmtaxPayer.ShowModal;
end;

end.
