<?php

namespace apexl\Io\services;

use apexl\Config\Singleton;
use PHPMailer\PHPMailer\PHPMailer;

/**
 * @mixin PHPMailer
 */
class Mailer
{
    /** @var PHPMailer */
    public $mail;

    public function __construct()
    {
        $this->mail = new PHPMailer(true);
        $config = Singleton::getInstance();

        //Allow config to set mailer settings.
        if (isset($config->app->email->smtp)) {
            $smtp = $config->app->email->smtp;
            $this->mail->isSMTP();
            $this->mail->Host = $smtp->host;
            $this->mail->SMTPAuth = $smtp->auth ?? true;
            $this->mail->Username = $smtp->username;
            $this->mail->Password = $smtp->password;
            $this->mail->SMTPSecure = $smtp->encryption ?? PHPMailer::ENCRYPTION_STARTTLS;
            $this->mail->Port = $smtp->port ?? 587;
            $this->mail->From = $smtp->from ?? sprintf(
                'noreply@%s',
                preg_replace(
                    ['#^https?://#', '#:\d+$#'],
                    '',
                    (string) $config->app->site->frontend_domain,
                )
            );
        }
    }

    public function __get($name)
    {
        return $this->mail->$name;
    }

    public function __set($name, $value)
    {
        $this->mail->$name = $value;
    }

    /**
     * @param $name
     * @param $arguments
     * @return mixed
     */
    public function __call($name, $arguments)
    {
        try {
            //pass-through calls to $this->mail
            if (!empty($arguments)) {
                return $this->mail->$name(...$arguments);
            } else {
                return $this->mail->$name();
            }
        } catch (\Exception $e) {
            error_log("[IO Exception :: Mailer] -".$e->getCode()." | ".$e->getMessage());

            return $e;
        }
    }
}
