﻿unit frm_SelectCompany;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Buttons,
  Data.DB, FireDAC.Comp.Client;

type
  TfrmSelectCompany = class(TForm)
    pnlMain: TPanel;
    lblTitle: TLabel;
    cbCompanies: TComboBox;
    btnOk: TBitBtn;
    procedure FormShow(Sender: TObject);
    procedure btnOkClick(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    FCompanyIds: TStringList; // Lista paralela con los IDs de empresa
    procedure CenterOnActiveMonitor; // Método para posicionar el formulario

  public
    { Public declarations }
  end;

var
  frmSelectCompany: TfrmSelectCompany;

implementation

uses
  System.IniFiles, dmg_Main, uAppTheme;

{$R *.dfm}
procedure TfrmSelectCompany.CenterOnActiveMonitor;
var
  LMonitor: TMonitor;
begin
  // Evitamos que Delphi use la posición por defecto del diseño del DFM
  Self.Position := poDesigned;

  // 1. Intentamos obtener el monitor donde está el cursor del ratón (el más intuitivo para el usuario)
  LMonitor := Screen.MonitorFromPoint(Mouse.CursorPos);

  // 2. Si hay un formulario activo en la aplicación, usamos ese monitor en su lugar
  if Assigned(Screen.ActiveForm) and (Screen.ActiveForm <> Self) then
    LMonitor := Screen.MonitorFromWindow(Screen.ActiveForm.Handle);

  // Centramos este formulario en las coordenadas del monitor detectado
  Self.Left := LMonitor.Left + (LMonitor.Width - Self.Width) div 2;
  Self.Top := LMonitor.Top + (LMonitor.Height - Self.Height) div 2;
end;


procedure TfrmSelectCompany.btnOkClick(Sender: TObject);
var
  LIni: TIniFile;
  LIniPath: string;
begin
  if (cbCompanies.ItemIndex >= 0) and (FCompanyIds.Count > cbCompanies.ItemIndex) then
  begin
    dmgMain.CurrentCompanyId := FCompanyIds[cbCompanies.ItemIndex];
    dmgMain.CurrentCompanyName := cbCompanies.Text;
    
    // Guardar la última empresa seleccionada en db_config.ini
    LIniPath := ExtractFilePath(ParamStr(0)) + 'db_config.ini';
    LIni := TIniFile.Create(LIniPath);
    try
      LIni.WriteString('LastAccess', 'CompanyId', dmgMain.CurrentCompanyId);
    finally
      LIni.Free;
    end;
    
    ModalResult := mrOk;
  end
  else
    ShowMessage('Por favor, selecciona una empresa para continuar.');
end;

procedure TfrmSelectCompany.FormDestroy(Sender: TObject);
begin
  FreeAndNil(FCompanyIds);
end;

procedure TfrmSelectCompany.FormShow(Sender: TObject);
var
  LIni: TIniFile;
  LIniPath: string;
  LLastCompanyId: string;
  LIdx: Integer;
  I: Integer;
begin
  TAppTheme.ApplyToForm(Self);

  if not Assigned(FCompanyIds) then
    FCompanyIds := TStringList.Create
  else
    FCompanyIds.Clear;

  // Cargar empresas desde la BD
  dmgMain.qryExec.Close;
  dmgMain.qryExec.SQL.Text := 'SELECT id, nombre FROM ge_empresas WHERE activo = true ORDER BY nombre';
  dmgMain.qryExec.Open;

  cbCompanies.Items.Clear;
  while not dmgMain.qryExec.Eof do
  begin
    cbCompanies.Items.Add(dmgMain.qryExec.FieldByName('nombre').AsString);
    FCompanyIds.Add(Trim(TdmgMain.CleanUUID(dmgMain.qryExec.FieldByName('id').AsString)));
    dmgMain.qryExec.Next;
  end;
  dmgMain.qryExec.Close;

  if cbCompanies.Items.Count = 1 then
  begin
    cbCompanies.ItemIndex := 0;
    btnOkClick(nil);
  end
  else if cbCompanies.Items.Count = 0 then
    ShowMessage('No se han encontrado empresas activas. Contacte con el administrador.')
  else
  begin
    // Cargar la última empresa seleccionada de db_config.ini
    LIniPath := ExtractFilePath(ParamStr(0)) + 'db_config.ini';
    if FileExists(LIniPath) then
    begin
      LIni := TIniFile.Create(LIniPath);
      try
        LLastCompanyId := Trim(LIni.ReadString('LastAccess', 'CompanyId', ''));
      finally
        LIni.Free;
      end;
      
      if LLastCompanyId <> '' then
      begin
        LIdx := -1;
        for I := 0 to FCompanyIds.Count - 1 do
        begin
          if SameText(FCompanyIds[I], LLastCompanyId) then
          begin
            LIdx := I;
            Break;
          end;
        end;
        if LIdx >= 0 then
          cbCompanies.ItemIndex := LIdx;
      end;
    end;
  end;
end;

end.
