<?php

namespace App\Providers;

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

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

    /**
     * Bootstrap services.
     */
    public function boot(): void
    {
        // Încarcă SMTP setări din baza de date dacă este activat
        try {
            if (Setting::get('smtp_enabled', false)) {
                Config::set('mail.default', 'smtp');
                Config::set('mail.mailers.smtp', [
                    'transport' => 'smtp',
                    'host' => Setting::get('smtp_host', env('MAIL_HOST', 'smtp.mailgun.org')),
                    'port' => Setting::get('smtp_port', env('MAIL_PORT', 587)),
                    'encryption' => Setting::get('smtp_encryption', env('MAIL_ENCRYPTION', 'tls')),
                    'username' => Setting::get('smtp_username', env('MAIL_USERNAME')),
                    'password' => Setting::get('smtp_password', env('MAIL_PASSWORD')),
                    'timeout' => null,
                ]);

                Config::set('mail.from', [
                    'address' => Setting::get('smtp_from_address', env('MAIL_FROM_ADDRESS', 'hello@example.com')),
                    'name' => Setting::get('smtp_from_name', env('MAIL_FROM_NAME', 'Example')),
                ]);
            }
        } catch (\Exception $e) {
            // If baza de date is not ready (migrations not run), use .env valoares
            // This prevents eroares during initial setup
        }
    }
}
