<?php

namespace apexl\Io\services;

use apexl\Config\Singleton;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

/**
 * @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)){
            $this->mail->isSMTP();
            $this->mail->Host = $config->app->email->smtp->host;
            $this->mail->SMTPAuth = $config->app->email->smtp->auth ?? true;
            $this->mail->Username = $config->app->email->smtp->username;
            $this->mail->Password = $config->app->email->smtp->password;
            $this->mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $this->mail->Port = $config->app->email->smtp->port ?? 587;
        }
    }

    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;
        }
    }
}
