<?php

namespace App\Providers;

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

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

    /**
     * Bootstrap any application services.
     */
  public function boot(): void
{
    // Prevent crashes during migration when table doesn't exist yet
    if (Schema::hasTable('settings')) {

        $mailHost = Setting::get('mail_host');

        // Only override if we actually have settings saved
        if ($mailHost) {
            Config::set('mail.mailers.smtp.host',       Setting::get('mail_host'));
            Config::set('mail.mailers.smtp.port',       Setting::get('mail_port'));
            Config::set('mail.mailers.smtp.username',   Setting::get('mail_username'));
            Config::set('mail.mailers.smtp.password',   Setting::get('mail_password'));
            Config::set('mail.mailers.smtp.encryption', Setting::get('mail_encryption'));
            Config::set('mail.from.address',            Setting::get('mail_from_address'));
            Config::set('mail.from.name',               Setting::get('company_name'));

            // Also update app name globally
            Config::set('app.name', Setting::get('company_name'));
        }
    }
}
}
