<?php

declare(strict_types=1);

namespace App\Providers;

use App\Contracts\Services\SettingsServiceInterface;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

final class SettingsServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     */
    public function register(): void
    {
        $this->app->bind(SettingsServiceInterface::class, \App\Services\SettingsService::class);
    }

    /**
     * Bootstrap services.
     */
    public function boot(): void
    {
        // Load settings after database is available
        if ($this->app->runningInConsole() && ! $this->app->runningUnitTests()) {
            return;
        }

        try {
            $settings = app(SettingsServiceInterface::class);
            $allSettings = $settings->all();

            // Process image settings to add /storage/ prefix
            $imageSettings = ['site_logo', 'site_favicon', 'email_logo', 'seo_og_default_image'];
            foreach ($imageSettings as $setting) {
                if (! isset($allSettings[$setting]) || ! $allSettings[$setting]) {
                    continue;
                }
                $path = (string) $allSettings[$setting];
                if (str_starts_with($path, '/') || str_starts_with($path, 'http://') || str_starts_with($path, 'https://')) {
                    continue;
                }
                $allSettings[$setting] = '/storage/'.$path;
            }

            // Share settings as config
            Config::set('settings', $allSettings);

            // Share settings with all views
            View::share('settings', $allSettings);

            // Update mail configuration from database settings
            if ($settings->has('smtp_host')) {
                Config::set('mail.mailers.smtp.host', $settings->get('smtp_host'));
                Config::set('mail.mailers.smtp.port', $settings->get('smtp_port'));
                Config::set('mail.mailers.smtp.username', $settings->get('smtp_username'));
                Config::set('mail.mailers.smtp.password', $settings->get('smtp_password'));
                Config::set('mail.mailers.smtp.encryption', $settings->get('smtp_encryption'));
                Config::set('mail.from.address', $settings->get('smtp_from_address'));
                Config::set('mail.from.name', $settings->get('smtp_from_name'));
            }
        } catch (\Exception $e) {
            // Silently fail if settings table doesn't exist yet (during migrations)
        }
    }
}
