<?php

namespace apexl\Io\services;

use apexl\Config\Configuration;
use PHPMailer\PHPMailer\PHPMailer;

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

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

        //Allow config to set mailer settings.
        if (config('smtp')) {
            $this->mail->isSMTP();
            $this->mail->Host = config('smtp.host');
            $this->mail->SMTPAuth = config('smtp.auth', true);
            $this->mail->Username = config('smtp.username');
            $this->mail->Password = config('smtp.password');
            $this->mail->SMTPSecure = config('smtp.encryption', PHPMailer::ENCRYPTION_STARTTLS);
            $this->mail->Port = config('smtp.port');
            $this->mail->From = config('smtp.from');
        }
    }

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