unit uConfigForm;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, uConfig, 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, Data.DB,
  FireDAC.Comp.Client, System.IOUtils, Vcl.FileCtrl, uDM;

type
  TCompanyItem = class
  public
    Id: string;
    Nombre: string;
    constructor Create(const AId, ANombre: string);
  end;

  TfrmConfig = class(TForm)
    GroupBoxDB: TGroupBox;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    Label4: TLabel;
    Label5: TLabel;
    edtServer: TEdit;
    edtDB: TEdit;
    edtUser: TEdit;
    edtPass: TEdit;
    edtPort: TEdit;
    btnTestDB: TButton;
    GroupBoxPaths: TGroupBox;
    LabelRecepcion: TLabel;
    edtPathRecepcion: TEdit;
    btnSelRecepcion: TButton;
    LabelFacturas: TLabel;
    edtPathFacturas: TEdit;
    btnSelFacturas: TButton;
    LabelAlbaranes: TLabel;
    edtPathAlbaranes: TEdit;
    btnSelAlbaranes: TButton;
    LabelTrabajadores: TLabel;
    edtPathTrabajadores: TEdit;
    btnSelTrabajadores: TButton;
    LabelErrores: TLabel;
    edtPathErrores: TEdit;
    btnSelErrores: TButton;
    Label9: TLabel;
    cmbIdEmpresa: TComboBox;
    GroupBoxNotif: TGroupBox;
    lblEmailError: TLabel;
    lblCuentaError: TLabel;
    edtEmailError: TEdit;
    cmbCuentaError: TComboBox;
    pnlBottom: TPanel;
    btnSave: TButton;
    btnCancel: TButton;
    procedure btnTestDBClick(Sender: TObject);
    procedure btnSaveClick(Sender: TObject);
    procedure btnCancelClick(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure btnSelRecepcionClick(Sender: TObject);
    procedure btnSelFacturasClick(Sender: TObject);
    procedure btnSelAlbaranesClick(Sender: TObject);
    procedure btnSelTrabajadoresClick(Sender: TObject);
    procedure btnSelErroresClick(Sender: TObject);
  private
    procedure CargarCuentasEnvio;
    procedure CargarEmpresas;
    function SelectPath(const ACurrent: string): string;
  public
    { Public declarations }
    destructor Destroy; override;
  end;

var
  frmConfig: TfrmConfig;

implementation

{$R *.dfm}

{ TCompanyItem }

constructor TCompanyItem.Create(const AId, ANombre: string);
begin
  Id := AId;
  Nombre := ANombre;
end;

{ TfrmConfig }

destructor TfrmConfig.Destroy;
var
  Idx: Integer;
begin
  for Idx := 0 to cmbIdEmpresa.Items.Count - 1 do
    if cmbIdEmpresa.Items.Objects[Idx] <> nil then
      cmbIdEmpresa.Items.Objects[Idx].Free;
  for Idx := 0 to cmbCuentaError.Items.Count - 1 do
    if cmbCuentaError.Items.Objects[Idx] <> nil then
      cmbCuentaError.Items.Objects[Idx].Free;
  inherited Destroy;
end;

procedure TfrmConfig.btnCancelClick(Sender: TObject);
begin
  ModalResult := mrCancel;
end;

procedure TfrmConfig.btnSaveClick(Sender: TObject);
var
  NewConfig: TAppConfig;
begin
  NewConfig := Config; 
  
  NewConfig.DBServer := edtServer.Text;
  NewConfig.DBName   := edtDB.Text;
  NewConfig.DBUser   := edtUser.Text;
  NewConfig.DBPass   := edtPass.Text;
  NewConfig.DBPort   := StrToIntDef(edtPort.Text, 3306);
  
  NewConfig.PathRecepcion    := edtPathRecepcion.Text;
  NewConfig.PathFacturas     := edtPathFacturas.Text;
  NewConfig.PathAlbaranes    := edtPathAlbaranes.Text;
  NewConfig.PathTrabajadores := edtPathTrabajadores.Text;
  NewConfig.PathErrores     := edtPathErrores.Text;
  
  if cmbIdEmpresa.ItemIndex > -1 then
    NewConfig.IdEmpresa := TCompanyItem(cmbIdEmpresa.Items.Objects[cmbIdEmpresa.ItemIndex]).Id
  else
    NewConfig.IdEmpresa := '1';
  
  // Notificaciones
  NewConfig.EmailErrorDestino := edtEmailError.Text;
  if (cmbCuentaError.ItemIndex > -1) and (TCompanyItem(cmbCuentaError.Items.Objects[cmbCuentaError.ItemIndex]).Id <> '') then
    NewConfig.IdConfigEnvioError := TCompanyItem(cmbCuentaError.Items.Objects[cmbCuentaError.ItemIndex]).Id
  else
    NewConfig.IdConfigEnvioError := '';
  
  TConfigHelper.SaveConfig(NewConfig);
  ModalResult := mrOk;
end;

procedure TfrmConfig.CargarCuentasEnvio;
var
  Q: TFDQuery;
  Idx: Integer;
begin
  for Idx := 0 to cmbCuentaError.Items.Count - 1 do
    if cmbCuentaError.Items.Objects[Idx] <> nil then
      cmbCuentaError.Items.Objects[Idx].Free;
  cmbCuentaError.Items.Clear;
  
  cmbCuentaError.Items.AddObject('-- Sin notificación --', TCompanyItem.Create('', '-- Sin notificación --'));
  
  Q := TFDQuery.Create(nil);
  try
    Q.Connection := DM.FDConnection;
    Q.SQL.Text := 'SELECT id, nombre_perfil FROM ge_config_envio ORDER BY nombre_perfil';
    Q.Open;
    while not Q.Eof do
    begin
      cmbCuentaError.Items.AddObject(Q.FieldByName('nombre_perfil').AsString, 
                                     TCompanyItem.Create(Q.FieldByName('id').AsString, Q.FieldByName('nombre_perfil').AsString));
      Q.Next;
    end;
    
    // Seleccionar la actual
    cmbCuentaError.ItemIndex := 0;
    for Idx := 0 to cmbCuentaError.Items.Count - 1 do
    begin
      if TCompanyItem(cmbCuentaError.Items.Objects[Idx]).Id = Config.IdConfigEnvioError then
      begin
        cmbCuentaError.ItemIndex := Idx;
        Break;
      end;
    end;
  finally
    Q.Free;
  end;
end;

procedure TfrmConfig.CargarEmpresas;
var
  Q: TFDQuery;
  Idx: Integer;
begin
  for Idx := 0 to cmbIdEmpresa.Items.Count - 1 do
    if cmbIdEmpresa.Items.Objects[Idx] <> nil then
      cmbIdEmpresa.Items.Objects[Idx].Free;
  cmbIdEmpresa.Items.Clear;

  Q := TFDQuery.Create(nil);
  try
    Q.Connection := DM.FDConnection;
    Q.SQL.Text := 'SELECT id, nombre FROM ge_empresas ORDER BY nombre';
    Q.Open;
    while not Q.Eof do
    begin
      cmbIdEmpresa.Items.AddObject(Q.FieldByName('nombre').AsString, 
        TCompanyItem.Create(Q.FieldByName('id').AsString, Q.FieldByName('nombre').AsString));
      Q.Next;
    end;
    
    // Seleccionar la actual
    cmbIdEmpresa.ItemIndex := -1;
    for Idx := 0 to cmbIdEmpresa.Items.Count - 1 do
    begin
      if TCompanyItem(cmbIdEmpresa.Items.Objects[Idx]).Id = Config.IdEmpresa then
      begin
        cmbIdEmpresa.ItemIndex := Idx;
        Break;
      end;
    end;
    
    if (cmbIdEmpresa.ItemIndex = -1) and (cmbIdEmpresa.Items.Count > 0) then
      cmbIdEmpresa.ItemIndex := 0;
  finally
    Q.Free;
  end;
end;

procedure TfrmConfig.btnSelAlbaranesClick(Sender: TObject);
begin
  edtPathAlbaranes.Text := SelectPath(edtPathAlbaranes.Text);
end;

procedure TfrmConfig.btnSelErroresClick(Sender: TObject);
begin
  edtPathErrores.Text := SelectPath(edtPathErrores.Text);
end;

procedure TfrmConfig.btnSelFacturasClick(Sender: TObject);
begin
  edtPathFacturas.Text := SelectPath(edtPathFacturas.Text);
end;

procedure TfrmConfig.btnSelRecepcionClick(Sender: TObject);
begin
  edtPathRecepcion.Text := SelectPath(edtPathRecepcion.Text);
end;

procedure TfrmConfig.btnSelTrabajadoresClick(Sender: TObject);
begin
  edtPathTrabajadores.Text := SelectPath(edtPathTrabajadores.Text);
end;

procedure TfrmConfig.btnTestDBClick(Sender: TObject);
var
  Conn: TFDConnection;
begin
  Conn := TFDConnection.Create(nil);
  try
    Conn.DriverName := 'MySQL';
    Conn.Params.Values['Server']   := edtServer.Text;
    Conn.Params.Values['Database'] := edtDB.Text;
    Conn.Params.Values['User_Name'] := edtUser.Text;
    Conn.Params.Values['Password'] := edtPass.Text;
    Conn.Params.Values['Port']     := edtPort.Text;
    Conn.LoginPrompt := False;
    
    try
      Conn.Connected := True;
      ShowMessage('Conexión establecida con éxito.');
    except
      on E: Exception do
        ShowMessage('Error al conectar: ' + E.Message);
    end;
  finally
    Conn.Free;
  end;
end;

procedure TfrmConfig.FormShow(Sender: TObject);
begin
  edtServer.Text := Config.DBServer;
  edtDB.Text     := Config.DBName;
  edtUser.Text   := Config.DBUser;
  edtPass.Text   := Config.DBPass;
  edtPort.Text   := Config.DBPort.ToString;
  
  edtPathRecepcion.Text    := Config.PathRecepcion;
  edtPathFacturas.Text     := Config.PathFacturas;
  edtPathAlbaranes.Text    := Config.PathAlbaranes;
  edtPathTrabajadores.Text := Config.PathTrabajadores;
  edtPathErrores.Text     := Config.PathErrores;
  
  CargarEmpresas;
  
  // Notificaciones
  edtEmailError.Text := Config.EmailErrorDestino;
  CargarCuentasEnvio;
end;

function TfrmConfig.SelectPath(const ACurrent: string): string;
var
  Dir: string;
begin
  Result := ACurrent;
  if SelectDirectory('Seleccionar carpeta', '', Dir, [sdNewUI, sdNewFolder]) then
    Result := Dir;
end;

end.
