unit uEnviarDocumento;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, FireDAC.Comp.Client, Data.DB;

type
  TEmailProfileItem = class
  public
    Id: string;
    NombrePerfil: string;
    constructor Create(const AId, ANombre: string);
  end;

  TfEnviarDocumento = class(TForm)
    pnlBottom: TPanel;
    btnEnviar: TButton;
    btnCancelar: TButton;
    GroupBox1: TGroupBox;
    chkEmail: TCheckBox;
    Label1: TLabel;
    edtEmailDestino: TEdit;
    Label2: TLabel;
    edtEmailAsunto: TEdit;
    Label3: TLabel;
    mmoEmailMensaje: TMemo;
    lblAdjunto: TLabel;
    btnVerPDF: TButton;
    btnConfigurar: TButton;
    pnlTop: TPanel;
    Label6: TLabel;
    cboCuentasEnvio: TComboBox;
    Label4: TLabel;
    edtEmailCopia: TEdit;
    procedure cboCuentasEnvioChange(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure chkEmailClick(Sender: TObject);
    procedure chkWhatsAppClick(Sender: TObject);
    procedure btnCancelarClick(Sender: TObject);
    procedure btnEnviarClick(Sender: TObject);
    procedure btnVerPDFClick(Sender: TObject);
    procedure btnConfigurarClick(Sender: TObject);
    procedure FormShow(Sender: TObject);
  private
    { Private declarations }
    FRutaPDF: string;
    procedure ConfigurarUI;
    procedure CargarCuentas;
  public
    { Public declarations }
    destructor Destroy; override;
    property RutaPDF: string read FRutaPDF write FRutaPDF;
    procedure InitData(const ATelefono, AEmail, ACCO, AAsuntoDefault: string; const AReportName: string);
  end;

var
  fEnviarDocumento: TfEnviarDocumento;

implementation

{$R *.dfm}

uses uEmailWhatsApp, Winapi.ShellAPI, uConfigEmail, uDM;

{ TEmailProfileItem }

constructor TEmailProfileItem.Create(const AId, ANombre: string);
begin
  Id := AId;
  NombrePerfil := ANombre;
end;

{ TfEnviarDocumento }

destructor TfEnviarDocumento.Destroy;
var
  Idx: Integer;
begin
  for Idx := 0 to cboCuentasEnvio.Items.Count - 1 do
    if cboCuentasEnvio.Items.Objects[Idx] <> nil then
      cboCuentasEnvio.Items.Objects[Idx].Free;
  inherited Destroy;
end;

procedure TfEnviarDocumento.FormCreate(Sender: TObject);
begin
  CargarCuentas;
  ConfigurarUI;
end;

procedure TfEnviarDocumento.FormShow(Sender: TObject);
var
  SelID: string;
  SmtpHost, SmtpUsuario, SmtpPassword, SmtpNombre: string;
  SmtpPuerto, WaModo: Integer;
  SmtpSSL: Boolean;
  WaTelefono, WaApiKey, TplEmailAsunto, TplEmailCuerpo, TplWaMensaje, FirmaHTML: string;
begin
  if cboCuentasEnvio.ItemIndex = -1 then Exit;
  SelID := TEmailProfileItem(cboCuentasEnvio.Items.Objects[cboCuentasEnvio.ItemIndex]).Id;

  // Recargar plantillas según la cuenta elegida
  LeerConfiguracion(SelID, SmtpHost, SmtpPuerto, SmtpSSL, SmtpUsuario, SmtpPassword, SmtpNombre,
    WaModo, WaTelefono, WaApiKey, TplEmailAsunto, TplEmailCuerpo, TplWaMensaje, FirmaHTML);
  edtEmailCopia.Text := SmtpUsuario;
end;

procedure TfEnviarDocumento.CargarCuentas;
var
  Qry: TFDQuery;
  Idx: Integer;
begin
  // Limpiar cuentas anteriores
  for Idx := 0 to cboCuentasEnvio.Items.Count - 1 do
    if cboCuentasEnvio.Items.Objects[Idx] <> nil then
      cboCuentasEnvio.Items.Objects[Idx].Free;
  cboCuentasEnvio.Items.Clear;

  Qry := TFDQuery.Create(nil);
  try
    Qry.Connection := DM.FDConnection;
    Qry.SQL.Text := 'SELECT id, nombre_perfil FROM config_envio ORDER BY nombre_perfil';
    Qry.Open;
    while not Qry.Eof do
    begin
      cboCuentasEnvio.Items.AddObject(Qry.FieldByName('nombre_perfil').AsString, 
        TEmailProfileItem.Create(Qry.FieldByName('id').AsString, Qry.FieldByName('nombre_perfil').AsString));
      Qry.Next;
    end;
  finally
    Qry.Free;
  end;

  if cboCuentasEnvio.Items.Count > 0 then
  begin
    cboCuentasEnvio.ItemIndex := 0;
    cboCuentasEnvioChange(Self);
  end;
end;

procedure TfEnviarDocumento.InitData(const ATelefono, AEmail, ACCO, AAsuntoDefault: string; const AReportName: string);
begin
  edtEmailDestino.Text := AEmail;
  edtEmailCopia.Text := ACCO;
  if AAsuntoDefault <> '' then
  begin
    // Reemplazar la variable {documento} en el asunto
    edtEmailAsunto.Text := StringReplace(edtEmailAsunto.Text, '{documento}', AAsuntoDefault, [rfReplaceAll, rfIgnoreCase]);
  end;

  if Trim(AEmail) <> '' then chkEmail.Checked := True;
  
  lblAdjunto.Caption := 'Adjunto: ' + ExtractFileName(FRutaPDF);
  ConfigurarUI;
end;

procedure TfEnviarDocumento.ConfigurarUI;
begin
  edtEmailDestino.Enabled := chkEmail.Checked;
  edtEmailCopia.Enabled := chkEmail.Checked;
  edtEmailAsunto.Enabled := chkEmail.Checked;
  mmoEmailMensaje.Enabled := chkEmail.Checked;
  btnEnviar.Enabled := chkEmail.Checked;
end;

procedure TfEnviarDocumento.chkEmailClick(Sender: TObject);
begin
  ConfigurarUI;
end;

procedure TfEnviarDocumento.chkWhatsAppClick(Sender: TObject);
begin
  ConfigurarUI;
end;

procedure TfEnviarDocumento.btnCancelarClick(Sender: TObject);
begin
  Close;
end;

procedure TfEnviarDocumento.btnVerPDFClick(Sender: TObject);
begin
  if FileExists(FRutaPDF) then
    ShellExecute(0, 'open', PChar(FRutaPDF), nil, nil, SW_SHOWNORMAL)
  else
    MessageDlg('El archivo PDF no se ha encontrado: ' + FRutaPDF, mtError, [mbOK], 0);
end;

procedure TfEnviarDocumento.btnEnviarClick(Sender: TObject);
var
  LErrorMsg: string;
  LSmtpHost, LSmtpUsuario, LSmtpPassword, LSmtpNombre: string;
  LSmtpPuerto, LWaModo: Integer;
  LSmtpSSL: Boolean;
  LGlobalWaTelefono, LWaApiKey, LTpl1, LTpl2, LTpl3, LFirmaHTML: string;
  LEnvioEmailOk: Boolean;
  LTotalMensaje: string;
  LSelConfigID: string;
  LListaCompleta: string;
begin
  LEnvioEmailOk := False;
  LTotalMensaje := '';
  
  if cboCuentasEnvio.ItemIndex = -1 then
  begin
    MessageDlg('Debe seleccionar una cuenta de envío.', mtError, [mbOK], 0);
    Exit;
  end;
  
  LSelConfigID := TEmailProfileItem(cboCuentasEnvio.Items.Objects[cboCuentasEnvio.ItemIndex]).Id;

  if not FileExists(FRutaPDF) then
  begin
    MessageDlg('El archivo PDF adjunto no existe.', mtError, [mbOK], 0);
    Exit;
  end;

  // 1. Enviar Email si está marcado
  if chkEmail.Checked and ((Trim(edtEmailDestino.Text) <> '') or (Trim(edtEmailCopia.Text) <> '')) then
  begin
    Screen.Cursor := crHourGlass;
    try
      LListaCompleta := Trim(edtEmailDestino.Text);
      if Trim(edtEmailCopia.Text) <> '' then
      begin
        if LListaCompleta <> '' then LListaCompleta := LListaCompleta + ';';
        LListaCompleta := LListaCompleta + edtEmailCopia.Text;
      end;

      if EnviarEmailsIndividuales(LSelConfigID, LListaCompleta, edtEmailAsunto.Text, mmoEmailMensaje.Text, FRutaPDF, LErrorMsg) then
      begin
        LEnvioEmailOk := True;
        LTotalMensaje := LTotalMensaje + 'Emails enviados correctamente.' + #13#10;
      end
      else
        LTotalMensaje := LTotalMensaje + 'Fallo en Email: ' + LErrorMsg + #13#10;
    finally
      Screen.Cursor := crDefault;
    end;
  end;

  if LTotalMensaje = '' then LTotalMensaje := 'Operación finalizada.';
  MessageDlg(LTotalMensaje, mtInformation, [mbOK], 0);
  ModalResult := mrOk;
end;

procedure TfEnviarDocumento.btnConfigurarClick(Sender: TObject);
begin
  with TfConfigEmail.Create(Self) do
  try
    ShowModal;
  finally
    Free;
  end;
  CargarCuentas;
end;

procedure TfEnviarDocumento.cboCuentasEnvioChange(Sender: TObject);
var
  SelID: string;
  SmtpHost, SmtpUsuario, SmtpPassword, SmtpNombre: string;
  SmtpPuerto, WaModo: Integer;
  SmtpSSL: Boolean;
  WaTelefono, WaApiKey, TplEmailAsunto, TplEmailCuerpo, TplWaMensaje, FirmaHTML: string;
begin
  if cboCuentasEnvio.ItemIndex = -1 then Exit;
  SelID := TEmailProfileItem(cboCuentasEnvio.Items.Objects[cboCuentasEnvio.ItemIndex]).Id;

  // Recargar plantillas según la cuenta elegida
  LeerConfiguracion(SelID, SmtpHost, SmtpPuerto, SmtpSSL, SmtpUsuario, SmtpPassword, SmtpNombre,
    WaModo, WaTelefono, WaApiKey, TplEmailAsunto, TplEmailCuerpo, TplWaMensaje, FirmaHTML);
      
    edtEmailAsunto.Text := TplEmailAsunto;
    mmoEmailMensaje.Text := TplEmailCuerpo;

  if (edtEmailCopia.Text = '') or (Pos(';', edtEmailCopia.Text) = 0) then
    edtEmailCopia.Text := SmtpUsuario
  else
  begin
    edtEmailCopia.Text := SmtpUsuario + ';' + Copy(edtEmailCopia.Text, Pos(';', edtEmailCopia.Text) + 1, MaxInt);
  end;
end;

end.
