<?php

namespace App\Seraph\Services;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Mail;
use Exception;

class Mailer
{
    /**
     * Email addresses to send the email to.
     *
     * @var array
     */
    private $send_to;

    /**
     * Parameters to replace in the template.
     *
     * @var string
     */
    private $parameters;

    /**
     * Email subject.
     *
     * @var string
     */
    private $subject;

    /**
     * Email address to send the email from.
     *
     * @var string
     */
    private $sender;

    /**
     * Name to show as the sender.
     *
     * @var string
     */
    private $sender_name;

    /**
     * Email address to send the email from.
     *
     * @var string
     */
    private $template;

    /**
     * A reference to the Monolog.
     *
     * @var \Illuminate\Log\Writer
     */
    private $log;

    public function __construct(Log $log)
    {
        $this->log = $log;
        $this->sender = Config::get('emails.from.email');
        $this->sender_name = Config::get('emails.from.name');
    }

    /**
     * Create a Mailer and init the basic values.
     *
     * @param  string $send_to
     * @param  string $subject
     * @param  string $template
     * @param  array $parameters
     *
     * @return string | false
     */
    public function create($send_to, $subject, $template, $parameters)
    {
        $this->send_to = $send_to;
        $this->subject = $subject;
        $this->template = $template;
        $this->parameters = $parameters;
    }

    /**
     * Send an email using a template and the parameters given in create.
     *
     * @return void
     */
    public function send()
    {
        try {
            $mailer = $this;

            // Use global SMTP configuration
            $result = \App\Seraph\Services\GlobalMailerService::send($this->template, $this->parameters, function ($message) use ($mailer) {
                $message->from($mailer->sender, $mailer->sender_name);
                $message->to($mailer->send_to)
                    ->subject($mailer->subject);
            });

            return $result;
        } catch (Exception $e) {
            $this->log->error($e);

            return false;
        }
    }
}
