unit Email.ServiceImpl;

interface

uses
  XData.Server.Module,
  XData.Service.Common,

  IdSMTP, IdMessage, IdSSLOpenSSL, IdText, IdExplicitTLSClientServerBase,
  IdIOHandlerSocket, IdException, IdSSL, IdSMTPBase, IdGlobal, IdStack, IdWinsock2,
  IdStackConsts, IdIOHandler, IdIOHandlerStack, IdBaseComponent,
  IdComponent, IdTCPConnection, IdTCPClient, IdMessageClient,

  Email.Service;

type
  [ServiceImplementation]
  TEmailService = class(TInterfacedObject, IEmailService)
  public
    function SendEmail(Name, Email, Subject, Body: string): string;
  end;

implementation

uses
  System.SysUtils,
  System.IniFiles,
  Main;


function TEmailService.SendEmail(Name, Email, Subject, Body: string): string;
var
  SMTP: TIdSMTP;
  Message: TIdMessage;
  SSL: TIdSSLIOHandlerSocketOpenSSL;
  EFXIni: TIniFile;
  IniPath: string;
begin
  // Load the .ini file that matches the executable's name (e.g. EFXEmailServer.ini)
  IniPath := ChangeFileExt(ParamStr(0), '.ini');
  if not FileExists(IniPath) then
    raise Exception.Create('Configuration file not found: ' + IniPath);

  EFXIni := TIniFile.Create(IniPath);
  try
    SMTP := TIdSMTP.Create(nil);
    try
      Message := TIdMessage.Create(nil);
      try
        if not EFXIni.SectionExists('SMTP') then
          raise Exception.Create('Configuration section [SMTP] not found in ' + IniPath);

        SMTP.Host := EFXIni.ReadString('SMTP', 'Host', '');
        if SMTP.Host = '' then
          raise Exception.Create('SMTP Host is not configured.');

        SMTP.Port := EFXIni.ReadInteger('SMTP', 'Port', 0);
        if SMTP.Port = 0 then
          raise Exception.Create('SMTP Port is not configured or invalid.');

        SMTP.Username := EFXIni.ReadString('SMTP', 'Username', '');
        if SMTP.Username = '' then
          raise Exception.Create('SMTP Username is not configured.');

        SMTP.Password := EFXIni.ReadString('SMTP', 'Password', '');
        if SMTP.Password = '' then
          raise Exception.Create('SMTP Password is not configured.');

        Message.From.Address := EFXIni.ReadString('SMTP', 'FromEmail', '');
        if Message.From.Address = '' then
          raise Exception.Create('SMTP FromEmail is not configured.');

        Message.Recipients.EmailAddresses := EFXIni.ReadString('SMTP', 'RecipientEmail', '');
        if Message.Recipients.EmailAddresses = '' then
          raise Exception.Create('SMTP RecipientEmail is not configured.');

        Message.Subject := Subject;
        Message.Body.Text := Format(
        '<html>' +
        '<body style="font-family: Arial, sans-serif; font-size: 14px;">' +
          '<h3>New Contact Us Form Submission</h3>' +
          '<table cellpadding="6" cellspacing="0" border="0">' +
            '<tr><td><strong>Name:</strong></td><td>%s</td></tr>' +
            '<tr><td><strong>Email:</strong></td><td>%s</td></tr>' +
            '<tr><td><strong>Subject:</strong></td><td>%s</td></tr>' +
            '<tr valign="top"><td><strong>Message:</strong></td><td>%s</td></tr>' +
            '<tr><td><strong>Timestamp:</strong></td><td>%s</td></tr>' +
          '</table>' +
        '</body>' +
        '</html>',
        [Name, Email, Subject, Body.Replace(sLineBreak, '<br>'), DateTimeToStr(Now)]
      );
        Message.ContentType := 'text/html';

        // SSL and TLS setup
        SSL := TIdSSLIOHandlerSocketOpenSSL.Create(SMTP);
        SMTP.IOHandler := SSL;
        SMTP.UseTLS := utUseImplicitTLS;

        // Send the email
        SMTP.Connect;
        SMTP.Send(Message);
        SMTP.Disconnect;

        // Optional logging
        FMain.ContactFormData('Email Data:' + sLineBreak +
                              'Name: ' + Name + sLineBreak +
                              'Email: ' + Email + sLineBreak +
                              'Subject: ' + Subject + sLineBreak +
                              'Message: ' + Body);

        Result := 'Email sent successfully';
      finally
        Message.Free;
      end;
    finally
      SMTP.Free;
    end;
  finally
    EFXIni.Free;
  end;
end;


initialization
  RegisterServiceType(TEmailService);

end.

