<?php

namespace Modules\ClinicCore\Http\Controllers;

use Illuminate\Routing\Controller;

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

    public function user_permissions()
    {
        return [
            ['value' => 'clinic.access_module',           'label' => __('clinicCore::lang.perm_access_module'),           'default' => true],
            ['value' => 'clinic.manage_departments',       'label' => __('clinicCore::lang.perm_manage_departments'),       'default' => true],
            ['value' => 'clinic.manage_doctors',           'label' => __('clinicCore::lang.perm_manage_doctors'),           'default' => true],
            ['value' => 'clinic.manage_patient_contacts',        'label' => __('clinicCore::lang.perm_manage_patient_contacts'),        'default' => true],
            ['value' => 'clinic.manage_pets',              'label' => __('clinicCore::lang.perm_manage_pets'),              'default' => true],
            ['value' => 'clinic.view_appointments',        'label' => __('clinicCore::lang.perm_view_appointments'),        'default' => true],
            ['value' => 'clinic.manage_appointments',      'label' => __('clinicCore::lang.perm_manage_appointments'),      'default' => true],
            ['value' => 'clinic.manage_prescriptions',     'label' => __('clinicCore::lang.perm_manage_prescriptions'),     'default' => true],
            ['value' => 'clinic.manage_vaccinations',      'label' => __('clinicCore::lang.perm_manage_vaccinations'),      'default' => true],
            ['value' => 'clinic.manage_medicines',         'label' => __('clinicCore::lang.perm_manage_medicines'),         'default' => true],
            ['value' => 'clinic.manage_medical_conditions','label' => __('clinicCore::lang.perm_manage_medical_conditions'),'default' => true],
            ['value' => 'clinic.view_reports',             'label' => __('clinicCore::lang.perm_view_reports'),             'default' => true],
            ['value' => 'clinic.manage_reports',           'label' => __('clinicCore::lang.perm_manage_reports'),           'default' => true],
            ['value' => 'clinic.access_settings',          'label' => __('clinicCore::lang.perm_access_settings'),          'default' => true],
            ['value' => 'clinic.evaluate_pet_owner',       'label' => 'Clinic: Evaluate Patient',                    'default' => true],
            ['value' => 'clinic.evaluate_doctor',          'label' => 'Clinic: Evaluate Doctor / Clinic (patient feedback)', 'default' => true],
            ['value' => 'clinic.manage_evaluation_questions', 'label' => 'Clinic: Manage Evaluation Questions',         'default' => true],
            ['value' => 'clinic.review_evaluations',       'label' => 'Clinic: Review Flagged Evaluations',            'default' => true],
            ['value' => 'clinic.edit_completed_appointments', 'label' => 'Clinic: Edit Completed Appointments (no approval needed)', 'default' => false],
            ['value' => 'clinic.approve_edit_requests',    'label' => 'Clinic: Approve Appointment Edit Requests',     'default' => false],
            ['value' => 'clinic.change_appointment_doctor', 'label' => 'Clinic: Change Appointment Doctor (bypass preferred doctor)', 'default' => false],
            ['value' => 'clinic.approve_doctor_change',    'label' => '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' => 'clinic.manage_owner_blocking',    'label' => 'Clinic: Manage Patient Blocking',                 'default' => false],
            ['value' => 'clinic.view_owner_blocking',      'label' => 'Clinic: View Patient Blocking',                   'default' => false],
            ['value' => 'clinic.view_critical_report',     'label' => 'Clinic: View Medical Critical Check Report',    'default' => true],
            ['value' => 'clinic.manage_exam_templates',    'label' => 'Clinic: Manage Exam Templates',                 'default' => false],
            ['value' => 'clinic.record_exam_findings',     'label' => 'Clinic: Record Exam Findings',                  'default' => true],
            ['value' => 'clinic.view_exam_findings',       'label' => 'Clinic: View Exam Findings',                    'default' => true],
            ['value' => 'clinic.manage_subject_notes',     'label' => 'Clinic: Manage Subject (patient) Notes',      'default' => true],
            ['value' => 'clinic.view_confidential_notes',  'label' => 'Clinic: View Confidential Notes',               'default' => false],
            ['value' => 'clinic.manage_controlled',        'label' => 'Clinic: Manage Controlled Drug Register',       'default' => false],
            ['value' => 'clinic.use_ai_assist',            'label' => 'Clinic: Use AI Medical Assistant',              'default' => false],
            // SIFA P3-T1 / P3-T8 - patient master, structured baseline & alerts.
            ['value' => 'clinic.patient.merge',            'label' => 'Clinic: Merge Duplicate Patients',              'default' => false],
            ['value' => 'clinic.allergy.manage',           'label' => 'Clinic: Manage Allergies / Meds / Insurance',   'default' => true],
            ['value' => 'clinic.alert.manage',             'label' => 'Clinic: Manage Medical Alerts',                 'default' => true],
            ['value' => 'clinic.alert.acknowledge',        'label' => 'Clinic: Acknowledge Medical Alerts',            'default' => true],
            // SIFA P3-T2 / P3-T3 / P3-T4 - encounters, clinical notes & vitals.
            ['value' => 'clinic.note.sign',                'label' => 'Clinic: Sign & Lock Clinical Notes',            'default' => true],
            ['value' => 'clinic.note.amend',               'label' => 'Clinic: Amend Signed Notes',                    'default' => false],
            ['value' => 'clinic.encounter.diagnose',       'label' => 'Clinic: Record Encounter Diagnoses',            'default' => true],
            ['value' => 'clinic.vitals.record',            'label' => 'Clinic: Record Vital Signs',                    'default' => true],
            ['value' => 'clinic.vitals.view_trends',       'label' => 'Clinic: View Vitals Trends',                    'default' => true],
            // SIFA P3-T5 / P3-T6 - prescriptions upgrade & unified orders.
            ['value' => 'clinic.rx.refill',                'label' => 'Clinic: Dispense Prescription Refills',         'default' => true],
            ['value' => 'clinic.order.create',             'label' => 'Clinic: Place Clinical Orders',                 'default' => true],
            ['value' => 'clinic.order.view',               'label' => 'Clinic: View Clinical Orders',                  'default' => true],
            ['value' => 'clinic.order.verify',             'label' => 'Clinic: Verify Order Results',                  'default' => false],
            // SIFA P3-T7 - scheduling upgrade (exceptions, waitlist, queue).
            ['value' => 'clinic.schedule.manage_exceptions', 'label' => 'Clinic: Manage Schedule Exceptions',          'default' => true],
            ['value' => 'clinic.waitlist.manage',          'label' => 'Clinic: Manage Appointment Waitlist',           'default' => true],
            ['value' => 'clinic.queue.view',               'label' => "Clinic: View Today's Queue",                    'default' => true],
            // SIFA P4-T3 / P4-T6 - pharmacy dispensing & referrals.
            ['value' => 'clinic.rx.dispense',              'label' => 'Clinic: Dispense Prescriptions (Pharmacy)',     'default' => true],
            ['value' => 'clinic.referral.manage',          'label' => 'Clinic: Manage Referrals',                      'default' => true],
        ];
    }

    /**
     * Item #7 - SaaS subscription check. Reuses the existing
     * '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 clinic.
     */
    public function clinicCoreSubscribed(): bool
    {
        try {
            $mu = app(\App\Utils\ModuleUtil::class);
            if (!$mu->isSuperadminInstalled()) return true;
            $bizId = (int) session('user.business_id');
            return (bool) $mu->hasThePermissionInSubscription($bizId, '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('clinic.access_module')) return;
        // Per-business module entitlement (DB-driven, immune to the admin
        // Gate::before bypass). Hides the whole Clinic dropdown when this
        // tenant is not entitled to ClinicCore.
        if (!module_entitled('ClinicCore')) return;
        // Item #7 - SaaS subscription gate. Hide the entire ClinicCore
        // dropdown when the clinic's package doesn't include
        // 'clinic_module' (only applies if Superadmin is installed).
        if (!$this->clinicCoreSubscribed()) return;

        \Menu::modify('admin-sidebar-menu', function ($menu) {
            $menu->dropdown(__('clinicCore::lang.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([ClcDashboardController::class, 'index']),
                    __('clinicCore::lang.dashboard'),
                    ['active' => request()->segment(1) == 'clinic' && !request()->segment(2)]
                );
                if ($user->can('clinic.view_appointments') || $user->can('clinic.manage_appointments')) {
                    $sub->url(
                        action([ClcAppointmentController::class, 'index']),
                        __('clinicCore::lang.appointments'),
                        ['active' => request()->segment(2) == 'appointments']
                    );
                    $sub->url(
                        action([ClcAppointmentController::class, 'calendar']),
                        '↳ ' . __('clinicCore::lang.calendar'),
                        ['active' => request()->segment(2) == 'appointments' && request()->segment(3) == 'calendar']
                    );
                }
                // SIFA P3-T7 — Today's queue + Waitlist (daily-flow items, appended
                // under appointments; existing structure untouched, no reorder).
                if ($user->can('clinic.queue.view')) {
                    $sub->url(
                        route('clinic.queue.index'),
                        '↳ ' . __('clinicCore::lang.todays_queue'),
                        ['active' => request()->segment(2) == 'queue']
                    );
                }
                if ($user->can('clinic.waitlist.manage')) {
                    $sub->url(
                        route('clinic.waitlist.index'),
                        '↳ ' . __('clinicCore::lang.waitlist'),
                        ['active' => request()->segment(2) == 'waitlist']
                    );
                }
                if ($user->can('clinic.manage_patient_contacts')) {
                    $sub->url(
                        action([ClcPatientContactController::class, 'index']),
                        __('clinicCore::lang.patient_contacts'),
                        ['active' => request()->segment(2) == 'patient-contacts']
                    );
                }
                if ($user->can('clinic.manage_pets')) {
                    $sub->url(
                        action([ClcPatientController::class, 'index']),
                        __('clinicCore::lang.pets'),
                        ['active' => request()->segment(2) == 'patients']
                    );
                }
                // SIFA P3-T1 - duplicate review / merge (only the one new item,
                // appended under the existing patients menu — no restructuring).
                if ($user->can('clinic.patient.merge')) {
                    $sub->url(
                        route('clinic.patients.duplicates'),
                        '↳ ' . __('clinicCore::lang.duplicates'),
                        ['active' => request()->segment(2) == 'patients-duplicates']
                    );
                }

                // ── 2. CLINICAL ── (nested - collapsed by default) ──
                // Vaccinations only surface for clinic types that immunise.
                $vaxCap = \Modules\ClinicCore\Entities\Services\ClinicCapabilities::businessHas($bizId, 'vaccinations');
                $hasClinical = $user->can('clinic.manage_prescriptions')
                            || $user->can('clinic.rx.dispense')
                            || $user->can('clinic.referral.manage')
                            || $user->can('clinic.order.view')
                            || $user->can('clinic.order.create')
                            || ($user->can('clinic.manage_vaccinations') && $vaxCap)
                            || $user->can('clinic.manage_reports')
                            || $user->can('clinic.view_imaging')
                            || $user->can('clinic.imaging.report')
                            || $user->can('clinic.imaging.verify')
                            || $user->can('clinic.manage_pets');
                if ($hasClinical) {
                    $sub->dropdown(__('Clinical'), function ($sub2) use ($user, $vaxCap) {
                        if ($user->can('clinic.manage_prescriptions')) {
                            $sub2->url(action([ClcPrescriptionController::class, 'index']), __('clinicCore::lang.prescriptions'),
                                ['active' => request()->segment(2) == 'prescriptions']);
                        }
                        // SIFA P4-T3 — pharmacist dispense queue.
                        if ($user->can('clinic.rx.dispense')) {
                            $sub2->url(route('clinic.pharmacy.index'), __('clinicCore::lang.pharmacy_dispense'),
                                ['active' => request()->segment(2) == 'pharmacy']);
                        }
                        // SIFA P4-T6 — referrals.
                        if ($user->can('clinic.referral.manage')) {
                            $sub2->url(route('clinic.referrals.index'), __('clinicCore::lang.referrals'),
                                ['active' => request()->segment(2) == 'referrals']);
                        }
                        // SIFA P3-T6 — unified clinical orders (lab / imaging / procedure).
                        if ($user->can('clinic.order.view') || $user->can('clinic.order.create')) {
                            $sub2->url(action([ClcOrderController::class, 'index']), __('clinicCore::lang.orders'),
                                ['active' => request()->segment(2) == 'orders']);
                        }
                        // SIFA P5-T1 — radiology modality worklist board (was only
                        // reachable from an appointment quick-action). Gated by the
                        // same imaging perms the worklist/report screens check.
                        if ($user->can('clinic.view_imaging') || $user->can('clinic.imaging.report') || $user->can('clinic.imaging.verify')) {
                            $sub2->url(route('clinic.imaging.worklist'), __('Imaging Worklist'),
                                ['active' => request()->segment(2) == 'imaging' && request()->segment(3) == 'worklist']);
                        }
                        if ($user->can('clinic.manage_vaccinations') && $vaxCap) {
                            $sub2->url(action([ClcVaccinationController::class, 'index']), __('clinicCore::lang.vaccinations'),
                                ['active' => request()->segment(2) == 'vaccinations']);
                        }
                        if ($user->can('clinic.manage_reports')) {
                            $sub2->url(action([ClcMedicalReportController::class, 'index']), __('clinicCore::lang.medical_reports'),
                                ['active' => request()->segment(2) == 'medical-reports']);
                        }
                        if ($user->can('clinic.manage_pets')) {
                            $sub2->url(action([ClcBirthDeathRecordController::class, 'index']), __('clinicCore::lang.birth_death_records'),
                                ['active' => request()->segment(2) == 'birth-death']);
                        }
                    }, ['icon' => 'fas fa-stethoscope']);
                }

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

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

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

                // ── 6. TRUST & COMPLIANCE ── (nested) ──
                // Controlled-drug register only surfaces when this clinic type
                // actually handles controlled substances (capability + per-business
                // override), in addition to the permission gate.
                $cdEnabled = \Modules\ClinicCore\Entities\Services\ClinicCapabilities::businessHas($bizId, 'controlled_drugs');
                $hasCompliance = $user->can('clinic.view_owner_blocking')
                              || $user->can('clinic.manage_owner_blocking')
                              || ($user->can('clinic.manage_controlled') && $cdEnabled);
                if ($hasCompliance) {
                    $sub->dropdown(__('Compliance'), function ($sub2) use ($user, $bizId, $countOr, $cdEnabled) {
                        if ($user->can('clinic.view_owner_blocking') || $user->can('clinic.manage_owner_blocking')) {
                            $sub2->url(
                                route('clinic.owner-blocking.index'),
                                $countOr(__('Patient Blocking'), function () use ($bizId) {
                                    return \Modules\ClinicCore\Entities\ClcPatientContactDetail::where('business_id', $bizId)
                                        ->where('is_blocked', true)->count();
                                }),
                                ['active' => request()->segment(2) == 'owner-blocking']
                            );
                        }
                        if ($user->can('clinic.manage_controlled') && $cdEnabled) {
                            $sub2->url(route('clinic.controlled-register.index'), __('Controlled Drug Register'),
                                ['active' => request()->segment(2) == 'controlled-register']);
                            $sub2->url(route('clinic.authorized-vets.index'), __('Authorised Practitioners'),
                                ['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('clinic.access_settings')) {
                    $sub->dropdown(__('Configuration'), function ($sub2) {
                        $sub2->url(action([ClcDepartmentController::class, 'index']), __('clinicCore::lang.departments'),
                            ['active' => request()->segment(2) == 'departments']);
                        $sub2->url(action([ClcDoctorController::class, 'index']), __('clinicCore::lang.doctors'),
                            ['active' => request()->segment(2) == 'doctors']);
                        $sub2->url(route('clinic.locations.index'), __('clinicCore::lang.clinic_locations'),
                            ['active' => request()->segment(2) == 'locations']);
                        $sub2->url(route('clinic.apt-types.index'), __('clinicCore::lang.appointment_types'),
                            ['active' => request()->segment(2) == 'appointment-types']);
                        $sub2->url(route('clinic.apt-reasons.index'), __('clinicCore::lang.appointment_reasons'),
                            ['active' => request()->segment(2) == 'appointment-reasons']);
                        $sub2->url(action([ClcMedicalConditionController::class, 'index']), __('clinicCore::lang.medical_conditions'),
                            ['active' => request()->segment(2) == 'medical-conditions']);
                        $sub2->url(action([ClcVaccineTypeController::class, 'index']), __('clinicCore::lang.vaccine_types'),
                            ['active' => request()->segment(2) == 'vaccine-types']);
                        $sub2->url(route('clinic.consent-templates.index'), __('clinicCore::lang.consent_templates'),
                            ['active' => request()->segment(2) == 'consent-templates']);
                        $sub2->url(route('clinic.soap-options.index'), __('SOAP Options'),
                            ['active' => request()->segment(2) == 'soap-options']);
                        $sub2->url(route('clinic.packages.index'), __('Treatment Packages'),
                            ['active' => request()->segment(2) == 'treatment-packages']);
                        $sub2->url(route('clinic.evaluation-questions.index'), __('Evaluation Questions'),
                            ['active' => request()->segment(2) == 'evaluation-questions']);
                        $sub2->url(route('clinic.role-landing.index'), __('Role Settings'),
                            ['active' => request()->segment(2) == 'role-landing']);
                        $sub2->url(route('clinic.settings.index'), __('clinicCore::lang.module_settings'),
                            ['active' => request()->segment(2) == 'settings' && request()->segment(3) != 'reminders']);
                        $sub2->url(route('clinic.reminders.settings'), __('clinicCore::lang.reminder_settings'),
                            ['active' => request()->segment(2) == 'reminders']);
                        $sub2->url(route('clinic.portal-brand.index'), __('PWA Portal Brand'),
                            ['active' => request()->segment(2) == 'portal-brand']);
                        $sub2->url(route('clinic.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 ClinicCore ones at a glance.
                try {
                    $satellite = app(\App\Utils\ModuleUtil::class)->getModuleData('clinicCoreMenuItems');
                    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-notes-medical'])->order(40);
        });
    }

    /**
     * Core ERP hook: inject clinic pre-fill JS into the POS create screen.
     * Picks up session('clc_preselect_products') set by ClcAppointmentController::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('clc_preselect_products');
        if (empty($payload) || empty($payload['items'])) {
            return [];
        }
        return [
            'module_js_path' => 'clinicCore::pos_bridge.preselect_js',
            'view_data'      => ['clc_preselect' => $payload],
        ];
    }
}
