<?php

namespace App\Providers;

use App\Services\ThemeManager;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class ThemeServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(ThemeManager::class);
    }

    public function boot(): void
    {
        $themeManager = $this->app->make(ThemeManager::class);

        try {
            $activeTheme = $themeManager->getActive();
        } catch (\Exception $e) {
            $activeTheme = 'default';
        }

        // Prepend active theme's views path - it takes priority over resources/views/
        if ($themeManager->exists($activeTheme)) {
            $viewsPath = $themeManager->getViewsPath($activeTheme);

            if (is_dir($viewsPath)) {
                $finder = $this->app['view']->getFinder();
                $finder->prependLocation($viewsPath);
            }
        }

        // Share theme info with all views
        View::share('activeTheme', $activeTheme);
        View::share('themeAssets', $themeManager->getAssets($activeTheme));
    }
}
