<?php

namespace App\Providers;

use App\Models\Smtp;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;

class MailConfigServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap services.
     */
    public function boot(): void
    {
        // Only attempt to load if the table exists to avoid errors during migrations
        if (Schema::hasTable('smtps')) {
            $smtp = Smtp::first();

            if ($smtp) {
                $config = [
                    'transport' => 'smtp',
                    'host' => $smtp->smtphost,
                    'port' => $smtp->smtpport,
                    'from' => [
                        'address' => $smtp->fromemail,
                        'name' => config('app.name'),
                    ],
                    'encryption' => $smtp->smtpencryption === 'none' ? null : $smtp->smtpencryption,
                    'username' => $smtp->smtpusername,
                    'password' => $smtp->smtppassword,
                    'timeout' => 10,
                ];

                Config::set('mail.mailers.smtp', array_merge(config('mail.mailers.smtp', []), $config));
                Config::set('mail.from.address', $smtp->fromemail);
                
                // If you want to force the app to use SMTP mailer
                Config::set('mail.default', 'smtp');
            }
        }
    }
}
