<?php

namespace Modules\PMCore\App\Providers;

use App\Services\Settings\SettingsRegistry;
use App\Traits\RegistersMenuItems;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
use Modules\PMCore\App\Models\Project;
use Modules\PMCore\App\Models\Timesheet;
use Modules\PMCore\App\Policies\ProjectPolicy;
use Modules\PMCore\App\Policies\ProjectTaskPolicy;
use Modules\PMCore\App\Policies\TimesheetPolicy;
use Modules\PMCore\App\Settings\PMCoreSettings;
use Nwidart\Modules\Traits\PathNamespace;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;

class PMCoreServiceProvider extends ServiceProvider
{
    use PathNamespace;
    use RegistersMenuItems;

    protected string $name = 'PMCore';

    protected string $nameLower = 'pmcore';

    /**
     * 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 policies
        $this->registerPolicies();

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

        // Register Project as taskable with TaskSystem (when available)
        $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([
            \Modules\PMCore\App\Console\UpdateTimesheetAmounts::class,
        ]);
    }

    /**
     * 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 model policies
     */
    protected function registerPolicies(): void
    {
        Gate::policy(Project::class, ProjectPolicy::class);
        Gate::policy(Timesheet::class, TimesheetPolicy::class);

        // Register TaskSystem Task policy only when TaskSystem is available
        if (moduleExists('TaskSystem')) {
            Gate::policy(\Modules\TaskSystem\App\Models\Task::class, ProjectTaskPolicy::class);
        }
    }

    /**
     * Register module settings
     */
    private function registerModuleSettings(): void
    {
        if (class_exists(SettingsRegistry::class)) {
            $settingsRegistry = app(SettingsRegistry::class);

            $settingsRegistry->registerModule('pmcore', [
                'name' => __('Project Management'),
                'description' => __('Configure project defaults, workflow rules, and management preferences'),
                'icon' => 'bx bx-briefcase',
                'handler' => PMCoreSettings::class,
                'permissions' => [], // Can add permissions if needed
                'order' => 30, // Display order in settings menu
            ]);
        }
    }

    /**
     * Register PMCore entities as taskable types with TaskSystem module.
     * This allows tasks to be created and linked to Projects.
     */
    private function registerTaskableTypes(): void
    {
        // Only register if TaskSystem module is enabled
        if (! function_exists('moduleExists') || ! moduleExists('TaskSystem')) {
            return;
        }

        // Register after app is fully booted to ensure TaskSystem is loaded
        $this->app->booted(function () {
            try {
                $registry = app(\Modules\TaskSystem\App\Services\TaskableRegistryService::class);

                // Register Project as a taskable entity
                $registry->register(
                    'Project',
                    \Modules\PMCore\App\Models\Project::class,
                    route('pmcore.projects.search'),
                    'name'
                );
            } catch (\Exception $e) {
                // TaskSystem module may not be fully loaded yet
                \Illuminate\Support\Facades\Log::debug(
                    'PMCore: 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' => 'Project Management',
                'icon' => 'menu-icon bx bx-folder',
                'roles' => ['super_admin', 'admin', 'hr', 'hr_manager', 'hr_executive'],
                'slug' => [
                    'pmcore.dashboard.index',
                    'pmcore.projects.index',
                    'pmcore.projects.show',
                    'pmcore.projects.create',
                    'pmcore.projects.edit',
                    'pmcore.projects.timesheets',
                    'pmcore.projects.tasks.index',
                    'pmcore.projects.tasks.board',
                    'pmcore.projects.tasks.show',
                    'pmcore.timesheets.index',
                    'pmcore.timesheets.create',
                    'pmcore.timesheets.show',
                    'pmcore.timesheets.edit',
                    'pmcore.timesheets.statistics',
                    'pmcore.resources.index',
                    'pmcore.resources.capacity',
                    'pmcore.resources.create',
                    'pmcore.resources.edit',
                    'pmcore.resources.schedule',
                    'pmcore.reports.index',
                    'pmcore.reports.time',
                    'pmcore.reports.budget',
                    'pmcore.reports.resource',
                    'pmcore.project-statuses.index',
                    'pmcore.settings.index',
                ],
                'submenu' => [
                    [
                        'url' => '/projects/dashboard',
                        'name' => 'Dashboard',
                        'slug' => 'pmcore.dashboard.index',
                    ],
                    [
                        'url' => '/projects',
                        'name' => 'All Projects',
                        'slug' => [
                            'pmcore.projects.index',
                            'pmcore.projects.show',
                            'pmcore.projects.create',
                            'pmcore.projects.edit',
                            'pmcore.projects.timesheets',
                            'pmcore.projects.tasks.index',
                            'pmcore.projects.tasks.board',
                            'pmcore.projects.tasks.show',
                        ],
                    ],
                    [
                        'url' => '/projects/timesheets',
                        'name' => 'Timesheets',
                        'slug' => [
                            'pmcore.timesheets.index',
                            'pmcore.timesheets.create',
                            'pmcore.timesheets.show',
                            'pmcore.timesheets.edit',
                            'pmcore.timesheets.statistics',
                        ],
                    ],
                    [
                        'url' => '/projects/resources',
                        'name' => 'Resources',
                        'slug' => [
                            'pmcore.resources.index',
                            'pmcore.resources.create',
                            'pmcore.resources.edit',
                            'pmcore.resources.schedule',
                        ],
                    ],
                    [
                        'url' => '/projects/resources/capacity',
                        'name' => 'Capacity Planning',
                        'slug' => 'pmcore.resources.capacity',
                    ],
                    [
                        'name' => 'Reports',
                        'slug' => [
                            'pmcore.reports.index',
                            'pmcore.reports.time',
                            'pmcore.reports.budget',
                            'pmcore.reports.resource',
                        ],
                        'submenu' => [
                            [
                                'url' => '/projects/reports',
                                'name' => 'Overview',
                                'slug' => 'pmcore.reports.index',
                            ],
                            [
                                'url' => '/projects/reports/time',
                                'name' => 'Time Report',
                                'slug' => 'pmcore.reports.time',
                            ],
                            [
                                'url' => '/projects/reports/budget',
                                'name' => 'Budget Report',
                                'slug' => 'pmcore.reports.budget',
                            ],
                            [
                                'url' => '/projects/reports/resource',
                                'name' => 'Resource Report',
                                'slug' => 'pmcore.reports.resource',
                            ],
                        ],
                    ],
                    [
                        'url' => '/projects/settings',
                        'name' => 'Settings',
                        'slug' => 'pmcore.settings.index',
                    ],
                ],
            ],
        ];
    }

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