<?php

namespace App\Repositories;

use App\User;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;

class MailerRepository extends BaseRepository
{
    protected $mailer = null;

    public function __construct()
    {
        $this->mailServerSettings();
    }

    /**
     * Lấy đối tượng mailer
     * @return null
     */
    public function getMailer()
    {
        return $this->mailer;
    }

    /**
     * Hàm gửi 1 email
     *
     * @param $toEmail
     * @param $subject
     * @param $message
     * @param null $attachFile
     *
     * @return int
     */
    public function sendMail($toEmail, $subject, $message, $attachFile = null)
    {
        if (!empty($this->mailer)) {
            try {
                $this->mailer->addAddress($toEmail);
                $this->mailer->Subject = $subject;
                $this->mailer->Body = $message;
                $this->mailer->send();

                $this->mailer->clearAllRecipients();
                $this->mailer->smtpClose();

                return 1;

            } catch (Exception $e) {
                return -2;
            }
        } else {
            reutrn -3;
        }
    }

    /**
     * @return null|PHPMailer
     */
    private function mailServerSettings()
    {
        $this->mailer = new PHPMailer(true);

        //$this->mailer->SMTPDebug = 2;
        $this->mailer->isSMTP();
        $this->mailer->CharSet = 'utf-8';
        $this->mailer->SMTPKeepAlive = true;
        $this->mailer->Timeout = 15;
        $this->mailer->getSMTPInstance()->Timelimit = 15;
        $this->mailer->Host = config('mail.host');
        $this->mailer->SMTPAuth = true;
        $this->mailer->SMTPSecure = config('mail.encryption');
        $this->mailer->Username = config('mail.username');
        $this->mailer->Password = config('mail.password');
        $this->mailer->Port = config('mail.port');
        $this->mailer->SMTPOptions = [
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            )
        ];
        $this->mailer->isHTML(true);
        $this->mailer->setFrom(config('mail.from.address'), config('mail.from.name'));
        $this->mailer->addCC('doanpv@dcv.vn', 'Phạm Văn Đoan');
        $this->mailer->Subject = '[VMusicChart] Cảnh báo';

        return $this->mailer;
    }

}