<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Models\Sysparam;
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
    {
        // 动态加载自定义 SMTP 配置 (如果有数据库则执行)
        try {
            if (Schema::hasTable('sysparam')) {
                $smtpConfig = Sysparam::where('alias', 'like', 'smtp_%')->pluck('body', 'alias');
                
                if ($smtpConfig->isNotEmpty() && $smtpConfig->get('smtp_host')) {
                    Config::set('mail.default', 'smtp');
                    Config::set('mail.mailers.smtp', [
                        'transport' => 'smtp',
                        'host' => $smtpConfig->get('smtp_host'),
                        'port' => $smtpConfig->get('smtp_port', 465),
                        'encryption' => $smtpConfig->get('smtp_encryption', 'ssl'),
                        'username' => $smtpConfig->get('smtp_username'),
                        'password' => $smtpConfig->get('smtp_password'),
                        'timeout'  => 10,
                        'local_domain' => env('MAIL_EHLO_DOMAIN'),
                    ]);

                    Config::set('mail.from', [
                        'address' => $smtpConfig->get('smtp_from_address', $smtpConfig->get('smtp_username')),
                        'name' => $smtpConfig->get('smtp_from_name', '飘落流星聊天室'),
                    ]);
                }
            }
        } catch (\Exception $e) {
            // 在安装初期表不存在时忽略，防止应用崩溃
        }
    }
}
