unit uDMMain;

interface

uses
  Winapi.Windows, Winapi.WinSock, System.SysUtils, System.Classes, Data.DB,
  FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf,
  FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async,
  FireDAC.Phys, FireDAC.Phys.MySQL, FireDAC.Phys.MySQLDef, FireDAC.VCLUI.Wait,
  FireDAC.Comp.UI, FireDAC.Comp.Client, FireDAC.Stan.Param, FireDAC.DatS,
  FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet,
  uSecurityCrypto;

type
  TdmMain = class(TDataModule)
    FDConn: TFDConnection;
    FDPhysMySQLDriverLink: TFDPhysMySQLDriverLink;
    FDGUIxWaitCursor: TFDGUIxWaitCursor;
    procedure DataModuleCreate(Sender: TObject);
  private
    FBaseDir: string;
    FConfigFilePath: string;
    FConfig: TDBConnectionConfig;
    FCurrentDoctorID: Integer;
    FCurrentDoctorName: string;
    FCurrentDoctorSpecialty: string;
    FCurrentDoctorColegiado: string;
    FPrivacyMode: Boolean;
    FLastActivityTick: UInt64;
    FLocalPCName: string;
    FLocalIP4: string;
    procedure DetectNetworkIdentity;
  public
    procedure LoadOrInitEncryptedConfig;
    function ConnectDatabase(out AErrorMsg: string): Boolean;
    function TestConnectionConfig(const AConfig: TDBConnectionConfig;
      out AServerInfo, AErrorMsg: string): Boolean;
    procedure SaveAndApplyConfig(const AConfig: TDBConnectionConfig);

    procedure SetParamString(AParam: TFDParam; const AValue: string);
    procedure SetParamMemo(AParam: TFDParam; const AValue: string);
    function GetNextId(const ATableName, AKeyField: string): Integer;

    procedure RegistrarAuditoria(AAccion: Integer; const AComentario: string);
    procedure TouchActivity;
    function IsSessionExpired: Boolean;

    property BaseDir: string read FBaseDir;
    property ConfigFilePath: string read FConfigFilePath;
    property Config: TDBConnectionConfig read FConfig write FConfig;
    property CurrentDoctorID: Integer read FCurrentDoctorID write FCurrentDoctorID;
    property CurrentDoctorName: string read FCurrentDoctorName write FCurrentDoctorName;
    property CurrentDoctorSpecialty: string read FCurrentDoctorSpecialty write FCurrentDoctorSpecialty;
    property CurrentDoctorColegiado: string read FCurrentDoctorColegiado write FCurrentDoctorColegiado;
    property PrivacyMode: Boolean read FPrivacyMode write FPrivacyMode;
    property LocalPCName: string read FLocalPCName;
    property LocalIP4: string read FLocalIP4;
  end;

const
  ACCION_LOGIN            = 1;
  ACCION_LOGOUT           = 2;
  ACCION_VER_PACIENTE     = 5;
  ACCION_VER_VISITA       = 6;
  ACCION_GUARDAR_PACIENTE = 7;
  ACCION_GUARDAR_VISITA   = 8;
  ACCION_CONFIG_SEGURIDAD = 11;
  ACCION_VER_DOCUMENTO    = 28;
  ACCION_ALTA_DOCUMENTO   = 29;

var
  dmMain: TdmMain;

implementation

{%CLASSGROUP 'Vcl.Controls.TControl'}

{$R *.dfm}

procedure TdmMain.DataModuleCreate(Sender: TObject);
begin
  FBaseDir := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0)));
  FConfigFilePath := FBaseDir + 'config\santias_db.enc';
  FCurrentDoctorID := -1;
  FCurrentDoctorName := 'SIN AUTENTICAR';
  FLastActivityTick := GetTickCount64;
  DetectNetworkIdentity;
  LoadOrInitEncryptedConfig;
end;

procedure TdmMain.DetectNetworkIdentity;
var
  LBuf: array[0..255] of Char;
  LSize: DWORD;
  LWSAData: TWSAData;
  LHostEnt: PHostEnt;
  LAddr: PInAddr;
  LAnsiHost: array[0..255] of AnsiChar;
begin
  LSize := 255;
  if GetComputerName(LBuf, LSize) then
    FLocalPCName := Copy( string(LBuf), 1, 30 )
  else
    FLocalPCName := 'CONSULTA-PC';

  FLocalIP4 := '127.0.0.1';
  if WSAStartup($0101, LWSAData) = 0 then
  try
    if gethostname(LAnsiHost, SizeOf(LAnsiHost)) = 0 then
    begin
      LHostEnt := gethostbyname(LAnsiHost);
      if (LHostEnt <> nil) and (LHostEnt^.h_addr_list <> nil) and (LHostEnt^.h_addr_list^ <> nil) then
      begin
        LAddr := PInAddr(LHostEnt^.h_addr_list^);
        FLocalIP4 := string(AnsiString(inet_ntoa(LAddr^)));
      end;
    end;
  finally
    WSACleanup;
  end;
end;

procedure TdmMain.LoadOrInitEncryptedConfig;
begin
  if not TSecurityCrypto.LoadEncryptedConfig(FConfigFilePath, FConfig, FBaseDir) then
  begin
    FConfig := TDBConnectionConfig.CreateDefault(FBaseDir);
    if not FileExists(FConfig.VendorLib) then
    begin
      if FileExists(FBaseDir + '..\libmysql.dll') then
        FConfig.VendorLib := ExpandFileName(FBaseDir + '..\libmysql.dll')
      else if FileExists('c:\fuentes\proyectos delphi\RAUL_ASENCIO\GESTION\libmysql.dll') then
        FConfig.VendorLib := 'c:\fuentes\proyectos delphi\RAUL_ASENCIO\GESTION\libmysql.dll';
    end;
    TSecurityCrypto.SaveEncryptedConfig(FConfigFilePath, FConfig);
  end;
  FPrivacyMode := FConfig.PrivacyMaskDefault;
end;

function TdmMain.ConnectDatabase(out AErrorMsg: string): Boolean;
begin
  Result := False;
  AErrorMsg := '';
  try
    FDConn.Connected := False;
    if (FConfig.VendorLib <> '') and FileExists(FConfig.VendorLib) then
      FDPhysMySQLDriverLink.VendorLib := FConfig.VendorLib;

    FDConn.Params.Clear;
    FDConn.DriverName := 'MySQL';
    FDConn.Params.Values['Server'] := FConfig.Host;
    FDConn.Params.Values['Port'] := IntToStr(FConfig.Port);
    FDConn.Params.Values['Database'] := FConfig.Database;
    FDConn.Params.Values['User_Name'] := FConfig.Username;
    FDConn.Params.Values['Password'] := FConfig.Password;
    FDConn.Params.Values['CharacterSet'] := 'utf8mb4';
    FDConn.Params.Values['LoginTimeout'] := '5';
    FDConn.Connected := True;
    Result := True;
  except
    on E: Exception do
      AErrorMsg := E.Message;
  end;
end;

function TdmMain.TestConnectionConfig(const AConfig: TDBConnectionConfig;
  out AServerInfo, AErrorMsg: string): Boolean;
var
  LTestConn: TFDConnection;
  LQry: TFDQuery;
begin
  Result := False;
  AServerInfo := '';
  AErrorMsg := '';
  LTestConn := TFDConnection.Create(nil);
  try
    try
      if (AConfig.VendorLib <> '') and FileExists(AConfig.VendorLib) then
        FDPhysMySQLDriverLink.VendorLib := AConfig.VendorLib;

      LTestConn.LoginPrompt := False;
      LTestConn.DriverName := 'MySQL';
      LTestConn.Params.Values['Server'] := AConfig.Host;
      LTestConn.Params.Values['Port'] := IntToStr(AConfig.Port);
      LTestConn.Params.Values['Database'] := AConfig.Database;
      LTestConn.Params.Values['User_Name'] := AConfig.Username;
      LTestConn.Params.Values['Password'] := AConfig.Password;
      LTestConn.Params.Values['CharacterSet'] := 'utf8mb4';
      LTestConn.Params.Values['LoginTimeout'] := '5';
      LTestConn.Connected := True;

      LQry := TFDQuery.Create(nil);
      try
        LQry.Connection := LTestConn;
        LQry.SQL.Text :=
          'SELECT VERSION() AS ver, ' +
          '(SELECT COUNT(*) FROM gm_pacientes) AS npac, ' +
          '(SELECT COUNT(*) FROM gm_visitas) AS nvis, ' +
          '(SELECT COUNT(*) FROM gd_documentos) AS ndoc';
        LQry.Open;
        AServerInfo := Format('Motor: %s | Pacientes: %d | Visitas: %d | Documentos: %d',
          [LQry.FieldByName('ver').AsString,
           LQry.FieldByName('npac').AsInteger,
           LQry.FieldByName('nvis').AsInteger,
           LQry.FieldByName('ndoc').AsInteger]);
      finally
        LQry.Free;
      end;
      Result := True;
    except
      on E: Exception do
        AErrorMsg := E.Message;
    end;
  finally
    LTestConn.Free;
  end;
end;

procedure TdmMain.SaveAndApplyConfig(const AConfig: TDBConnectionConfig);
begin
  FConfig := AConfig;
  FPrivacyMode := FConfig.PrivacyMaskDefault;
  TSecurityCrypto.SaveEncryptedConfig(FConfigFilePath, FConfig);
end;

procedure TdmMain.SetParamString(AParam: TFDParam; const AValue: string);
begin
  AParam.DataType := ftWideString;
  if Trim(AValue) = '' then
    AParam.AsWideString := ''
  else
    AParam.AsWideString := AValue;
end;

procedure TdmMain.SetParamMemo(AParam: TFDParam; const AValue: string);
begin
  AParam.DataType := ftWideMemo;
  AParam.AsWideMemo := AValue;
end;

function TdmMain.GetNextId(const ATableName, AKeyField: string): Integer;
var
  LQry: TFDQuery;
begin
  Result := 1;
  if not FDConn.Connected then
    Exit;
  LQry := TFDQuery.Create(nil);
  try
    LQry.Connection := FDConn;
    LQry.SQL.Text := Format('SELECT COALESCE(MAX(%s), 0) + 1 AS next_id FROM %s', [AKeyField, ATableName]);
    LQry.Open;
    if not LQry.IsEmpty then
      Result := LQry.FieldByName('next_id').AsInteger;
  finally
    LQry.Free;
  end;
end;

procedure TdmMain.RegistrarAuditoria(AAccion: Integer; const AComentario: string);
var
  LQry: TFDQuery;
begin
  if not FDConn.Connected then
    Exit;
  LQry := TFDQuery.Create(nil);
  try
    try
      LQry.Connection := FDConn;
      LQry.SQL.Text :=
        'INSERT INTO gl_tabla (FECHA, IP, IP4, USUARIO, ACCION, PC, COMENTARIO) ' +
        'VALUES (NOW(), 0, :ip4, :usu, :acc, :pc, :com)';
      SetParamString(LQry.ParamByName('ip4'), Copy(FLocalIP4, 1, 20));
      LQry.ParamByName('usu').AsInteger := FCurrentDoctorID;
      LQry.ParamByName('acc').AsInteger := AAccion;
      SetParamString(LQry.ParamByName('pc'), Copy(FLocalPCName, 1, 30));
      SetParamString(LQry.ParamByName('com'), Copy(AComentario, 1, 512));
      LQry.ExecSQL;
    except
      // Silencioso en caso de reconexión puntual
    end;
  finally
    LQry.Free;
  end;
end;

procedure TdmMain.TouchActivity;
begin
  FLastActivityTick := GetTickCount64;
end;

function TdmMain.IsSessionExpired: Boolean;
var
  LElapsedSec: UInt64;
begin
  if FConfig.InactivityMinutes <= 0 then
    Exit(False);
  LElapsedSec := (GetTickCount64 - FLastActivityTick) div 1000;
  Result := LElapsedSec >= UInt64(FConfig.InactivityMinutes * 60);
end;

end.

