<?php

namespace App\Providers;

use App\Services\SettingsService;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Log;
use Illuminate\Contracts\Foundation\Application;

class SettingsServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     */
    public function register(): void
    {
        // Register the SettingsService as a singleton
        $this->app->singleton(SettingsService::class, function ($app) {
            return new SettingsService();
        });

        // Also bind under the legacy "app_settings" key so facades / helpers work
        $this->app->singleton('app_settings', function ($app) {
            return $app->make(SettingsService::class);
        });
    }

    /**
     * Bootstrap services.
     */
    public function boot(): void
    {
        // Use a deferred approach to load settings
        // This ensures all services are loaded before accessing the database
        $this->app->booted(function () {
            try {
                // Check if we're in console mode
                if ($this->app->runningInConsole()) {
                    return;
                }

                // Check if database connection is available and settings table exists
                if ($this->canAccessDatabase() && Schema::hasTable('settings')) {
                    $settingsService = app(SettingsService::class);
                    
                    // Share settings with all views
                    View::share('appSettings', $settingsService->all());
                    
                    // Share theme variables with all views
                    View::share('themeVariables', $settingsService->getThemeCssVariables());
                    View::share('themeMode', $settingsService->getThemeMode());
                    
                    // Log successful loading
                    Log::info('Settings loaded successfully in provider');
                } else {
                    // Provide default values if settings table doesn't exist
                    $this->shareDefaultSettings();
                }
            } catch (\Exception $e) {
                // Log the error but don't crash the application
                Log::warning('Could not load settings in provider: ' . $e->getMessage());
                
                // Provide default values on error
                $this->shareDefaultSettings();
            }
        });
    }

    /**
     * Check if we can access the database
     */
    protected function canAccessDatabase(): bool
    {
        try {
            if (!$this->app->bound('db')) {
                return false;
            }
            
            $connection = $this->app->make('db')->connection();
            $pdo = $connection->getPdo();
            
            return $pdo !== null;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * Share default settings when database is not available
     */
    protected function shareDefaultSettings()
    {
        $defaultThemeVariables = array_merge(
            SettingsService::canonicalGreenThemeCssVariables(),
            [
                '--font-family' => "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif",
                '--border-radius' => '12px',
                '--box-shadow' => '0 4px 12px rgba(0,0,0,0.08)',
                '--header-font-size' => '2.5rem',
                '--gray-100' => '#f8f9fa',
                '--gray-200' => '#e9ecef',
                '--gray-600' => '#6c757d',
                '--gray-800' => '#343a40',
            ]
        );

        View::share('appSettings', []);
        View::share('themeVariables', $defaultThemeVariables);
        View::share('themeMode', 'light');
    }
}