<?php

namespace App\Providers;

use App\Models\Setting;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\ServiceProvider;

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

    /**
     * Bootstrap services.
     */
    public function boot(): void
    {
        if (!Schema::hasTable('settings')) {
            return;
        }

        $settings = Setting::where('group', 'smtp')->get()->pluck('value', 'key');

        if ($settings->isNotEmpty()) {
            
            // 1. Force the default driver to be SMTP
            Config::set('mail.default', 'smtp'); 

            $password = isset($settings['smtp_password']) 
                ? $this->decryptValue($settings['smtp_password']) 
                : null;

            $config = [
                'transport' => 'smtp',
                'host'       => $settings['smtp_host'] ?? env('MAIL_HOST'),
                'port'       => $settings['smtp_port'] ?? env('MAIL_PORT'),
                'username'   => $settings['smtp_username'] ?? env('MAIL_USERNAME'),
                'password'   => $password ?? env('MAIL_PASSWORD'),
                'encryption' => $settings['smtp_encryption'] === 'null' ? null : ($settings['smtp_encryption'] ?? env('MAIL_ENCRYPTION')),
                'timeout'    => null,
                'auth_mode'  => null,
            ];

            // 2. Set the SMTP configuration
            Config::set('mail.mailers.smtp', $config);
            
            // 3. Set the From Address
            if (isset($settings['smtp_from_address'])) {
                Config::set('mail.from.address', $settings['smtp_from_address']);
            }
            if (isset($settings['smtp_from_name'])) {
                Config::set('mail.from.name', $settings['smtp_from_name']);
            }
        }
    }

    private function decryptValue($value)
    {
        try {
            return Crypt::decryptString($value);
        } catch (\Exception $e) {
            return $value;
        }
    }
}