<?php

namespace Modules\LandingPage\Providers;

use Illuminate\Support\Facades\View as ViewFacade;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
use Nwidart\Modules\Traits\PathNamespace;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;

class LandingPageServiceProvider extends ServiceProvider
{
    use PathNamespace;

    protected string $name = 'LandingPage';

    protected string $nameLower = 'landingpage';

    /**
     * Boot the application events.
     */
    public function boot(): void
    {
        $this->registerCommands();
        $this->registerCommandSchedules();
        $this->registerTranslations();
        $this->registerConfig();
        $this->registerViews();
        $this->loadMigrationsFrom(module_path($this->name, 'database/migrations'));

        // Share active theme and site direction with all views
        // It's important to check if running in console to avoid issues during migrations
        // or when the database/settings table might not be ready.
        if (!$this->app->runningInConsole()) {
            try {
                ViewFacade::composer('*', function ($view) {
                    $activeTheme = setting('landingpage_active_theme', 'general');
                    $siteDirection = setting('site_direction', 'ltr'); // Default to LTR

                    $view->with('activeTheme', $activeTheme)
                         ->with('siteDirection', $siteDirection);
                });
            } catch (\Exception $e) {
                // Log error or handle case where settings table might not exist
                // For now, we'll provide defaults to prevent breaking views if DB is not ready.
                ViewFacade::composer('*', function ($view) {
                    $view->with('activeTheme', 'general')
                         ->with('siteDirection', 'ltr');
                });
            }
        }
    }

    /**
     * Register the service provider.
     */
    public function register(): void
    {
        $this->app->register(EventServiceProvider::class);
        $this->app->register(RouteServiceProvider::class);
    }

    /**
     * Register commands in the format of Command::class
     */
    protected function registerCommands(): void
    {
        // $this->commands([]);
    }

    /**
     * Register command Schedules.
     */
    protected function registerCommandSchedules(): void
    {
        // $this->app->booted(function () {
        //     $schedule = $this->app->make(Schedule::class);
        //     $schedule->command('inspire')->hourly();
        // });
    }

    /**
     * Register translations.
     */
    public function registerTranslations(): void
    {
        $langPath = resource_path('lang/modules/'.$this->nameLower);

        if (is_dir($langPath)) {
            $this->loadTranslationsFrom($langPath, $this->nameLower);
            $this->loadJsonTranslationsFrom($langPath);
        } else {
            $this->loadTranslationsFrom(module_path($this->name, 'lang'), $this->nameLower);
            $this->loadJsonTranslationsFrom(module_path($this->name, 'lang'));
        }
    }

    /**
     * Register config.
     */
    protected function registerConfig(): void
    {
        $configPath = module_path($this->name, config('modules.paths.generator.config.path', 'Config')); // Added default for generator path

        if (is_dir($configPath)) {
            $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($configPath, RecursiveDirectoryIterator::SKIP_DOTS));

            foreach ($iterator as $file) {
                if ($file->isFile() && $file->getExtension() === 'php') {
                    $configFilename = $file->getFilename();
                    $configKeyBase = str_replace('.php', '', $configFilename);

                    // For the main config.php, use the module's lower name as the key.
                    // For other config files, use moduleNameLower.configKeyBase (e.g., landingpage.settings)
                    $key = ($configFilename === 'config.php') ? $this->nameLower : $this->nameLower . '.' . $configKeyBase;
                    
                    // Ensure we don't create keys like 'landingpage.landingpage' if config.php is inside a subdirectory named 'landingpage'
                    // This part of your original logic for $segments and $normalized was a bit complex
                    // and might lead to unexpected keys if not careful.
                    // The simplified approach above is common for nwidart/laravel-modules.
                    // If you have a specific nested config structure you need to support,
                    // the original logic might be needed, but ensure it produces the correct final key.

                    $this->publishes([$file->getPathname() => config_path($this->nameLower . '/' . $file->getFilename())], 'config');
                    $this->mergeConfigFrom($file->getPathname(), $key);
                }
            }
        }
    }

    /**
     * Merge config from the given path.
     * Changed from merge_config_from to mergeConfigFrom to match Laravel conventions.
     */
    protected function mergeConfigFrom($path, $key)
    {
        $config = $this->app['config']->get($key, []);
        $this->app['config']->set($key, array_replace_recursive(require $path, $config));
    }

    /**
     * Register views.
     */
    public function registerViews(): void
    {
        $viewPath = resource_path('views/modules/'.$this->nameLower);
        $sourcePath = module_path($this->name, 'resources/views');

        $this->publishes([$sourcePath => $viewPath], ['views', $this->nameLower.'-module-views']);

        // Corrected line: Use $this->nameLower for the view namespace hint
        $this->loadViewsFrom(array_merge($this->getPublishableViewPaths(), [$sourcePath]), $this->nameLower);

        // This line is correct if your components are in Modules/LandingPage/View/Components
        // and you call them like <x-LandingPage::component-name />
        Blade::componentNamespace(config('modules.namespace', 'Modules').'\\' . $this->name . '\\View\\Components', $this->name);
    }

    /**
     * Get the services provided by the provider.
     */
    public function provides(): array
    {
        return [];
    }

    private function getPublishableViewPaths(): array
    {
        $paths = [];
        foreach (config('view.paths') as $path) {
            if (is_dir($path.'/modules/'.$this->nameLower)) {
                $paths[] = $path.'/modules/'.$this->nameLower;
            }
        }
        return $paths;
    }
}
