<?php

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

    /**
     * VRC permissions exposed in the role editor. (Admins bypass these via
     * the core Gate::before for Admin#<business_id>.) The full vrc.* surface
     * is declared here up-front; features are gated by these as each phase
     * lands. See spec §2.
     */
    public function user_permissions()
    {
        return [
            ['value' => 'vrc.access',                 'label' => __('vrc::lang.access_vrc'),                  'default' => false],
            ['value' => 'vrc.dashboard.view',         'label' => 'VRC — ' . __('vrc::lang.dashboard'),        'default' => false],

            // Vehicles & catalog
            ['value' => 'vrc.vehicle.view',           'label' => 'VRC — View ' . __('vrc::lang.vehicles'),    'default' => false],
            ['value' => 'vrc.vehicle.manage',         'label' => 'VRC — Manage ' . __('vrc::lang.vehicles'),  'default' => false],
            ['value' => 'vrc.service.view',           'label' => 'VRC — View ' . __('vrc::lang.services'),    'default' => false],
            ['value' => 'vrc.service.manage',         'label' => 'VRC — Manage ' . __('vrc::lang.services'),  'default' => false],

            // Appointments & resources
            ['value' => 'vrc.appointment.view',       'label' => 'VRC — View ' . __('vrc::lang.appointments'),   'default' => false],
            ['value' => 'vrc.appointment.manage',     'label' => 'VRC — Manage ' . __('vrc::lang.appointments'), 'default' => false],
            ['value' => 'vrc.bay.manage',             'label' => 'VRC — Manage ' . __('vrc::lang.bays'),         'default' => false],

            // Repair orders (core)
            ['value' => 'vrc.repair_order.view',      'label' => 'VRC — View ' . __('vrc::lang.repair_orders'),   'default' => false],
            ['value' => 'vrc.repair_order.create',    'label' => 'VRC — Create ' . __('vrc::lang.repair_orders'), 'default' => false],
            ['value' => 'vrc.repair_order.manage',    'label' => 'VRC — Manage ' . __('vrc::lang.repair_orders'), 'default' => false],
            ['value' => 'vrc.repair_order.deliver_with_balance', 'label' => 'VRC — ' . __('vrc::lang.perm_deliver_with_balance'), 'default' => false],

            // Inspections
            ['value' => 'vrc.inspection.view',        'label' => 'VRC — View ' . __('vrc::lang.inspections'),   'default' => false],
            ['value' => 'vrc.inspection.manage',      'label' => 'VRC — Manage ' . __('vrc::lang.inspections'), 'default' => false],
            ['value' => 'vrc.inspection.skip',        'label' => 'VRC — ' . __('vrc::lang.perm_skip_inspection'), 'default' => false],

            // Estimates
            ['value' => 'vrc.estimate.view',          'label' => 'VRC — View ' . __('vrc::lang.estimates'),   'default' => false],
            ['value' => 'vrc.estimate.manage',        'label' => 'VRC — Manage ' . __('vrc::lang.estimates'), 'default' => false],
            ['value' => 'vrc.estimate.approve',       'label' => 'VRC — ' . __('vrc::lang.perm_approve_estimate'), 'default' => false],

            // Technicians & labor
            ['value' => 'vrc.technician.view',        'label' => 'VRC — View ' . __('vrc::lang.technicians'),   'default' => false],
            ['value' => 'vrc.technician.manage',      'label' => 'VRC — Manage ' . __('vrc::lang.technicians'), 'default' => false],

            // Insurance & warranty
            ['value' => 'vrc.insurance.view',         'label' => 'VRC — View ' . __('vrc::lang.insurance'),   'default' => false],
            ['value' => 'vrc.insurance.manage',       'label' => 'VRC — Manage ' . __('vrc::lang.insurance'), 'default' => false],

            // Reminders, reports, settings
            ['value' => 'vrc.reminder.manage',        'label' => 'VRC — Manage ' . __('vrc::lang.reminders'), 'default' => false],
            ['value' => 'vrc.reports.view',           'label' => 'VRC — Reports',  'default' => false],
            ['value' => 'vrc.settings.access',        'label' => 'VRC — Settings', 'default' => false],

            // Workshop routing (work centers + stage board)
            ['value' => 'vrc.workflow.view',          'label' => 'VRC — View workflow board',   'default' => false],
            ['value' => 'vrc.workflow.manage',        'label' => 'VRC — Manage work centers',   'default' => false],

            // Parts storage
            ['value' => 'vrc.storage.view',           'label' => 'VRC — View storage bins',     'default' => false],
            ['value' => 'vrc.storage.manage',         'label' => 'VRC — Manage storage bins',   'default' => false],

            // Support / complaints / CSAT
            ['value' => 'vrc.ticket.view',            'label' => 'VRC — View support tickets',  'default' => false],
            ['value' => 'vrc.ticket.manage',          'label' => 'VRC — Manage support tickets','default' => false],

            // ISO 9001 — quality (documents, NCR, CAPA)
            ['value' => 'vrc.quality.view',           'label' => 'VRC — View quality (ISO 9001)',   'default' => false],
            ['value' => 'vrc.quality.manage',         'label' => 'VRC — Manage quality (ISO 9001)', 'default' => false],

            // ISO 14001 — environmental
            ['value' => 'vrc.environment.view',       'label' => 'VRC — View environmental (ISO 14001)',   'default' => false],
            ['value' => 'vrc.environment.manage',     'label' => 'VRC — Manage environmental (ISO 14001)', 'default' => false],

            // ISO 45001 — health & safety
            ['value' => 'vrc.safety.view',            'label' => 'VRC — View safety (ISO 45001)',   'default' => false],
            ['value' => 'vrc.safety.manage',          'label' => 'VRC — Manage safety (ISO 45001)', 'default' => false],

            // ISO 18541 — RMI access; customer portal admin
            ['value' => 'vrc.rmi.view',               'label' => 'VRC — Repair info (RMI)',         'default' => false],
            ['value' => 'vrc.portal.manage',          'label' => 'VRC — Manage customer portal',    'default' => false],
        ];
    }

    /**
     * Inject a "Vehicles & service history" tab into the core contact detail
     * page. Auto-called by the core via
     * ModuleUtil::getModuleData('get_contact_view_tabs'); rendered by
     * resources/views/contact/show.blade.php. Only shown to users who can view
     * VRC vehicles.
     */
    public function get_contact_view_tabs()
    {
        // SaaS entitlement gate (data check, immune to the Admin#<biz> Gate::before
        // bypass) — hides VRC where the active business isn't entitled. No-op when
        // the SaasSwitcher helper isn't loaded, so the module stays portable.
        if (function_exists('module_entitled') && ! module_entitled('Vrc')) {
            return [];
        }

        if (! auth()->check() || ! auth()->user()->can('vrc.vehicle.view')) {
            return [];
        }

        return [
            [
                'tab_menu_path'    => 'vrc::contact.vehicles_tab_menu',
                'tab_content_path' => 'vrc::contact.vehicles_tab_content',
                'tab_data'         => [],
            ],
        ];
    }

    /**
     * Inject the Vehicle Repair (VRC) section into the admin sidebar.
     *
     * Phase 0 only exposes the dashboard link (it is the only route that
     * exists yet). Each subsequent phase adds its own sub-items here, gated
     * by the matching vrc.* permission — exactly like the BMS module.
     */
    public function modifyAdminMenu()
    {
        // SaaS entitlement gate — keep the VRC section out of the sidebar in
        // projects not entitled to it (e.g. the vet/shifa/static tenants), even
        // for Admins who bypass the can() check. No-op outside SaasSwitcher.
        if (function_exists('module_entitled') && ! module_entitled('Vrc')) {
            return;
        }

        if (! auth()->check() || ! auth()->user()->can('vrc.access')) {
            return;
        }

        \Menu::modify('admin-sidebar-menu', function ($menu) {
            $menu->dropdown(__('vrc::lang.vrc_module'), function ($sub) {
                $sub->url(route('vrc.dashboard'), __('vrc::lang.dashboard'),
                    ['active' => request()->segment(1) == 'vrc' && request()->segment(2) == null]);

                $isSeg = fn ($seg) => request()->segment(1) == 'vrc' && request()->segment(2) == $seg;

                if (auth()->user()->can('vrc.repair_order.view')) {
                    $sub->url(route('vrc.repair-orders.index'), __('vrc::lang.repair_orders'), ['active' => $isSeg('repair-orders')]);
                }

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

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

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

                if (auth()->user()->can('vrc.service.view')) {
                    $sub->url(route('vrc.services.index'), __('vrc::lang.services'), ['active' => $isSeg('services') || $isSeg('service-categories')]);
                    $sub->url(route('vrc.service-packages.index'), __('vrc::lang.packages'), ['active' => $isSeg('service-packages')]);
                }

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

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

                if (auth()->user()->can('vrc.repair_order.manage')) {
                    $sub->url(route('vrc.procurement.to-order'), __('vrc::lang.parts_to_order'), ['active' => $isSeg('procurement')]);
                }

                if (auth()->user()->can('vrc.vehicle.manage')) {
                    $sub->url(route('vrc.vehicle-makes.index'), __('vrc::lang.vehicle_makes'), ['active' => $isSeg('vehicle-makes')]);
                    $sub->url(route('vrc.vehicle-models.index'), __('vrc::lang.vehicle_models'), ['active' => $isSeg('vehicle-models-admin')]);
                }

                if (auth()->user()->can('vrc.inspection.manage')) {
                    $sub->url(route('vrc.inspection-templates.index'), __('vrc::lang.inspection_templates'), ['active' => $isSeg('inspection-templates')]);
                }

                if (auth()->user()->can('vrc.insurance.manage')) {
                    $sub->url(route('vrc.insurance-companies.index'), __('vrc::lang.insurance_companies'), ['active' => $isSeg('insurance-companies')]);
                }

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

                if (auth()->user()->can('vrc.reminder.manage')) {
                    $sub->url(route('vrc.service-reminders.index'), __('vrc::lang.reminders'), ['active' => $isSeg('service-reminders')]);
                }

                if (auth()->user()->can('vrc.workflow.view')) {
                    $sub->url(route('vrc.workflow.board'), 'Workflow board', ['active' => $isSeg('workflow')]);
                }

                if (auth()->user()->can('vrc.ticket.view')) {
                    $sub->url(route('vrc.tickets.index'), 'Support tickets', ['active' => $isSeg('tickets')]);
                }

                if (auth()->user()->can('vrc.rmi.view')) {
                    $sub->url(route('vrc.rmi.index'), 'Repair info (RMI)', ['active' => $isSeg('rmi')]);
                }

                if (auth()->user()->can('vrc.workflow.manage')) {
                    $sub->url(route('vrc.work-centers.index'), 'Work centers', ['active' => $isSeg('work-centers')]);
                }

                if (auth()->user()->can('vrc.storage.view')) {
                    $sub->url(route('vrc.storage-bins.index'), 'Storage bins', ['active' => $isSeg('storage-bins')]);
                }

                if (auth()->user()->can('vrc.technician.manage')) {
                    $sub->url(route('vrc.technician-certifications.index'), 'Technician certs', ['active' => $isSeg('technician-certifications')]);
                }

                if (auth()->user()->can('vrc.portal.manage')) {
                    $sub->url(route('vrc.portal-accounts.index'), 'Customer portal', ['active' => $isSeg('portal-accounts')]);
                }

                if (auth()->user()->can('vrc.settings.access')) {
                    $sub->url(route('vrc.service-plans.index'), __('vrc::lang.service_plans'), ['active' => $isSeg('service-plans')]);
                    $sub->url(route('vrc.settings.edit'), __('vrc::lang.settings'),
                        ['active' => request()->segment(1) == 'vrc' && request()->segment(2) == 'settings']);
                }
            }, ['icon' => 'fa fas fa-car'])->order(37);

            // VRC — Compliance (ISO 9001 / 14001 / 45001). Separate dropdown so the
            // workshop menu stays focused; each link is gated by its own permission.
            if (auth()->user()->canAny(['vrc.quality.view', 'vrc.environment.view', 'vrc.safety.view'])) {
                $menu->dropdown('Compliance (ISO)', function ($sub) {
                    $isSeg2 = fn ($a, $b) => request()->segment(1) == 'vrc' && request()->segment(2) == $a && request()->segment(3) == $b;

                    if (auth()->user()->can('vrc.quality.view')) {
                        $sub->url(route('vrc.quality.documents.index'), 'Documents / SOPs (9001)', ['active' => $isSeg2('quality', 'documents')]);
                        $sub->url(route('vrc.quality.ncrs.index'), 'Non-conformance (9001)', ['active' => $isSeg2('quality', 'ncrs')]);
                        $sub->url(route('vrc.quality.capas.index'), 'CAPA actions (9001)', ['active' => $isSeg2('quality', 'capas')]);
                    }
                    if (auth()->user()->can('vrc.environment.view')) {
                        $sub->url(route('vrc.env.waste-streams.index'), 'Waste streams (14001)', ['active' => $isSeg2('env', 'waste-streams')]);
                        $sub->url(route('vrc.env.waste-disposals.index'), 'Waste log (14001)', ['active' => $isSeg2('env', 'waste-disposals')]);
                        $sub->url(route('vrc.env.aspects.index'), 'Env. aspects (14001)', ['active' => $isSeg2('env', 'aspects')]);
                    }
                    if (auth()->user()->can('vrc.safety.view')) {
                        $sub->url(route('vrc.safety.hazards.index'), 'Hazards / risk (45001)', ['active' => $isSeg2('safety', 'hazards')]);
                        $sub->url(route('vrc.safety.incidents.index'), 'Incidents (45001)', ['active' => $isSeg2('safety', 'incidents')]);
                        $sub->url(route('vrc.safety.trainings.index'), 'Safety training (45001)', ['active' => $isSeg2('safety', 'trainings')]);
                    }
                }, ['icon' => 'fa fas fa-clipboard-check'])->order(38);
            }
        });
    }
}
