<?php

namespace App\Checklist;

use App\Contracts\GoLiveChecklist;
use App\Facades\Settings;
use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport;

class CheckMail implements GoLiveChecklist
{
    /**
     * Name of the check
     *
     * @return string
     */
    public function name(): string
    {
        return __('go-live.mail_sending');
    }

    /**
     * Does the check passes
     *
     * @return bool|null
     */
    public function passes(): ?bool
    {
        return $this->checkConnection();
    }

    /**
     * URL to perform check
     *
     * @return string
     */
    public function urlToCheck(): string
    {
        return route('tenant.checklists.mail');
    }

    /**
     * Check mail connection
     *
     * @return bool
     */
    public function checkConnection()
    {
        try {
            // Create the Transport
            $transport = (new EsmtpTransport(
                Settings::get('mail.smtp.host', 'localhost'),
                Settings::get('mail.smtp.port', 587),
                true
            ));

            $transport
                ->setUsername(Settings::get('mail.smtp.username', ''))
                ->setPassword(Settings::get('mail.smtp.password', ''))
                ->start();

            return true;
        } catch (\Exception $exception) {
            return false;
        }
    }
}
