<?php
/**
 * SendTestMail Artisan Command
 *
 * @version     1.0.$Revision:$
 * @version     SVN: $Id:$
 * @package     bplan-base/globals
 * @subpackage  Commands
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 * @copyright   Copyright (C) 2025, 2026 bplan-solutions GmbH & Co. KG <https://www.bplan-solutions.de/>
 * /Δ\
 */

namespace BplanBase\Globals\Console\Commands;


use BplanBase\Globals\Mail\PHPMailer;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;


/**
 * SendTestMail Artisan Command
 *
 * @version     2.0.0 / 2026-07-22
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 */
class SendTestMail extends Command
{


/* +++ TRAITS +++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */


/* +++ CLASS CONSTANTS +++ ++++++++++++++++++++++++++++++++++++++++++++++++ */


/* +++ OBJECT MEMBERS +++ +++++++++++++++++++++++++++++++++++++++++++++++++ */


    /**
     * @var string
     */
    protected $description = 'Sends a test e-mail to a given address using the current .env mail configuration';


    /**
     * @var string
     */
    protected $signature = 'globals:send-test-mail {email? : The recipient e-mail address} {--method= : Mail method to test (all|laravel|phpmailer)}';


/* +++ CLASS MEMBERS +++ ++++++++++++++++++++++++++++++++++++++++++++++++++ */


/* +++ OBJECT METHODS +++ +++++++++++++++++++++++++++++++++++++++++++++++++ */


    /**
     * Sends a test mail via the Laravel-native mail transport (Mail::raw()).
     *
     * @param       string $email
     *
     * @return      bool
     *
     * @version     1.0.0 / 2026-07-22
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    private function _sendLaravelMail(string $email): bool
    {
        $this->info('Sending test mail via Laravel Mail to ['.$email.']');
        $this->info(' Mail driver:  '.config('mail.default'));
        $this->info(' Mail host  :  '.config('mail.mailers.'.config('mail.default').'.host', '[none]'));
        $this->info(' Mail from  :  '.config('mail.from.address'));
        $this->newLine();

        try {
            Mail::raw(
                'This is a test e-mail sent via the ['.$this->signature.'] Artisan command (Laravel Mail).'
                    ."\n\n".'Mail driver: '.config('mail.default')
                    ."\n".'Sent at    : '.now()->toDateTimeString(),

                function ($message) use ($email): void {
                    $message->to($email)->subject('Globals – Test Mail (Laravel Mail) – '.config('app.name'));
                }
            );
        } catch (\Throwable $E) {
            $this->error('Failed to send mail via Laravel Mail: '.$E->getMessage());

            return false;
        }
        $this->info('Test mail sent successfully via Laravel Mail.');

        return true;

    } // _sendLaravelMail()


    /**
     * Sends a test mail via the PHPMailer class from the Globals package.
     *
     * @param       string $email
     *
     * @return      bool
     *
     * @version     1.0.0 / 2026-07-22
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    private function _sendPhpMailerMail(string $email): bool
    {
        $this->info('Sending test mail via PHPMailer to ['.$email.']');
        $this->info(' Mail driver:  '.config('mail.default'));
        $this->info(' SMTP host  :  '.config('mail.mailers.smtp.host', '[none]'));
        $this->info(' Mail from  :  '.config('mail.from.address'));
        $this->newLine();

        try {
            $Mailer = new PHPMailer(true);
            $Mailer->addAddress($email);
            $Mailer->isHTML(true);

            $Mailer->Subject = 'Globals – Test Mail (PHPMailer) – '.config('app.name');
            $Mailer->Body = 'This is a test e-mail sent via the ['.$this->signature.'] Artisan command using the PHPMailer class.'
                .'<br><br>Mail driver: '.config('mail.default')
                .'<br>Sent at    : '.now()->toDateTimeString();
            $Mailer->AltBody = strip_tags(str_replace('<br>', "\n", $Mailer->Body));

            $Mailer->send();
        } catch (\Throwable $E) {
            $this->error('Failed to send mail via PHPMailer: '.$E->getMessage());

            return false;
        }
        $this->info('Test mail sent successfully via PHPMailer.');

        return true;

    } // _sendPhpMailerMail()


    /**
     * Execute the console command.
     *
     * @version     1.1.0 / 2026-07-22
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function handle(): int
    {
        $email = $this->argument('email');

        if (empty($email) === true) {
            $email = $this->ask('Recipient e-mail address');
        }

        if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
            $this->error('Invalid e-mail address ['.$email.']');

            return self::FAILURE;
        }
        $method = $this->option('method');

        if (empty($method) === false && in_array($method, ['all', 'laravel', 'phpmailer'], true) === false) {
            $this->error('Invalid method ['.$method.'], falling back to selection menu.');

            $method = null;
        }

        if (empty($method) === true) {
            $method = $this->choice(
                'Which mail method should be tested?',
                [
                    'all'       => 'Both (Laravel Mail + PHPMailer)',
                    'laravel'   => 'Laravel Mail (Mail::raw)',
                    'phpmailer' => 'PHPMailer',
                ],
                'all'
            );
        }
        $this->newLine();

        $success = true;

        if (in_array($method, ['all', 'laravel'], true) === true) {
            $success = ($this->_sendLaravelMail($email) === true) && $success;
            $this->newLine();
        }

        if (in_array($method, ['all', 'phpmailer'], true) === true) {
            $success = ($this->_sendPhpMailerMail($email) === true) && $success;
        }

        return ($success === true) ? self::SUCCESS : self::FAILURE;

    } // handle()


/* +++ CLASS METHODS +++ ++++++++++++++++++++++++++++++++++++++++++++++++++ */


} // class SendTestMail extends Command {}
