<?php

namespace App\Providers;

use Config;
use App\Models\Setting;
use App\Models\SMTPMails;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;

class MailServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     */
    protected $mail;
    protected $from;

    public function register(): void
    {
        //
    }

    /**
     * Bootstrap services.
     */
    public function boot(): void
    {

        if (Config::get("srm_db_config") && !is_null(Setting::where("settings_key", "fromEmail")->first())) {

            $this->mail = SMTPMails::defaultSmtpMail()->first();

            $this->from = [
                'address' => get_from_email(),
                'name'    => get_from_name()
            ];

            if (isset($this->mail->id) && $this->checkSmtpEncryption()) {

                $encryption = $this->mail->encryption;

// Check for valid encryption values
                if (!in_array($encryption, ['tls', 'ssl'])) {
                    $encryption = null;
                }

                try{
                    $config = array(
                        // 'driver'     => 'smtp',
                        'transport'  => 'smtp',
                        'host'       => $this->mail->smtp,
                        'port'       => $this->mail->port,
                        'encryption' => $encryption,
                        'username'   => $this->mail->username,
                        'password'   => decrypt($this->mail->Password),
                        'from'       => array('address' => $this->from['address'], 'name' => $this->from['name']),
                        'timeout'    => null,
                        'auth_mode'  => null

                    );
                    Config::set('mail.mailers.smtp', $config);
                }catch(\Exception $e){
                    Log::error("Mail Error: ". $e->getMessage());
                }
            }

        }

    }


    private function checkSmtpEncryption(){
        try {
            decrypt($this->mail->Password);
            return true;
        } catch (\Exception $e) {
            SMTPMails::truncate();
            return false;
        }

    }

}