<?php

namespace Modules\WMSInventoryCore\App\Providers;

use App\Services\Settings\SettingsRegistry;
use App\Traits\RegistersMenuItems;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
use Modules\WMSInventoryCore\App\Settings\WMSInventoryCoreSettings;
use Nwidart\Modules\Traits\PathNamespace;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;

class WMSInventoryCoreServiceProvider extends ServiceProvider
{
    use PathNamespace;
    use RegistersMenuItems;

    protected string $name = 'WMSInventoryCore';

    protected string $nameLower = 'wmsinventorycore';

    /**
     * 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'));

        // Register module settings
        $this->registerModuleSettings();

        // Register dynamic menu items
        $this->registerMenuItems();
    }

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

        // Register module settings
        $this->app->singleton('wmsinventorycore.settings', function () {
            return new WMSInventoryCoreSettings;
        });
    }

    /**
     * Register module settings
     */
    protected function registerModuleSettings(): void
    {
        if ($this->app->bound(SettingsRegistry::class)) {
            $registry = $this->app->make(SettingsRegistry::class);

            $registry->registerModule('wmsinventorycore', [
                'name' => __('Inventory Management'),
                'description' => __('Configure inventory tracking, stock management, and warehouse operations'),
                'icon' => 'bx bx-package',
                'handler' => WMSInventoryCoreSettings::class,
                'permissions' => [], // Remove permissions for now
                'order' => 40,
            ]);
        }
    }

    /**
     * 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, 'resources/lang'), $this->nameLower);
            $this->loadJsonTranslationsFrom(module_path($this->name, 'resources/lang'));
        }
    }

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

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

            foreach ($iterator as $file) {
                if ($file->isFile() && $file->getExtension() === 'php') {
                    $relativePath = str_replace($configPath.DIRECTORY_SEPARATOR, '', $file->getPathname());
                    $configKey = $this->nameLower.'.'.str_replace([DIRECTORY_SEPARATOR, '.php'], ['.', ''], $relativePath);
                    $key = ($relativePath === 'config.php') ? $this->nameLower : $configKey;

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

    /**
     * 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']);

        $this->loadViewsFrom(array_merge($this->getPublishableViewPaths(), [$sourcePath]), $this->nameLower);

        $componentNamespace = $this->module_namespace($this->name, $this->app_path(config('modules.paths.generator.component-class.path')));
        Blade::componentNamespace($componentNamespace, $this->nameLower);
    }

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

    /**
     * Get the publishable view paths.
     */
    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;
    }

    /**
     * Get the menu items for this module.
     *
     * @return array<array<string, mixed>>
     */
    protected function getMenuItems(): array
    {
        return [
            [
                'name' => __('Inventory Management'),
                'icon' => 'menu-icon bx bx-package',
                'roles' => ['super_admin', 'admin', 'hr', 'hr_manager', 'hr_executive'],
                'slug' => [
                    'wmsinventorycore.dashboard.index',
                    'wmsinventorycore.units.index',
                    'wmsinventorycore.warehouses.index',
                    'wmsinventorycore.adjustments.index',
                    'wmsinventorycore.transfers.index',
                    'wmsinventorycore.vendors.index',
                    'wmsinventorycore.reports.inventory-valuation',
                    'wmsinventorycore.reports.stock-movement',
                    'wmsinventorycore.reports.low-stock',
                    'wmsinventorycore.settings.index',
                ],
                'submenu' => [
                    [
                        'url' => '/inventory/dashboard',
                        'name' => __('Dashboard'),
                        'slug' => 'wmsinventorycore.dashboard.index',
                    ],
                    [
                        'url' => '/inventory/units',
                        'name' => __('Units'),
                        'slug' => 'wmsinventorycore.units.index',
                    ],
                    [
                        'url' => '/inventory/warehouses',
                        'name' => __('Warehouses'),
                        'slug' => 'wmsinventorycore.warehouses.index',
                    ],
                    [
                        'url' => '/inventory/vendors',
                        'name' => __('Vendors'),
                        'slug' => 'wmsinventorycore.vendors.index',
                    ],
                    [
                        'url' => '/inventory/adjustments',
                        'name' => __('Stock Adjustments'),
                        'slug' => 'wmsinventorycore.adjustments.index',
                    ],
                    [
                        'url' => '/inventory/transfers',
                        'name' => __('Stock Transfers'),
                        'slug' => 'wmsinventorycore.transfers.index',
                    ],
                    [
                        'name' => __('Reports'),
                        'slug' => [
                            'wmsinventorycore.reports.inventory-valuation',
                            'wmsinventorycore.reports.stock-movement',
                            'wmsinventorycore.reports.low-stock',
                        ],
                        'submenu' => [
                            [
                                'url' => '/inventory/reports/inventory-valuation',
                                'name' => __('Inventory Valuation'),
                                'slug' => 'wmsinventorycore.reports.inventory-valuation',
                            ],
                            [
                                'url' => '/inventory/reports/stock-movement',
                                'name' => __('Stock Movement'),
                                'slug' => 'wmsinventorycore.reports.stock-movement',
                            ],
                            [
                                'url' => '/inventory/reports/low-stock',
                                'name' => __('Low Stock Alert'),
                                'slug' => 'wmsinventorycore.reports.low-stock',
                            ],
                        ],
                    ],
                    [
                        'url' => '/inventory/settings',
                        'name' => __('Settings'),
                        'slug' => 'wmsinventorycore.settings.index',
                    ],
                ],
            ],
        ];
    }

    /**
     * Get the menu priority for this module.
     * Lower values appear higher in the menu.
     */
    protected function getMenuPriority(): int
    {
        return 80; // Inventory modules
    }
}
