<?php

namespace App\Services;

use App\Models\Mail;
use App\Models\SMTPMails;
use PHPMailer\PHPMailer\PHPMailer;
use App\Repositories\SMTPRepository;

class SMTPService
{

    private $mail;
    private $smtpRepository;
    public function __construct(SMTPRepository $smtpRepository)
    {
        $this->smtpRepository = $smtpRepository;
    }

    public function checkSMTPConnection($data)
    {

        $this->initiateConnection($data);
        try {

            if (!$this->mail->smtpConnect()) {
                throw new Exception("Could not connect to SMTP server.");
            }

        } catch (\Exception $e) {
            $error = str_replace("SMTP Error:", "SMTP Connection Error.", $e->getMessage());
            abort(400, $error);
        }

    }

    public function update($data)
    {

        $this->checkSMTPConnection($data);

        if (
            !$this->checkConnectionExists($data)->exists()
            && !$this->smtpRepository->getNumberOfServers()
        ) {
            $this->smtpRepository->create($data);
        } else

        if (!$this->checkConnectionExists($data)->exists()) {

            if (!isset($data["confirmed"])) {
                abort(400, 'need-confirmation');
            }

            $this->smtpRepository->setAllDefaultSMTPFalse();

            $this->smtpRepository->create($data);
        } else {

            $this->smtpRepository->updateOrCreate($data);
        }

    }

    private function initiateConnection($data)
    {
        $this->mail = new PHPMailer(true);
        $this->mail->isSMTP();
        $this->mail->SMTPAuth                     = true;
        $this->mail->Host                         = $data['smtp_server'];
        $this->mail->Port                         = $data['smtp_port'];
        $this->mail->Username                     = $data['username'];
        $this->mail->Password                     = $data['password'];
        $this->mail->AuthType                     = $data['auth_mode'];
        $this->mail->Timeout                      = 30;
        $this->mail->SMTPSecure                   = $data['encryption'];
        $this->mail->getSMTPInstance()->Timelimit = 30;

        if (!in_array($data['encryption'], ['tls', 'ssl'])) {
            $this->mail->SMTPAutoTLS                  = false;
        }

    }

    private function checkConnectionExists($data)
    {
        return SMTPMails::where([
            'smtp'     => $data['smtp_server'],
            'port'     => $data['smtp_port'],
            'username' => $data['username']
        ]);
    }

    public function getDeafultSMTPServer()
    {
        return SMTPMails::defaultSmtpMail()->first();
    }

}