<?php

namespace Modules\MedRegistry\Http\Controllers;

use App\Utils\ModuleUtil;
use Illuminate\Routing\Controller;

/**
 * Module discovery hooks. The ERP core auto-calls these via
 * App\Utils\ModuleUtil::getModuleData('<method>') — superadmin_package() for
 * the package list, user_permissions() for the role editor, and
 * modifyAdminMenu() to inject the "Medical Modules" section into the admin
 * sidebar. Mirrors Modules\Vrc\Http\Controllers\DataController.
 *
 * getModuleData() only reaches modules that are enabled AND installed
 * (system.medregistry_version), so everything here is implicitly gated by the
 * install version too.
 */
class DataController extends Controller
{
    /**
     * Module entry for the superadmin package manager.
     */
    public function superadmin_package()
    {
        return [
            [
                'name'    => 'medreg_module',
                'label'   => __('medregistry::lang.medreg_module'),
                'default' => false,
            ],
        ];
    }

    /**
     * MedRegistry permissions exposed in the role editor. (Admins bypass these
     * via the core Gate::before for Admin#<business_id>.) The same list is
     * registered as Spatie permissions by migration
     * 2026_07_02_000005_register_medreg_permissions.
     */
    public function user_permissions()
    {
        return [
            ['value' => 'medreg.registry.view',   'label' => 'Medical modules — ' . __('medregistry::lang.perm_registry_view'),   'default' => false],
            ['value' => 'medreg.registry.manage', 'label' => 'Medical modules — ' . __('medregistry::lang.perm_registry_manage'), 'default' => false],
            ['value' => 'medreg.wizard.run',      'label' => 'Medical modules — ' . __('medregistry::lang.perm_wizard_run'),      'default' => false],
            ['value' => 'medreg.settings.manage', 'label' => 'Medical modules — ' . __('medregistry::lang.perm_settings_manage'), 'default' => false],
        ];
    }

    /**
     * Inject the "Medical Modules" section into the admin sidebar
     * (Registry / Module instances / Setup wizard), gated by the SaaS
     * entitlement helper, the medreg_module subscription flag and the
     * medreg.* permissions — mirroring the Vrc menu hook.
     */
    public function modifyAdminMenu()
    {
        // SaaS entitlement gate — keep the section out of the sidebar in host
        // projects not entitled to it. No-op when SaasSwitcher isn't loaded.
        if (function_exists('module_entitled') && ! module_entitled('MedRegistry')) {
            return;
        }

        if (! auth()->check()) {
            return;
        }

        $business_id = session()->get('user.business_id');
        $moduleUtil = new ModuleUtil();

        // Superadmin subscription gate (fallback-allow on hosts without the
        // Superadmin module — same semantics as every other module).
        if (! $moduleUtil->hasThePermissionInSubscription($business_id, 'medreg_module')) {
            return;
        }

        $is_admin = $moduleUtil->is_admin(auth()->user(), $business_id);

        $can_view = auth()->user()->can('medreg.registry.view');
        $can_manage = auth()->user()->can('medreg.registry.manage');
        $can_wizard = $is_admin; // wizard is admin-only (P1-T6)

        if (! $can_view && ! $can_manage && ! $can_wizard) {
            return;
        }

        \Menu::modify('admin-sidebar-menu', function ($menu) use ($can_view, $can_manage, $can_wizard) {
            $menu->dropdown(__('medregistry::lang.medical_modules'), function ($sub) use ($can_view, $can_manage, $can_wizard) {
                $isSeg = fn ($seg1, $seg2 = false) => request()->segment(1) == $seg1
                    && ($seg2 === false || request()->segment(2) == $seg2);

                if ($can_view) {
                    $sub->url(route('medreg.registry.index'), __('medregistry::lang.registry'),
                        ['active' => $isSeg('med-registry', null)]);
                }

                if ($can_manage) {
                    $sub->url(route('medreg.instances.index'), __('medregistry::lang.module_instances'),
                        ['active' => $isSeg('med-registry', 'instances')]);
                }

                if ($can_wizard) {
                    $sub->url(route('medreg.wizard.step1'), __('medregistry::lang.setup_wizard'),
                        ['active' => request()->segment(1) == 'med-setup']);
                }
            }, ['icon' => 'fa fas fa-th-large'])->order(39);
        });
    }
}
