<?php

namespace App\Providers;

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

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

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        if (Schema::hasTable('settings')) {
            try {
                // Cache all settings for 5 minutes to avoid repeated DB queries
                $allSettings = Cache::remember('app_settings', 300, function () {
                    return Setting::pluck('value', 'key')->toArray();
                });

                $siteName = $allSettings['site_name'] ?? 'Bursa Kerja';
                $siteDescription = $allSettings['site_description'] ?? 'Temukan lowongan pekerjaan terbaru dan terpercaya';
                $countdownSeconds = (int) ($allSettings['countdown_seconds'] ?? 8);

                View::share('siteName', $siteName);
                View::share('siteDescription', $siteDescription);
                View::share('countdownSeconds', $countdownSeconds);

                // Override SMTP config from database settings
                $overrides = [];

                $map = [
                    'mail_host'         => 'mail.mailers.smtp.host',
                    'mail_port'         => 'mail.mailers.smtp.port',
                    'mail_username'     => 'mail.mailers.smtp.username',
                    'mail_password'     => 'mail.mailers.smtp.password',
                    'mail_encryption'   => 'mail.mailers.smtp.encryption',
                    'mail_from_address' => 'mail.from.address',
                    'mail_from_name'    => 'mail.from.name',
                ];

                foreach ($map as $settingKey => $configKey) {
                    $value = $allSettings[$settingKey] ?? null;
                    if ($value !== null) {
                        $overrides[$configKey] = $value;
                    }
                }

                if (!empty($overrides)) {
                    $overrides['mail.default'] = 'smtp';
                    config($overrides);
                }
            } catch (\Exception $e) {
                // DB not yet migrated — set defaults
                View::share('siteName', 'Bursa Kerja');
                View::share('siteDescription', 'Temukan lowongan pekerjaan terbaru dan terpercaya');
                View::share('countdownSeconds', 8);
            }
        } else {
            View::share('siteName', 'Bursa Kerja');
            View::share('siteDescription', 'Temukan lowongan pekerjaan terbaru dan terpercaya');
            View::share('countdownSeconds', 8);
        }
    }
}
