<?php

namespace App\Providers;

use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        //
    }

    public function boot(): void
    {
        // Admin Gate: Only users with is_admin === true can access admin-only routes
        Gate::define('admin', function ($user) {
            return $user->is_admin === true;
        });

        // Dynamically set SMTP Mail Config from Database Settings
        try {
            if (\Illuminate\Support\Facades\Schema::hasTable('settings')) {
                $mailHost = \App\Models\Setting::get('mail_host');
                if (!empty($mailHost)) {
                    \Illuminate\Support\Facades\Config::set('mail.mailers.smtp.host', $mailHost);
                    \Illuminate\Support\Facades\Config::set('mail.mailers.smtp.port', \App\Models\Setting::get('mail_port', '2525'));
                    \Illuminate\Support\Facades\Config::set('mail.mailers.smtp.username', \App\Models\Setting::get('mail_username'));
                    \Illuminate\Support\Facades\Config::set('mail.mailers.smtp.password', \App\Models\Setting::get('mail_password'));
                    
                    // Set global from address based on Admin Email and Site Name
                    $adminEmail = \App\Models\Setting::get('admin_email');
                    $siteName = \App\Models\Setting::get('site_name');
                    if (!empty($adminEmail)) {
                        \Illuminate\Support\Facades\Config::set('mail.from.address', $adminEmail);
                        \Illuminate\Support\Facades\Config::set('mail.from.name', $siteName);
                    }
                }
            }
        } catch (\Exception $e) {
            // Ignore errors during initial migrations or if DB is unavailable
        }
    }
}
