<?php

namespace Shm\ShmEmail;

use Shm\ShmDB\mDB;
use Shm\ShmUtils\Config;
use Shm\ShmUtils\ShmInit;

class ShmEmail
{

    public $mailTo;
    public $subject;
    public $body;

    public static function create()
    {
        return new self();
    }

    public function mailTo($mailTo)
    {
        $this->mailTo = $mailTo;
        return $this;
    }

    public function subject($subject)
    {
        $this->subject = $subject;
        return $this;
    }

    public function body($body)
    {
        $this->body = $body;
        return $this;
    }

    public function sendAsync()
    {

        if (!$this->mailTo || !$this->subject || !$this->body) {
            return;
        }

        mDB::collection("shm_email_queue")->insertOne([
            "mailTo" => $this->mailTo,
            "subject" => $this->subject,
            "body" => $this->body,
        ]);
    }
    public function send()
    {

        try {

            if (!$this->mailTo || !$this->subject || !$this->body) {
                return;
            }


            $host  = Config::get('smtp.host', null);
            $port  =  Config::get('smtp.port', null);
            $username  = Config::get('smtp.username', null);
            $password  = Config::get('smtp.password', null);
            $encryption  = Config::get('smtp.encryption', null);
            $from_email  = Config::get('smtp.from_email', null);
            $from_name  = Config::get('smtp.from_name', null);

            if (!$host || !$port || !$username || !$password) {

                return;
            }




            $mail = new \Nette\Mail\Message;
            $mail->setFrom($from_email, $from_name)
                ->addTo($this->mailTo)
                ->setSubject($this->subject)
                ->setHtmlBody($this->body);

            $mailer = new \Nette\Mail\SmtpMailer(
                host: $host,
                port: $port,
                username: $username,
                password: $password,
                encryption: $encryption,
                timeout: 5
            );
            $mailer->send($mail);
        } catch (\Exception $e) {
            ShmInit::sendOnError($e);


            return;
        }
    }
}