<?php

namespace App\Providers;

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

class SettingsServiceProvider extends ServiceProvider
{
    public function boot()
    {
        if (Schema::hasTable('settings')) {
            try {
                $settings = Setting::all();
                
                foreach ($settings as $setting) {
                    config()->set('settings.' . $setting->key, $setting->value);
                }
                
                // Set app name from settings
                config()->set('app.name', config('settings.app_name', 'Innovaxcess Attendance'));
                
                // Set mail configuration from settings
                $this->configureMailFromSettings();
                
            } catch (\Exception $e) {
                // Don't break the app if settings table doesn't exist yet
            }
        }
    }
    
    private function configureMailFromSettings()
    {
        if (config('settings.mail_driver')) {
            config()->set('mail.default', config('settings.mail_driver'));
            config()->set('mail.mailers.smtp.host', config('settings.mail_host'));
            config()->set('mail.mailers.smtp.port', config('settings.mail_port'));
            config()->set('mail.mailers.smtp.username', config('settings.mail_username'));
            config()->set('mail.mailers.smtp.password', config('settings.mail_password'));
            config()->set('mail.mailers.smtp.encryption', config('settings.mail_encryption'));
            config()->set('mail.from.address', config('settings.mail_from_address'));
            config()->set('mail.from.name', config('settings.mail_from_name'));
        }
    }
}