unit frm_AlmacenesEditor;

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, FireDAC.Stan.Param, uAppTheme, uBaseForm,
  Vcl.ComCtrls, Vcl.Grids, Vcl.DBGrids;

type
  TfrmAlmacenesEditor = class(TfrmBase)
    lblId: TLabel;
    edtId: TEdit;
    lblDescripcion: TLabel;
    edtDescripcion: TEdit;
    chkActivo: TCheckBox;
    chkCompartido: TCheckBox;
    procedure FormShow(Sender: TObject);
    procedure btnSaveClick(Sender: TObject);
    procedure btnSalirClick(Sender: TObject);
  protected
    procedure DoAnadir; override;
    procedure DoModificar; override;
    procedure DoPrimero; override;
    procedure DoAnterior; override;
    procedure DoSiguiente; override;
    procedure DoUltimo; override;
  private
    FAlmacenId: string;
    FParentForm: TForm;
    procedure LoadData;
  public
    property AlmacenId: string read FAlmacenId write FAlmacenId;
    property ParentForm: TForm read FParentForm write FParentForm;
  end;

var
  frmAlmacenesEditor: TfrmAlmacenesEditor;

implementation

uses
  dmg_Main, uDbErrorHandler, frm_Almacenes;

{$R *.dfm}

procedure TfrmAlmacenesEditor.FormShow(Sender: TObject);
begin
  TAppTheme.ApplyToForm(Self);

  btnGuardar.OnClick := btnSaveClick;
  btnSalir.OnClick := btnSalirClick;

  pgcDetails.Visible := True;
  TsListado.TabVisible := False;
  pgcDetails.ActivePage := tsDatosEnvio;
  pnlSideToolbar.Visible := False;
  dbgItems.Visible := False;
  pnlFooter.Visible := False;

  edtId.ReadOnly := True;
  edtId.Color := clBtnFace;

  if FAlmacenId <> '' then
    LoadData
  else
    DoAnadir;
end;

procedure TfrmAlmacenesEditor.LoadData;
begin
  if FAlmacenId = '' then Exit;

  dmgMain.qryExec.Close;
  dmgMain.qryExec.SQL.Text := 'SELECT id, descripcion, activo, compartido FROM ge_almacenes WHERE id = :id';
  dmgMain.qryExec.ParamByName('id').AsString := FAlmacenId;
  dmgMain.qryExec.Open;
  
  if not dmgMain.qryExec.IsEmpty then
  begin
    edtId.Text := FAlmacenId;
    edtDescripcion.Text := dmgMain.qryExec.FieldByName('descripcion').AsString;
    chkActivo.Checked := dmgMain.qryExec.FieldByName('activo').AsInteger <> 0;
    chkCompartido.Checked := dmgMain.qryExec.FieldByName('compartido').AsInteger <> 0;
  end;
  dmgMain.qryExec.Close;
end;

procedure TfrmAlmacenesEditor.DoAnadir;
begin
  FAlmacenId := '';
  edtId.Text := '(Nuevo)';
  edtDescripcion.Clear;
  chkActivo.Checked := True;
  chkCompartido.Checked := False;
  edtDescripcion.SetFocus;
end;

procedure TfrmAlmacenesEditor.DoModificar;
begin
  edtDescripcion.SetFocus;
end;

procedure TfrmAlmacenesEditor.DoPrimero;
var
  LParent: TfrmAlmacenes;
begin
  LParent := nil;
  if Assigned(FParentForm) and (FParentForm is TfrmAlmacenes) then
    LParent := TfrmAlmacenes(FParentForm)
  else if Assigned(frmAlmacenes) then
    LParent := frmAlmacenes;

  if Assigned(LParent) and Assigned(LParent.QryMain) and not LParent.QryMain.IsEmpty then
  begin
    LParent.QryMain.First;
    FAlmacenId := LParent.QryMain.FieldByName('id').AsString;
    LoadData;
  end;
end;

procedure TfrmAlmacenesEditor.DoAnterior;
var
  LParent: TfrmAlmacenes;
begin
  LParent := nil;
  if Assigned(FParentForm) and (FParentForm is TfrmAlmacenes) then
    LParent := TfrmAlmacenes(FParentForm)
  else if Assigned(frmAlmacenes) then
    LParent := frmAlmacenes;

  if Assigned(LParent) and Assigned(LParent.QryMain) and not LParent.QryMain.IsEmpty then
  begin
    LParent.QryMain.Prior;
    FAlmacenId := LParent.QryMain.FieldByName('id').AsString;
    LoadData;
  end;
end;

procedure TfrmAlmacenesEditor.DoSiguiente;
var
  LParent: TfrmAlmacenes;
begin
  LParent := nil;
  if Assigned(FParentForm) and (FParentForm is TfrmAlmacenes) then
    LParent := TfrmAlmacenes(FParentForm)
  else if Assigned(frmAlmacenes) then
    LParent := frmAlmacenes;

  if Assigned(LParent) and Assigned(LParent.QryMain) and not LParent.QryMain.IsEmpty then
  begin
    LParent.QryMain.Next;
    FAlmacenId := LParent.QryMain.FieldByName('id').AsString;
    LoadData;
  end;
end;

procedure TfrmAlmacenesEditor.DoUltimo;
var
  LParent: TfrmAlmacenes;
begin
  LParent := nil;
  if Assigned(FParentForm) and (FParentForm is TfrmAlmacenes) then
    LParent := TfrmAlmacenes(FParentForm)
  else if Assigned(frmAlmacenes) then
    LParent := frmAlmacenes;

  if Assigned(LParent) and Assigned(LParent.QryMain) and not LParent.QryMain.IsEmpty then
  begin
    LParent.QryMain.Last;
    FAlmacenId := LParent.QryMain.FieldByName('id').AsString;
    LoadData;
  end;
end;

procedure TfrmAlmacenesEditor.btnSalirClick(Sender: TObject);
begin
  Close;
end;

procedure TfrmAlmacenesEditor.btnSaveClick(Sender: TObject);
var
  LIsNew: Boolean;
begin
  if Trim(edtDescripcion.Text) = '' then
  begin
    ShowMessage('Debe introducir la descripción del almacén.');
    edtDescripcion.SetFocus;
    Exit;
  end;

  LIsNew := (FAlmacenId = '');
  try
    dmgMain.qryExec.Close;
    if LIsNew then
    begin
      dmgMain.qryExec.SQL.Text := 
        'INSERT INTO ge_almacenes (descripcion, activo, compartido, id_empresa, id_user_creator, id_user_update) ' +
        'VALUES (:des, :act, :comp, :emp, :user, :user)';
    end
    else
    begin
      dmgMain.qryExec.SQL.Text := 
        'UPDATE ge_almacenes SET descripcion = :des, activo = :act, compartido = :comp, ' +
        'id_user_update = :user, updated_at = CURRENT_TIMESTAMP ' +
        'WHERE id = :id';
      dmgMain.qryExec.ParamByName('id').AsString := FAlmacenId;
    end;
    dmgMain.qryExec.ParamByName('des').AsString := Trim(edtDescripcion.Text);
    dmgMain.qryExec.ParamByName('act').AsInteger := Ord(chkActivo.Checked);
    dmgMain.qryExec.ParamByName('comp').AsInteger := Ord(chkCompartido.Checked);
    
    if LIsNew then
      dmgMain.qryExec.ParamByName('emp').AsString := dmgMain.CurrentCompanyId;
      
    dmgMain.qryExec.ParamByName('user').AsString := dmgMain.CurrentUserId;
    
    dmgMain.qryExec.ExecSQL;
    
    if LIsNew then
    begin
      dmgMain.qryExec.Close;
      dmgMain.qryExec.SQL.Text := 'SELECT LAST_INSERT_ID() as new_id';
      dmgMain.qryExec.Open;
      FAlmacenId := dmgMain.qryExec.FieldByName('new_id').AsString;
      edtId.Text := FAlmacenId;
      dmgMain.qryExec.Close;
    end;
    
    ResetChangeTracking;
    ShowMessage('Almacén guardado correctamente.');

    if Assigned(FParentForm) and (FParentForm is TfrmAlmacenes) then
    begin
      TfrmAlmacenes(FParentForm).btnRefreshClick(nil);
      TfrmAlmacenes(FParentForm).QryMain.Locate('id', FAlmacenId, []);
    end;
  except
    on E: Exception do
      TDbErrorHandler.HandleException(E, 'Error al guardar el almacén');
  end;
end;

end.
