<?php

namespace Mtc\Modules\SiteMenu\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Cache;
use Mtc\Core\Admin\Menu;
use Mtc\Modules\SiteMenu\Services\SiteMenuRenderer;

/**
 * Site Menu module service provider.
 *
 * Registers the module's routes, migrations, config and admin Twig template
 * path. Front-end menu rendering is wired to the legacy `load_site_menu` hook
 * (see registerHooks) and the admin menu link is injected/repointed to the
 * modern /admin/site-menu route.
 */
class SiteMenuServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        $this->mergeConfigFrom(__DIR__ . '/../config/site_menu.php', 'site_menu');
        $this->loadMigrationsFrom(__DIR__ . '/../database/migrations');

        $routes = __DIR__ . '/../routes/site_menu.php';
        if (file_exists($routes)) {
            $this->loadRoutesFrom($routes);
        }

        // Pharmacy platform uses custom twig template loaders; register the
        // module's admin template directory with the view finder. Guarded with
        // is_dir() because the view finder throws on a non-existent path.
        $templates = __DIR__ . '/../templates';
        if (is_dir($templates)) {
            $view_paths = config('view.paths');
            $view_paths[] = $templates;
            config(['view.paths' => $view_paths]);
        }

        $this->registerHooks();

        if (!app()->runningInConsole()) {
            $this->injectAdminMenuItems();
        }
    }

    /**
     * Point the admin sidebar "Site Menu" link at the modern /admin/site-menu
     * route (repointing the row the legacy plugin installed, or creating one).
     * Cached so it only touches the DB once per deploy.
     */
    protected function injectAdminMenuItems(): void
    {
        if (!class_exists(Menu::class)) {
            return;
        }

        $cacheKey = 'admin_menu:site_menu_pointed';
        if (Cache::get($cacheKey) === true) {
            return;
        }

        try {
            Menu::query()->updateOrInsert(
                ['title' => 'Site Menu'],
                [
                    'path'       => '/admin/site-menu',
                    'activePath' => '/admin/site-menu',
                    'icon'       => 'fa fa-indent',
                    'new_window' => 0,
                ]
            );
            Cache::forever($cacheKey, true);
        } catch (\Throwable $e) {
            // Non-fatal: the admin link can be repaired manually if this fails.
        }
    }

    /**
     * Register the front-end render hook. Template authors keep calling
     * {{ hooks_do_action('load_site_menu', 'Menu Name') }} unchanged. This
     * module now owns the hook entirely (the legacy plugins/SiteMenu plugin
     * has been removed).
     */
    protected function registerHooks(): void
    {
        if (class_exists(\HooksAdapter::class)) {
            \HooksAdapter::add_action(
                'load_site_menu',
                [SiteMenuRenderer::class, 'renderMenu'],
                10, // priority
                1   // accepted args (the menu name)
            );
        }
    }

    public function register(): void
    {
    }
}
