<?php

namespace Modules\MedNotify\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, modifyAdminMenu()
 * to inject the "Notifications (Medical)" section into the admin sidebar and
 * parse_notification() so MedNotify in-app rows render in the existing bell
 * dropdown. Mirrors Modules\Vrc\Http\Controllers\DataController.
 *
 * getModuleData() only reaches modules that are enabled AND installed
 * (system.mednotify_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'    => 'mednotify_module',
                'label'   => __('mednotify::lang.mednotify_module'),
                'default' => false,
            ],
        ];
    }

    /**
     * MedNotify 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_100006_register_mednotify_permissions.
     */
    public function user_permissions()
    {
        return [
            ['value' => 'mednotify.templates.manage',      'label' => __('mednotify::lang.mednotify_module') . ' — ' . __('mednotify::lang.perm_templates_manage'),      'default' => false],
            ['value' => 'mednotify.preferences.manage_own', 'label' => __('mednotify::lang.mednotify_module') . ' — ' . __('mednotify::lang.perm_preferences_manage_own'), 'default' => false],
            ['value' => 'mednotify.log.view',              'label' => __('mednotify::lang.mednotify_module') . ' — ' . __('mednotify::lang.perm_log_view'),               'default' => false],
        ];
    }

    /**
     * Inject the "Notifications (Medical)" section into the admin sidebar
     * (Templates / My preferences / Log), gated EXACTLY like Vrc: the SaaS
     * entitlement helper, the mednotify_module subscription flag and the
     * mednotify.* permissions (getModuleData already implies the install gate).
     */
    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('MedNotify')) {
            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, 'mednotify_module')) {
            return;
        }

        $can_templates = auth()->user()->can('mednotify.templates.manage');
        $can_prefs = auth()->user()->can('mednotify.preferences.manage_own');
        $can_log = auth()->user()->can('mednotify.log.view');

        if (! $can_templates && ! $can_prefs && ! $can_log) {
            return;
        }

        \Menu::modify('admin-sidebar-menu', function ($menu) use ($can_templates, $can_prefs, $can_log) {
            $menu->dropdown(__('mednotify::lang.notifications_medical'), function ($sub) use ($can_templates, $can_prefs, $can_log) {
                $isSeg = fn ($seg) => request()->segment(1) == 'med-notify' && request()->segment(2) == $seg;

                if ($can_templates) {
                    $sub->url(route('mednotify.templates.index'), __('mednotify::lang.templates'),
                        ['active' => $isSeg('templates')]);
                }

                if ($can_prefs) {
                    $sub->url(route('mednotify.preferences.edit'), __('mednotify::lang.my_preferences'),
                        ['active' => $isSeg('preferences')]);
                }

                if ($can_log) {
                    $sub->url(route('mednotify.log.index'), __('mednotify::lang.log'),
                        ['active' => $isSeg('log')]);
                }
            }, ['icon' => 'fa fas fa-bell'])->order(40);
        });
    }

    /**
     * Render MedNotify in-app rows in the core bell dropdown. Auto-called by
     * App\Utils\Util::getNotifications() via getModuleData('parse_notification').
     * Returns the standard notification-data shape the dropdown expects, or an
     * empty array for notification types this module doesn't own.
     */
    public function parse_notification($notification)
    {
        $notification_data = [];

        if ($notification->type === \Modules\MedNotify\Notifications\MedNotifyNotification::class) {
            $data = $notification->data;

            $msg = ! empty($data['subject']) ? $data['subject'] : ($data['body'] ?? '');

            $notification_data = [
                'msg'        => strip_tags((string) $msg),
                'icon_class' => ! empty($data['icon_class']) ? $data['icon_class'] : 'fas fa-bell bg-blue',
                'link'       => ! empty($data['link']) ? $data['link'] : '#',
                'read_at'    => $notification->read_at,
                'created_at' => $notification->created_at->diffForHumans(),
            ];
        }

        return $notification_data;
    }
}
