<?php

namespace Modules\MedOrganization\Http\Controllers;

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 Organization section into the admin
 * sidebar. Mirrors Modules\Vrc\Http\Controllers\DataController.
 */
class DataController extends Controller
{
    /**
     * Module entry for the superadmin package manager.
     */
    public function superadmin_package()
    {
        return [
            [
                'name'    => 'medorg_module',
                'label'   => __('medorganization::lang.medorg_module'),
                'default' => false,
            ],
        ];
    }

    /**
     * MedOrganization permissions exposed in the role editor. (Admins bypass
     * these via the core Gate::before for Admin#<business_id>.)
     */
    public function user_permissions()
    {
        return [
            ['value' => 'medorg.facility.view',           'label' => 'Organization — ' . __('medorganization::lang.perm_facility_view'),      'default' => false],
            ['value' => 'medorg.facility.manage',         'label' => 'Organization — ' . __('medorganization::lang.perm_facility_manage'),    'default' => false],
            ['value' => 'medorg.department.manage',       'label' => 'Organization — ' . __('medorganization::lang.perm_department_manage'),  'default' => false],
            ['value' => 'medorg.room.manage',             'label' => 'Organization — ' . __('medorganization::lang.perm_room_manage'),        'default' => false],
            ['value' => 'medorg.license.view',            'label' => 'Organization — ' . __('medorganization::lang.perm_license_view'),       'default' => false],
            ['value' => 'medorg.license.manage',          'label' => 'Organization — ' . __('medorganization::lang.perm_license_manage'),     'default' => false],
            ['value' => 'medorg.license.verify',          'label' => 'Organization — ' . __('medorganization::lang.perm_license_verify'),     'default' => false],
            ['value' => 'medorg.access_rules.manage',     'label' => 'Organization — ' . __('medorganization::lang.perm_access_rules'),       'default' => false],
            ['value' => 'medorg.access_all_departments',  'label' => 'Organization — ' . __('medorganization::lang.perm_all_departments'),    'default' => false],
        ];
    }

    /**
     * SaaS subscription gate — mirrors ClinicCore's clinicCoreSubscribed().
     * True when Superadmin isn't installed (single-tenant) or when the
     * current business's package includes 'medorg_module'.
     */
    public function medOrgSubscribed(): bool
    {
        try {
            $mu = app(\App\Utils\ModuleUtil::class);
            if (! $mu->isSuperadminInstalled()) {
                return true;
            }
            $bizId = (int) session('user.business_id');

            return (bool) $mu->hasThePermissionInSubscription($bizId, 'medorg_module', 'superadmin_package');
        } catch (\Throwable $e) {
            // Fail-open: a misconfigured SaaS layer must not lock
            // single-tenant installs out of the module entirely.
            return true;
        }
    }

    /**
     * Inject the "Organization" section into the admin sidebar, mirroring
     * exactly how Vrc/ClinicCore gate their menus:
     *   1. install gate — the lowercase {module}_version System property;
     *   2. per-business entitlement (SaasSwitcher helper, if loaded);
     *   3. SaaS subscription flag 'medorg_module';
     *   4. per-user medorg.* permissions per item.
     */
    public function modifyAdminMenu()
    {
        // 1. Install gate (System property written by InstallController).
        try {
            if (empty(\App\System::getProperty('medorganization_version'))) {
                return;
            }
        } catch (\Throwable $e) {
            return;
        }

        // 2. Per-business module entitlement (immune to the Admin Gate::before bypass).
        if (function_exists('module_entitled') && ! module_entitled('MedOrganization')) {
            return;
        }

        // 3. SaaS subscription gate.
        if (! $this->medOrgSubscribed()) {
            return;
        }

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

        $user = auth()->user();
        if (! $user->canAny([
            'medorg.facility.view', 'medorg.facility.manage', 'medorg.department.manage',
            'medorg.room.manage', 'medorg.license.view', 'medorg.license.manage',
            'medorg.access_rules.manage',
        ])) {
            return;
        }

        \Menu::modify('admin-sidebar-menu', function ($menu) {
            $menu->dropdown(__('medorganization::lang.organization'), function ($sub) {
                $isSeg = fn ($seg) => request()->segment(1) == 'med-org' && request()->segment(2) == $seg;

                if (auth()->user()->can('medorg.facility.view')) {
                    $sub->url(route('medorg.facilities.index'), __('medorganization::lang.facilities'), ['active' => $isSeg('facilities')]);
                }

                if (auth()->user()->can('medorg.department.manage')) {
                    $sub->url(route('medorg.departments.index'), __('medorganization::lang.departments'), ['active' => $isSeg('departments')]);
                    $sub->url(route('medorg.staff-assignments.index'), __('medorganization::lang.staff_assignments'), ['active' => $isSeg('staff-assignments')]);
                }

                if (auth()->user()->can('medorg.room.manage')) {
                    $sub->url(route('medorg.rooms.index'), __('medorganization::lang.rooms'), ['active' => $isSeg('rooms')]);
                }

                if (auth()->user()->can('medorg.license.view')) {
                    $sub->url(route('medorg.licenses.index'), __('medorganization::lang.licenses'), ['active' => $isSeg('licenses')]);
                }

                if (auth()->user()->can('medorg.access_rules.manage')) {
                    $sub->url(route('medorg.access-rules.index'), __('medorganization::lang.access_rules'), ['active' => $isSeg('access-rules')]);
                }
            }, ['icon' => 'fa fas fa-hospital'])->order(36);
        });
    }
}
