<?php

namespace Modules\CRMCore\App\Providers;

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

class CRMCoreServiceProvider extends ServiceProvider
{
    use PathNamespace;
    use RegistersMenuItems;

    protected string $name = 'CRMCore';

    protected string $nameLower = 'crmcore';

    /**
     * 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'));
        $this->registerSettings();
        $this->registerTaskableTypes();

        // 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 SettingsRegistry
     */
    private function registerSettings(): void
    {
        if (class_exists(SettingsRegistry::class)) {
            $settingsRegistry = app(SettingsRegistry::class);

            $settingsRegistry->registerModule('crmcore', [
                'name' => __('CRM Settings'),
                'icon' => 'bx bx-group',
                'description' => __('Configure CRM module settings including leads, contacts, companies, and customer management'),
                'route' => 'crm.settings.index',
                'handler' => \Modules\CRMCore\App\Services\CRMCoreSettingsHandler::class,
            ]);
        }
    }

    /**
     * Register CRM entities as taskable types with TaskSystem module
     */
    private function registerTaskableTypes(): void
    {
        // Only register if TaskSystem module is enabled
        if (! function_exists('moduleExists') || ! moduleExists('TaskSystem')) {
            return;
        }

        // Register taskable types with TaskableRegistryService
        $this->app->booted(function () {
            try {
                $registry = app(\Modules\TaskSystem\App\Services\TaskableRegistryService::class);

                // Register CRM entity types
                $registry->register(
                    'Customer',
                    \Modules\SystemCore\App\Models\CoreCustomer::class,
                    route('customers.search'),
                    'name'
                );

                $registry->register(
                    'Company',
                    \Modules\CRMCore\App\Models\Company::class,
                    route('companies.selectSearch'),
                    'name'
                );

                $registry->register(
                    'Lead',
                    \Modules\CRMCore\App\Models\Lead::class,
                    route('leads.selectSearch'),
                    'title'
                );

                $registry->register(
                    'Deal',
                    \Modules\CRMCore\App\Models\Deal::class,
                    route('deals.selectSearch'),
                    'title'
                );
            } catch (\Exception $e) {
                // TaskSystem module may not be fully loaded yet
                \Illuminate\Support\Facades\Log::debug('CRMCore: Could not register taskable types: '.$e->getMessage());
            }
        });
    }

    /**
     * Get the menu items for this module.
     *
     * @return array<array<string, mixed>>
     */
    protected function getMenuItems(): array
    {
        return [
            [
                'name' => 'CRM',
                'icon' => 'menu-icon bx bx-group',
                'roles' => ['super_admin', 'admin', 'hr', 'hr_manager', 'hr_executive'],
                'slug' => [
                    'crm.dashboard.index',
                    'companies.index',
                    'customer-groups.index',
                    'leads.index',
                    'deals.index',
                    'settings.leadStatuses.index',
                    'settings.leadSources.index',
                    'settings.dealPipelines.index',
                    'settings.dealStages.index',
                ],
                'submenu' => [
                    [
                        'url' => '/crm/dashboard',
                        'name' => 'Dashboard',
                        'slug' => 'crm.dashboard.index',
                    ],
                    [
                        'url' => '/companies',
                        'name' => 'Companies',
                        'slug' => 'companies.index',
                    ],
                    [
                        'url' => '/customer-groups',
                        'name' => 'Customer Groups',
                        'slug' => 'customer-groups.index',
                    ],
                    [
                        'url' => '/leads',
                        'name' => 'Leads',
                        'slug' => 'leads.index',
                    ],
                    [
                        'url' => '/deals',
                        'name' => 'Deals',
                        'slug' => 'deals.index',
                    ],
                    [
                        'name' => 'Settings',
                        'slug' => [
                            'settings.leadStatuses.index',
                            'settings.leadSources.index',
                            'settings.dealPipelines.index',
                            'settings.dealStages.index',
                            'crmcore.settings.index',
                        ],
                        'submenu' => [
                            [
                                'url' => '/settings/lead-statuses',
                                'name' => 'Lead Statuses',
                                'slug' => 'settings.leadStatuses.index',
                            ],
                            [
                                'url' => '/settings/lead-sources',
                                'name' => 'Lead Sources',
                                'slug' => 'settings.leadSources.index',
                            ],
                            [
                                'url' => '/settings/deal-pipelines',
                                'name' => 'Deal Pipelines',
                                'slug' => 'settings.dealPipelines.index',
                            ],
                            [
                                'url' => '/settings/deal-stages',
                                'name' => 'Deal Stages',
                                'slug' => 'settings.dealStages.index',
                            ],
                            [
                                'url' => '/crmcore/settings',
                                'name' => 'CRM Settings',
                                'slug' => 'crmcore.settings.index',
                            ],
                        ],
                    ],
                ],
            ],
        ];
    }

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