<?php

namespace Modules\AccountingCore\App\Providers;

use App\Services\AddonService\AddonService;
use App\Services\Settings\SettingsRegistry;
use App\Traits\RegistersMenuItems;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
use Modules\AccountingCore\App\Settings\AccountingCoreSettings;
use Nwidart\Modules\Traits\PathNamespace;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;

class AccountingCoreServiceProvider extends ServiceProvider
{
    use PathNamespace;
    use RegistersMenuItems;

    protected string $name = 'AccountingCore';

    protected string $nameLower = 'accountingcore';

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

        // Check if AccountingPro is enabled
        $this->checkAccountingProStatus();

        // 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 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 [];
    }

    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;
    }

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

            $registry->registerModule('accountingcore', [
                'name' => __('Accounting'),
                'description' => __('Configure basic accounting settings for income and expense tracking'),
                'icon' => 'bx bx-calculator',
                'handler' => AccountingCoreSettings::class,
                'permissions' => [],
                'order' => 10,
            ]);
        }
    }

    /**
     * Check if AccountingPro is enabled and bind appropriate services
     */
    protected function checkAccountingProStatus(): void
    {
        $addonService = app(AddonService::class);

        if ($addonService->isAddonEnabled('AccountingPro')) {
            // AccountingPro is enabled, bind it as the primary accounting provider
            $this->app->bind('accounting.provider', 'Modules\AccountingPro\App\Services\AccountingProService');
        } else {
            // Use basic accounting
            $this->app->bind('accounting.provider', 'Modules\AccountingCore\App\Services\AccountingCoreService');
        }
    }

    /**
     * Get the menu items for this module.
     *
     * @return array<array<string, mixed>>
     */
    protected function getMenuItems(): array
    {
        return [
            [
                'name' => 'Accounting',
                'icon' => 'menu-icon bx bx-calculator',
                'roles' => ['super_admin', 'admin', 'hr', 'hr_manager', 'hr_executive'],
                'slug' => [
                    'accountingcore.dashboard',
                    'accountingcore.transactions.index',
                    'accountingcore.categories.index',
                    'systemcore.tax-configurations.index',
                    'accountingcore.reports.index',
                    'accountingcore.settings.index',
                ],
                'submenu' => [
                    [
                        'url' => '/accountingcore/dashboard',
                        'name' => 'Dashboard',
                        'slug' => 'accountingcore.dashboard',
                    ],
                    [
                        'url' => '/accountingcore/transactions',
                        'name' => 'Transactions',
                        'slug' => 'accountingcore.transactions.index',
                    ],
                    [
                        'url' => '/accountingcore/categories',
                        'name' => 'Categories',
                        'slug' => 'accountingcore.categories.index',
                    ],
                    [
                        'url' => '/systemcore/tax-configurations',
                        'name' => 'Tax Configurations',
                        'slug' => 'systemcore.tax-configurations.index',
                    ],
                    [
                        'url' => '/accountingcore/reports',
                        'name' => 'Reports',
                        'slug' => 'accountingcore.reports.index',
                    ],
                    [
                        'url' => '/accountingcore/settings',
                        'name' => 'Settings',
                        'slug' => 'accountingcore.settings.index',
                    ],
                ],
            ],
        ];
    }

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