<?php

namespace Modules\VetClinic\Http\Controllers;

use Illuminate\Routing\Controller;

class DataController extends Controller
{
    public function superadmin_package()
    {
        return [
            [
                'name'    => 'vet_clinic',
                'label'   => __('vetClinic::lang.vet_clinic_module'),
                'default' => false,
            ]
        ];
    }

    public function user_permissions()
    {
        return [
            ['value' => 'vet_clinic.access_module',           'label' => __('vetClinic::lang.perm_access_module'),           'default' => true],
            ['value' => 'vet_clinic.manage_departments',       'label' => __('vetClinic::lang.perm_manage_departments'),       'default' => true],
            ['value' => 'vet_clinic.manage_doctors',           'label' => __('vetClinic::lang.perm_manage_doctors'),           'default' => true],
            ['value' => 'vet_clinic.manage_pet_owners',        'label' => __('vetClinic::lang.perm_manage_pet_owners'),        'default' => true],
            ['value' => 'vet_clinic.manage_pets',              'label' => __('vetClinic::lang.perm_manage_pets'),              'default' => true],
            ['value' => 'vet_clinic.view_appointments',        'label' => __('vetClinic::lang.perm_view_appointments'),        'default' => true],
            ['value' => 'vet_clinic.manage_appointments',      'label' => __('vetClinic::lang.perm_manage_appointments'),      'default' => true],
            ['value' => 'vet_clinic.manage_prescriptions',     'label' => __('vetClinic::lang.perm_manage_prescriptions'),     'default' => true],
            ['value' => 'vet_clinic.manage_vaccinations',      'label' => __('vetClinic::lang.perm_manage_vaccinations'),      'default' => true],
            ['value' => 'vet_clinic.manage_medicines',         'label' => __('vetClinic::lang.perm_manage_medicines'),         'default' => true],
            ['value' => 'vet_clinic.manage_medical_conditions','label' => __('vetClinic::lang.perm_manage_medical_conditions'),'default' => true],
            ['value' => 'vet_clinic.view_reports',             'label' => __('vetClinic::lang.perm_view_reports'),             'default' => true],
            ['value' => 'vet_clinic.manage_reports',           'label' => __('vetClinic::lang.perm_manage_reports'),           'default' => true],
            ['value' => 'vet_clinic.access_settings',          'label' => __('vetClinic::lang.perm_access_settings'),          'default' => true],
            ['value' => 'vet_clinic.evaluate_pet_owner',       'label' => 'Vet Clinic: Evaluate Pet Owner',                    'default' => true],
            ['value' => 'vet_clinic.evaluate_doctor',          'label' => 'Vet Clinic: Evaluate Doctor / Clinic (pet owner feedback)', 'default' => true],
            ['value' => 'vet_clinic.manage_evaluation_questions', 'label' => 'Vet Clinic: Manage Evaluation Questions',         'default' => true],
            ['value' => 'vet_clinic.review_evaluations',       'label' => 'Vet Clinic: Review Flagged Evaluations',            'default' => true],
            ['value' => 'vet_clinic.edit_completed_appointments', 'label' => 'Vet Clinic: Edit Completed Appointments (no approval needed)', 'default' => false],
            ['value' => 'vet_clinic.approve_edit_requests',    'label' => 'Vet Clinic: Approve Appointment Edit Requests',     'default' => false],
            ['value' => 'vet_clinic.change_appointment_doctor', 'label' => 'Vet Clinic: Change Appointment Doctor (bypass preferred doctor)', 'default' => false],
            ['value' => 'vet_clinic.approve_doctor_change',    'label' => 'Vet Clinic: Approve Doctor-Change Requests',        'default' => false],
            // Item #7 - new permissions from recent feature waves must be
            // surfaced here so SaaS package admins can grant them per-package.
            ['value' => 'vet_clinic.manage_owner_blocking',    'label' => 'Vet Clinic: Manage Owner Blocking',                 'default' => false],
            ['value' => 'vet_clinic.view_owner_blocking',      'label' => 'Vet Clinic: View Owner Blocking',                   'default' => false],
            ['value' => 'vet_clinic.view_critical_report',     'label' => 'Vet Clinic: View Medical Critical Check Report',    'default' => true],
            ['value' => 'vet_clinic.manage_exam_templates',    'label' => 'Vet Clinic: Manage Exam Templates',                 'default' => false],
            ['value' => 'vet_clinic.record_exam_findings',     'label' => 'Vet Clinic: Record Exam Findings',                  'default' => true],
            ['value' => 'vet_clinic.view_exam_findings',       'label' => 'Vet Clinic: View Exam Findings',                    'default' => true],
            ['value' => 'vet_clinic.manage_subject_notes',     'label' => 'Vet Clinic: Manage Subject (owner/pet) Notes',      'default' => true],
            ['value' => 'vet_clinic.view_confidential_notes',  'label' => 'Vet Clinic: View Confidential Notes',               'default' => false],
            ['value' => 'vet_clinic.manage_controlled',        'label' => 'Vet Clinic: Manage Controlled Drug Register',       'default' => false],
        ];
    }

    /**
     * Item #7 - SaaS subscription check. Reuses the existing
     * 'vet_clinic' package key declared in superadmin_package() at the
     * top of this file (don't create a parallel one). Returns true when
     * Superadmin isn't installed (single-tenant install) or when the
     * current business's package includes vet_clinic.
     */
    public function vetClinicSubscribed(): bool
    {
        try {
            $mu = app(\App\Utils\ModuleUtil::class);
            if (!$mu->isSuperadminInstalled()) return true;
            $bizId = (int) session('user.business_id');
            return (bool) $mu->hasThePermissionInSubscription($bizId, 'vet_clinic', 'superadmin_package');
        } catch (\Throwable $e) {
            // Fail-open: when SaaS infra is misconfigured, don't lock
            // single-tenant clinics out of the module entirely.
            return true;
        }
    }

    public function modifyAdminMenu()
    {
        if (!auth()->user()->can('vet_clinic.access_module')) return;
        // Per-business module entitlement (DB-driven, immune to the admin
        // Gate::before bypass). Hides the whole Vet dropdown when this tenant
        // is not entitled to VetClinic.
        if (!module_entitled('VetClinic')) return;
        // Item #7 - SaaS subscription gate. Hide the entire VetClinic
        // dropdown when the clinic's package doesn't include
        // 'vet_clinic_module' (only applies if Superadmin is installed).
        if (!$this->vetClinicSubscribed()) return;

        \Menu::modify('admin-sidebar-menu', function ($menu) {
            $menu->dropdown(__('vetClinic::lang.vet_clinic'), function ($sub) {
                $user    = auth()->user();
                $bizId   = session('user.business_id');
                $countOr = function ($label, callable $countFn) {
                    try {
                        $n = $countFn();
                        return $n > 0 ? $label . ' (' . $n . ')' : $label;
                    } catch (\Throwable $e) { return $label; }
                };

                // ── 1. DAILY WORK ── (flat - the most-used items stay
                //    immediately clickable, no extra expand step) ──
                $sub->url(
                    action([VcDashboardController::class, 'index']),
                    __('vetClinic::lang.dashboard'),
                    ['active' => request()->segment(1) == 'vet-clinic' && !request()->segment(2)]
                );
                if ($user->can('vet_clinic.view_appointments') || $user->can('vet_clinic.manage_appointments')) {
                    $sub->url(
                        action([VcAppointmentController::class, 'index']),
                        __('vetClinic::lang.appointments'),
                        ['active' => request()->segment(2) == 'appointments']
                    );
                    $sub->url(
                        action([VcAppointmentController::class, 'calendar']),
                        '↳ ' . __('vetClinic::lang.calendar'),
                        ['active' => request()->segment(2) == 'appointments' && request()->segment(3) == 'calendar']
                    );
                }
                if ($user->can('vet_clinic.manage_pet_owners')) {
                    $sub->url(
                        action([VcPetOwnerController::class, 'index']),
                        __('vetClinic::lang.pet_owners'),
                        ['active' => request()->segment(2) == 'pet-owners']
                    );
                }
                if ($user->can('vet_clinic.manage_pets')) {
                    $sub->url(
                        action([VcPetController::class, 'index']),
                        __('vetClinic::lang.pets'),
                        ['active' => request()->segment(2) == 'pets']
                    );
                }

                // ── 2. CLINICAL ── (nested - collapsed by default) ──
                $hasClinical = $user->can('vet_clinic.manage_prescriptions')
                            || $user->can('vet_clinic.manage_vaccinations')
                            || $user->can('vet_clinic.manage_reports')
                            || $user->can('vet_clinic.manage_pets');
                if ($hasClinical) {
                    $sub->dropdown(__('Clinical'), function ($sub2) use ($user) {
                        if ($user->can('vet_clinic.manage_prescriptions')) {
                            $sub2->url(action([VcPrescriptionController::class, 'index']), __('vetClinic::lang.prescriptions'),
                                ['active' => request()->segment(2) == 'prescriptions']);
                        }
                        if ($user->can('vet_clinic.manage_vaccinations')) {
                            $sub2->url(action([VcVaccinationController::class, 'index']), __('vetClinic::lang.vaccinations'),
                                ['active' => request()->segment(2) == 'vaccinations']);
                        }
                        if ($user->can('vet_clinic.manage_reports')) {
                            $sub2->url(action([VcMedicalReportController::class, 'index']), __('vetClinic::lang.medical_reports'),
                                ['active' => request()->segment(2) == 'medical-reports']);
                        }
                        if ($user->can('vet_clinic.manage_pets')) {
                            $sub2->url(action([VcBirthDeathRecordController::class, 'index']), __('vetClinic::lang.birth_death_records'),
                                ['active' => request()->segment(2) == 'birth-death']);
                        }
                    }, ['icon' => 'fas fa-stethoscope']);
                }

                // ── 3. PHARMACY ──
                if ($user->can('vet_clinic.manage_medicines')) {
                    $sub->url(
                        action([VcMedicineController::class, 'index']),
                        __('vetClinic::lang.pharmacy'),
                        ['active' => request()->segment(2) == 'medicines']
                    );
                }

                // ── 4. REPORTS & ANALYTICS ── (nested) ──
                $hasReports = $user->can('vet_clinic.view_reports')
                           || $user->can('vet_clinic.manage_appointments')
                           || $user->can('vet_clinic.manage_exam_templates');
                if ($hasReports) {
                    $sub->dropdown(__('Reports & Analytics'), function ($sub2) use ($user) {
                        if ($user->can('vet_clinic.view_reports')) {
                            $sub2->url(route('vc.reports.kpi'), __('KPI Dashboard'),
                                ['active' => request()->segment(2) == 'reports' && request()->segment(3) == 'kpi']);
                            $sub2->url(action([VcReportController::class, 'index']), __('vetClinic::lang.reports'),
                                ['active' => request()->segment(2) == 'reports' && request()->segment(3) != 'kpi']);
                        }
                        if ($user->can('vet_clinic.view_reports') || $user->can('vet_clinic.manage_appointments')) {
                            $sub2->url(route('vc.vital-ranges.index'), __('Vital Ranges'),
                                ['active' => request()->segment(2) == 'vital-ranges']);
                        }
                        if ($user->can('vet_clinic.access_settings') || $user->can('vet_clinic.manage_exam_templates')) {
                            $sub2->url(route('vc.system-findings.index'), __('Exam Checklists'),
                                ['active' => request()->segment(2) == 'system-findings']);
                        }
                    }, ['icon' => 'fas fa-chart-line']);
                }

                // ── 5. APPROVALS & WORKFLOW ── (nested) ──
                $hasApprovals = $user->can('vet_clinic.approve_edit_requests')
                             || $user->can('vet_clinic.approve_doctor_change');
                if ($hasApprovals) {
                    $sub->dropdown(__('Approvals'), function ($sub2) use ($user, $bizId, $countOr) {
                        if ($user->can('vet_clinic.approve_edit_requests')) {
                            $sub2->url(
                                route('vc.edit-requests.index'),
                                $countOr(__('vetClinic::lang.edit_requests'), function () use ($bizId) {
                                    return \Modules\VetClinic\Entities\VcAppointmentEditRequest::where('business_id', $bizId)
                                        ->where('status', 'pending')->count();
                                }),
                                ['active' => request()->segment(2) == 'appointment-edit-requests']
                            );
                        }
                        if ($user->can('vet_clinic.approve_doctor_change')) {
                            $sub2->url(
                                route('vc.doctor-change-requests.index'),
                                $countOr(__('vetClinic::lang.doctor_change_requests'), function () use ($bizId) {
                                    return \Modules\VetClinic\Entities\VcDoctorChangeRequest::where('business_id', $bizId)
                                        ->where('status', 'pending')->count();
                                }),
                                ['active' => request()->segment(2) == 'doctor-change-requests']
                            );
                        }
                    }, ['icon' => 'fas fa-tasks']);
                }

                // ── 6. TRUST & COMPLIANCE ── (nested) ──
                $hasCompliance = $user->can('vet_clinic.view_owner_blocking')
                              || $user->can('vet_clinic.manage_owner_blocking')
                              || $user->can('vet_clinic.manage_controlled');
                if ($hasCompliance) {
                    $sub->dropdown(__('Compliance'), function ($sub2) use ($user, $bizId, $countOr) {
                        if ($user->can('vet_clinic.view_owner_blocking') || $user->can('vet_clinic.manage_owner_blocking')) {
                            $sub2->url(
                                route('vc.owner-blocking.index'),
                                $countOr(__('Owner Blocking'), function () use ($bizId) {
                                    return \Modules\VetClinic\Entities\VcPetOwnerDetail::where('business_id', $bizId)
                                        ->where('is_blocked', true)->count();
                                }),
                                ['active' => request()->segment(2) == 'owner-blocking']
                            );
                        }
                        if ($user->can('vet_clinic.manage_controlled')) {
                            $sub2->url(route('vc.controlled-register.index'), __('Controlled Drug Register'),
                                ['active' => request()->segment(2) == 'controlled-register']);
                            $sub2->url(route('vc.authorized-vets.index'), __('Authorised Vets'),
                                ['active' => request()->segment(2) == 'authorized-vets']);
                        }
                    }, ['icon' => 'fas fa-shield-alt']);
                }

                // ── 7. CONFIGURATION ── (nested - the biggest group;
                //    nesting collapses ~15 items down to one toggle) ──
                if ($user->can('vet_clinic.access_settings')) {
                    $sub->dropdown(__('Configuration'), function ($sub2) {
                        $sub2->url(action([VcDepartmentController::class, 'index']), __('vetClinic::lang.departments'),
                            ['active' => request()->segment(2) == 'departments']);
                        $sub2->url(action([VcDoctorController::class, 'index']), __('vetClinic::lang.doctors'),
                            ['active' => request()->segment(2) == 'doctors']);
                        $sub2->url(route('vc.locations.index'), __('vetClinic::lang.clinic_locations'),
                            ['active' => request()->segment(2) == 'locations']);
                        $sub2->url(route('vc.apt-types.index'), __('vetClinic::lang.appointment_types'),
                            ['active' => request()->segment(2) == 'appointment-types']);
                        $sub2->url(route('vc.apt-reasons.index'), __('vetClinic::lang.appointment_reasons'),
                            ['active' => request()->segment(2) == 'appointment-reasons']);
                        $sub2->url(action([VcMedicalConditionController::class, 'index']), __('vetClinic::lang.medical_conditions'),
                            ['active' => request()->segment(2) == 'medical-conditions']);
                        $sub2->url(action([VcVaccineTypeController::class, 'index']), __('vetClinic::lang.vaccine_types'),
                            ['active' => request()->segment(2) == 'vaccine-types']);
                        $sub2->url(route('vc.consent-templates.index'), __('vetClinic::lang.consent_templates'),
                            ['active' => request()->segment(2) == 'consent-templates']);
                        $sub2->url(route('vc.soap-options.index'), __('SOAP Options'),
                            ['active' => request()->segment(2) == 'soap-options']);
                        $sub2->url(route('vc.evaluation-questions.index'), __('Evaluation Questions'),
                            ['active' => request()->segment(2) == 'evaluation-questions']);
                        $sub2->url(route('vc.role-landing.index'), __('Role Settings'),
                            ['active' => request()->segment(2) == 'role-landing']);
                        $sub2->url(route('vc.settings.index'), __('vetClinic::lang.module_settings'),
                            ['active' => request()->segment(2) == 'settings' && request()->segment(3) != 'reminders']);
                        $sub2->url(route('vc.reminders.settings'), __('vetClinic::lang.reminder_settings'),
                            ['active' => request()->segment(2) == 'reminders']);
                        $sub2->url(route('vc.portal-brand.index'), __('PWA Portal Brand'),
                            ['active' => request()->segment(2) == 'portal-brand']);
                        $sub2->url(route('vc.portal-engagement.index'), __('PWA Engagement'),
                            ['active' => request()->segment(2) == 'portal-engagement']);
                    }, ['icon' => 'fas fa-cog']);
                }

                // ── 8. EXTENSIONS (satellite modules: VetAI, VetAdmission, VetPortal) ──
                // Surfaced under their own collapsible so the user can tell
                // modular features from core VetClinic ones at a glance.
                try {
                    $satellite = app(\App\Utils\ModuleUtil::class)->getModuleData('vetClinicMenuItems');
                    if (!empty($satellite)) {
                        $sub->dropdown(__('Extensions'), function ($sub2) use ($satellite) {
                            foreach ($satellite as $contribution) {
                                if ($contribution instanceof \Closure) {
                                    $contribution($sub2);
                                }
                            }
                        }, ['icon' => 'fas fa-puzzle-piece']);
                    }
                } catch (\Throwable $e) {
                    // A satellite module must never break the Vet Clinic sidebar.
                }

            }, ['icon' => 'fas fa-paw'])->order(40);
        });
    }

    /**
     * Core ERP hook: inject vet-clinic pre-fill JS into the POS create screen.
     * Picks up session('vc_preselect_products') set by VcAppointmentController::launchPos
     * and auto-adds each item to the invoice using POS's existing pos_product_row().
     */
    public function get_pos_screen_view($data = [])
    {
        $payload = session()->pull('vc_preselect_products');
        if (empty($payload) || empty($payload['items'])) {
            return [];
        }
        return [
            'module_js_path' => 'vetClinic::pos_bridge.preselect_js',
            'view_data'      => ['vc_preselect' => $payload],
        ];
    }
}
