<?php

namespace App\Http\Controllers\Care;

use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Http\Controllers\Controller;
use App\Models\Appointment;
use App\Models\Department;
use App\Models\InvestigationType;
use App\Models\PatientAttachment;
use App\Models\Visit;
use App\Services\Care\Ambulance\AmbulanceDispatchBoardService;
use App\Services\Care\AppointmentService;
use App\Services\Care\CareQueueBridge;
use App\Services\Care\CareQueueSessionAdvance;
use App\Services\Care\ConsultationService;
use App\Services\Care\OrganizationResolver;
use App\Services\Care\SpecialtyClinicalRecordService;
use App\Services\Care\SpecialtyModuleService;
use App\Services\Care\SpecialtyShellService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class SpecialtyModuleController extends Controller
{
    use ScopesToAccount;

    public function show(
        Request $request,
        string $module,
        SpecialtyModuleService $modules,
        SpecialtyShellService $shell,
        CareQueueBridge $queueBridge,
    ): View|RedirectResponse {
        // Nursing Services is an ops hub (roster / registry), not a patient specialty shell.
        if ($module === 'nursing_services') {
            $this->authorizeAbility($request, 'nursing.services.view');

            return redirect()->route('care.nursing.services');
        }

        // Everyone lands on the specialty list/index — never auto-open a patient.
        return $this->renderShell($request, $module, 'visits', $modules, $shell, $queueBridge);
    }

    public function visits(
        Request $request,
        string $module,
        SpecialtyModuleService $modules,
        SpecialtyShellService $shell,
        CareQueueBridge $queueBridge,
    ): View {
        return $this->renderShell($request, $module, 'visits', $modules, $shell, $queueBridge);
    }

    public function history(
        Request $request,
        string $module,
        SpecialtyModuleService $modules,
        SpecialtyShellService $shell,
        CareQueueBridge $queueBridge,
    ): View {
        return $this->renderShell($request, $module, 'history', $modules, $shell, $queueBridge);
    }

    public function billing(
        Request $request,
        string $module,
        SpecialtyModuleService $modules,
        SpecialtyShellService $shell,
        CareQueueBridge $queueBridge,
    ): View {
        return $this->renderShell($request, $module, 'billing', $modules, $shell, $queueBridge);
    }

    public function workspace(
        Request $request,
        string $module,
        SpecialtyModuleService $modules,
        SpecialtyShellService $shell,
        CareQueueBridge $queueBridge,
        ?Visit $visit = null,
    ): View|RedirectResponse {
        // Bare /workspace (no visit) is the old auto-open entry — send users to the list.
        if ($visit === null) {
            return redirect()->route('care.specialty.show', $module);
        }

        return $this->renderShell($request, $module, 'workspace', $modules, $shell, $queueBridge, $visit);
    }

    public function addService(
        Request $request,
        string $module,
        Visit $visit,
        SpecialtyModuleService $modules,
        SpecialtyShellService $shell,
    ): RedirectResponse {
        $definition = $modules->definition($module);
        abort_unless($definition, 404);

        $organization = $this->organization($request);
        $member = $this->member($request);
        abort_unless($modules->memberCanAccess($organization, $member, $module), 403);
        abort_unless($modules->memberCanManage($organization, $member, $module), 403);
        abort_unless($visit->organization_id === $organization->id, 404);

        $validated = $request->validate([
            'service_code' => ['required', 'string', 'max:64'],
        ]);

        try {
            $bill = $shell->addCatalogServiceToVisit(
                $organization,
                $visit,
                $module,
                $validated['service_code'],
                $this->ownerRef($request),
                $this->ownerRef($request),
            );
        } catch (\Throwable $e) {
            return back()->with('error', $e->getMessage());
        }

        return back()->with('success', 'Added to invoice '.$bill->invoice_number.'.');
    }

    public function startConsultation(
        Request $request,
        string $module,
        Visit $visit,
        SpecialtyModuleService $modules,
        AppointmentService $appointments,
        ConsultationService $consultations,
    ): RedirectResponse {
        $this->authorizeAbility($request, 'consultations.manage');

        $definition = $modules->definition($module);
        abort_unless($definition, 404);

        $organization = $this->organization($request);
        $member = $this->member($request);
        abort_unless($modules->memberCanAccess($organization, $member, $module), 403);
        abort_unless($modules->memberCanManage($organization, $member, $module), 403);
        abort_unless($visit->organization_id === $organization->id, 404);
        $this->authorizeBranch($request, (int) $visit->branch_id);

        $visit->loadMissing(['appointment.consultation', 'appointment.practitioner']);
        $appointment = $visit->appointment;
        if (! $appointment || $appointment->organization_id !== $organization->id) {
            return back()->with('error', 'This visit has no appointment to start a consultation from.');
        }

        $owner = $this->ownerRef($request);
        $openConsultation = $appointment->consultation;
        if ($openConsultation && $openConsultation->status !== \App\Models\Consultation::STATUS_COMPLETED) {
            $clinical = app(SpecialtyClinicalRecordService::class);
            $shellTabs = app(SpecialtyShellService::class)->workspaceTabs($module);
            $preferredTab = match ($module) {
                'dentistry' => 'odontogram',
                'emergency' => 'triage',
                'blood_bank' => 'requests',
                'ophthalmology' => 'refraction',
                'physiotherapy' => 'assessment',
                'womens_health' => 'history',
                'radiology' => 'protocol',
                'cardiology' => 'history',
                'psychiatry' => 'history',
                'pediatrics' => 'history',
                'orthopedics' => 'history',
                'ent' => 'history',
                'oncology' => 'history',
                'renal' => 'history',
                'surgery' => 'history',
                'vaccination' => 'eligibility',
                'pathology' => 'request',
                'infusion' => 'assessment',
                'dermatology' => 'history',
                'podiatry' => 'history',
                'fertility' => 'history',
                'child_welfare' => 'intake',
                'ambulance' => 'dispatch',
                default => (collect(array_keys($shellTabs))
                    ->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null)
                    ?? 'clinical_notes'),
            };

            return redirect()
                ->route('care.specialty.workspace', [
                    'module' => $module,
                    'visit' => $visit,
                    'tab' => $preferredTab,
                ])
                ->with('success', 'Encounter already in progress.');
        }

        try {
            if (in_array($appointment->status, [
                Appointment::STATUS_WAITING,
                Appointment::STATUS_CHECKED_IN,
            ], true)) {
                $appointments->startConsultation(
                    $appointment,
                    $owner,
                    $appointment->practitioner_id,
                    $owner,
                );
                $appointment = $appointment->fresh(['practitioner', 'visit']);
            } elseif ($appointment->status !== Appointment::STATUS_IN_CONSULTATION) {
                return back()->with('error', 'This appointment cannot start a consultation from its current status.');
            }

            $consultations->startFromAppointment(
                $appointment,
                $owner,
                $owner,
            );
        } catch (\InvalidArgumentException $e) {
            return back()->with('error', $e->getMessage());
        }

        $visit = $visit->fresh() ?? $appointment->visit;
        if ($visit) {
            $stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
            $nextStage = $stageService->stageOnConsultationStart($module);
            if ($nextStage && ! $visit->specialty_stage) {
                try {
                    $stageService->setStage(
                        $organization,
                        $visit,
                        $module,
                        $nextStage,
                        $owner,
                        $owner,
                    );
                    $visit = $visit->fresh();
                } catch (\InvalidArgumentException) {
                    // Stage map may be empty for some modules.
                }
            } elseif ($nextStage && in_array($visit->specialty_stage, ['waiting', 'arrival', 'request', 'check_in'], true)) {
                try {
                    $stageService->setStage($organization, $visit, $module, $nextStage, $owner, $owner);
                    $visit = $visit->fresh();
                } catch (\InvalidArgumentException) {
                }
            }
        }
        $clinical = app(SpecialtyClinicalRecordService::class);
        $shellTabs = app(SpecialtyShellService::class)->workspaceTabs($module);
        $preferredTab = match ($module) {
            'dentistry' => 'odontogram',
            'emergency' => 'triage',
            'blood_bank' => 'requests',
            'ophthalmology' => 'refraction',
            'physiotherapy' => 'assessment',
            'womens_health' => 'history',
            'radiology' => 'protocol',
            'cardiology' => 'history',
            'psychiatry' => 'history',
            'pediatrics' => 'history',
            'orthopedics' => 'history',
            'ent' => 'history',
            'oncology' => 'history',
            'renal' => 'history',
            'surgery' => 'history',
            'vaccination' => 'eligibility',
            'pathology' => 'request',
            'infusion' => 'assessment',
            'dermatology' => 'history',
            'podiatry' => 'history',
            'fertility' => 'history',
            'child_welfare' => 'intake',
            'ambulance' => 'dispatch',
            default => (collect(array_keys($shellTabs))
                ->first(fn (string $tab) => $clinical->recordTypeForTab($module, $tab) !== null)
                ?? 'clinical_notes'),
        };

        return redirect()
            ->route('care.specialty.workspace', [
                'module' => $module,
                'visit' => $visit,
                'tab' => $preferredTab,
            ])
            ->with('success', 'Encounter started.');
    }

    public function saveClinical(
        Request $request,
        string $module,
        Visit $visit,
        SpecialtyModuleService $modules,
        SpecialtyClinicalRecordService $clinical,
    ): RedirectResponse {
        $definition = $modules->definition($module);
        abort_unless($definition, 404);

        $organization = $this->organization($request);
        $member = $this->member($request);
        abort_unless($modules->memberCanAccess($organization, $member, $module), 403);
        abort_unless($modules->memberCanManage($organization, $member, $module), 403);
        abort_unless($visit->organization_id === $organization->id, 404);

        $tab = (string) $request->input('tab', '');
        $recordType = $clinical->recordTypeForTab($module, $tab);
        abort_unless($recordType, 422);

        // Normalize checkbox booleans before validation.
        $payload = (array) $request->input('payload', []);
        foreach ($clinical->fieldsFor($module, $recordType) as $field) {
            if (($field['type'] ?? '') === 'boolean') {
                $payload[$field['name']] = $request->boolean('payload.'.$field['name']);
            }
        }
        $request->merge(['payload' => $payload]);

        $validated = $request->validate(array_merge([
            'tab' => ['required', 'string'],
            'stage_code' => ['nullable', 'string', 'max:64'],
            'status' => ['nullable', 'in:draft,active,completed'],
        ], $clinical->validationRules($module, $recordType)));

        $record = $clinical->upsert(
            $organization,
            $visit,
            $module,
            $recordType,
            $clinical->payloadFromRequest($validated),
            $this->ownerRef($request),
            $this->ownerRef($request),
            $validated['stage_code'] ?? null,
            $validated['status'] ?? \App\Models\SpecialtyClinicalRecord::STATUS_ACTIVE,
        );

        if ($module === 'emergency' && $recordType === 'triage') {
            $workflow = app(\App\Services\Care\Emergency\EmergencyWorkflowService::class);
            $stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
            $suggested = $workflow->stageFromTriage($record->payload ?? []);
            $current = $visit->specialty_stage;
            if (! $current || in_array($current, ['arrival', 'waiting'], true)) {
                try {
                    $stageService->setStage(
                        $organization,
                        $visit,
                        'emergency',
                        $suggested,
                        $this->ownerRef($request),
                        $this->ownerRef($request),
                    );
                } catch (\InvalidArgumentException) {
                }
            }
        }

        if ($module === 'emergency' && $recordType === 'observation') {
            $stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
            try {
                $stageService->setStage(
                    $organization,
                    $visit,
                    'emergency',
                    \App\Services\Care\Emergency\EmergencyWorkflowService::STAGE_OBSERVATION,
                    $this->ownerRef($request),
                    $this->ownerRef($request),
                );
            } catch (\InvalidArgumentException) {
            }
        }

        if ($module === 'blood_bank' && $recordType === 'blood_request') {
            $workflow = app(\App\Services\Care\BloodBank\BloodBankWorkflowService::class);
            $stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
            $suggested = $workflow->stageFromRequest($record->payload ?? []);
            $current = $visit->specialty_stage;
            if (! $current || in_array($current, ['request', 'waiting'], true)) {
                try {
                    $stageService->setStage(
                        $organization,
                        $visit,
                        'blood_bank',
                        $suggested,
                        $this->ownerRef($request),
                        $this->ownerRef($request),
                    );
                } catch (\InvalidArgumentException) {
                }
            } elseif ($suggested !== $current && in_array($suggested, ['crossmatch', 'issue'], true)) {
                // Advance when cross-match / issue status progresses on an existing request.
                $order = ['request' => 0, 'crossmatch' => 1, 'issue' => 2, 'transfusion' => 3, 'completed' => 4];
                if (($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
                    try {
                        $stageService->setStage(
                            $organization,
                            $visit,
                            'blood_bank',
                            $suggested,
                            $this->ownerRef($request),
                            $this->ownerRef($request),
                        );
                    } catch (\InvalidArgumentException) {
                    }
                }
            }
        }

        if ($module === 'ophthalmology' && in_array($recordType, ['refraction', 'eye_exam', 'eye_investigation', 'eye_plan'], true)) {
            $workflow = app(\App\Services\Care\Ophthalmology\OphthalmologyWorkflowService::class);
            $stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
            $suggested = match ($recordType) {
                'refraction' => $workflow->stageFromRefraction($record->payload ?? []),
                'eye_exam' => $workflow->stageFromExam($record->payload ?? []),
                'eye_investigation' => \App\Services\Care\Ophthalmology\OphthalmologyWorkflowService::STAGE_INVESTIGATION,
                'eye_plan' => $workflow->stageFromPlan($record->payload ?? []),
                default => null,
            };
            $current = $visit->specialty_stage;
            $early = ['check_in', 'history', 'waiting', null, ''];
            if ($suggested && (! $current || in_array($current, $early, true))) {
                try {
                    $stageService->setStage(
                        $organization,
                        $visit,
                        'ophthalmology',
                        $suggested,
                        $this->ownerRef($request),
                        $this->ownerRef($request),
                    );
                } catch (\InvalidArgumentException) {
                }
            } elseif ($suggested && $suggested !== $current) {
                $order = [
                    'check_in' => 0,
                    'history' => 1,
                    'refraction' => 2,
                    'exam' => 3,
                    'investigation' => 4,
                    'plan' => 5,
                    'treatment' => 6,
                    'completed' => 7,
                ];
                if (($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
                    try {
                        $stageService->setStage(
                            $organization,
                            $visit,
                            'ophthalmology',
                            $suggested,
                            $this->ownerRef($request),
                            $this->ownerRef($request),
                        );
                    } catch (\InvalidArgumentException) {
                    }
                }
            }
        }


        if ($module === 'physiotherapy' && in_array($recordType, ['pt_assessment', 'pt_plan', 'pt_session', 'pt_home_program'], true)) {
            $workflow = app(\App\Services\Care\Physiotherapy\PhysiotherapyWorkflowService::class);
            $stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
            $suggested = match ($recordType) {
                'pt_assessment' => $workflow->stageFromAssessment($record->payload ?? []),
                'pt_plan' => $workflow->stageFromPlan($record->payload ?? []),
                'pt_session' => $workflow->stageFromSession($record->payload ?? []),
                'pt_home_program' => $workflow->stageFromHomeProgram($record->payload ?? []),
                default => null,
            };
            $current = $visit->specialty_stage;
            $early = ['check_in', 'waiting', null, ''];
            $order = [
                'check_in' => 0,
                'assessment' => 1,
                'treatment_plan' => 2,
                'session' => 3,
                'progress' => 4,
                'completed' => 5,
            ];
            if ($suggested && (! $current || in_array($current, $early, true))) {
                try {
                    $stageService->setStage(
                        $organization,
                        $visit,
                        'physiotherapy',
                        $suggested,
                        $this->ownerRef($request),
                        $this->ownerRef($request),
                    );
                } catch (\InvalidArgumentException) {
                }
            } elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
                try {
                    $stageService->setStage(
                        $organization,
                        $visit,
                        'physiotherapy',
                        $suggested,
                        $this->ownerRef($request),
                        $this->ownerRef($request),
                    );
                } catch (\InvalidArgumentException) {
                }
            }
        }

        if ($module === 'womens_health' && in_array($recordType, ['anc_history', 'obstetric_exam', 'fetal_notes', 'mat_investigation', 'mat_plan'], true)) {
            $workflow = app(\App\Services\Care\WomensHealth\WomensHealthWorkflowService::class);
            $stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
            $suggested = match ($recordType) {
                'anc_history' => $workflow->stageFromHistory($record->payload ?? []),
                'obstetric_exam' => $workflow->stageFromExam($record->payload ?? []),
                'fetal_notes' => $workflow->stageFromFetal($record->payload ?? []),
                'mat_investigation' => \App\Services\Care\WomensHealth\WomensHealthWorkflowService::STAGE_INVESTIGATION,
                'mat_plan' => $workflow->stageFromPlan($record->payload ?? []),
                default => null,
            };
            $current = $visit->specialty_stage;
            $early = ['check_in', 'waiting', null, ''];
            $order = [
                'check_in' => 0,
                'history' => 1,
                'exam' => 2,
                'investigation' => 3,
                'plan' => 4,
                'postnatal' => 5,
                'completed' => 6,
            ];
            if ($suggested && (! $current || in_array($current, $early, true))) {
                try {
                    $stageService->setStage(
                        $organization,
                        $visit,
                        'womens_health',
                        $suggested,
                        $this->ownerRef($request),
                        $this->ownerRef($request),
                    );
                } catch (\InvalidArgumentException) {
                }
            } elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
                try {
                    $stageService->setStage(
                        $organization,
                        $visit,
                        'womens_health',
                        $suggested,
                        $this->ownerRef($request),
                        $this->ownerRef($request),
                    );
                } catch (\InvalidArgumentException) {
                }
            }
        }

        if ($module === 'radiology' && in_array($recordType, ['imaging_request', 'imaging_acquisition', 'imaging_report'], true)) {
            $workflow = app(\App\Services\Care\Radiology\RadiologyWorkflowService::class);
            $stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
            $suggested = match ($recordType) {
                'imaging_request' => $workflow->stageFromRequest($record->payload ?? []),
                'imaging_acquisition' => $workflow->stageFromAcquisition($record->payload ?? []),
                'imaging_report' => $workflow->stageFromReport($record->payload ?? []),
                default => null,
            };
            $current = $visit->specialty_stage;
            $early = ['check_in', 'waiting', 'request', null, ''];
            $order = [
                'check_in' => 0,
                'protocol' => 1,
                'acquisition' => 2,
                'reporting' => 3,
                'verified' => 4,
                'completed' => 5,
            ];
            if ($suggested && (! $current || in_array($current, $early, true))) {
                try {
                    $stageService->setStage(
                        $organization,
                        $visit,
                        'radiology',
                        $suggested,
                        $this->ownerRef($request),
                        $this->ownerRef($request),
                    );
                } catch (\InvalidArgumentException) {
                }
            } elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
                try {
                    $stageService->setStage(
                        $organization,
                        $visit,
                        'radiology',
                        $suggested,
                        $this->ownerRef($request),
                        $this->ownerRef($request),
                    );
                } catch (\InvalidArgumentException) {
                }
            }
        }

        if ($module === 'cardiology' && in_array($recordType, ['cardio_history', 'cardiac_exam', 'cardio_investigation', 'cardio_plan'], true)) {
            $workflow = app(\App\Services\Care\Cardiology\CardiologyWorkflowService::class);
            $stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
            $suggested = match ($recordType) {
                'cardio_history' => $workflow->stageFromHistory($record->payload ?? []),
                'cardiac_exam' => $workflow->stageFromExam($record->payload ?? []),
                'cardio_investigation' => $workflow->stageFromInvestigation($record->payload ?? []),
                'cardio_plan' => $workflow->stageFromPlan($record->payload ?? []),
                default => null,
            };
            $current = $visit->specialty_stage;
            $early = ['check_in', 'waiting', null, ''];
            $order = [
                'check_in' => 0,
                'history' => 1,
                'exam' => 2,
                'investigation' => 3,
                'plan' => 4,
                'procedure' => 5,
                'completed' => 6,
            ];
            if ($suggested && (! $current || in_array($current, $early, true))) {
                try {
                    $stageService->setStage(
                        $organization,
                        $visit,
                        'cardiology',
                        $suggested,
                        $this->ownerRef($request),
                        $this->ownerRef($request),
                    );
                } catch (\InvalidArgumentException) {
                }
            } elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
                try {
                    $stageService->setStage(
                        $organization,
                        $visit,
                        'cardiology',
                        $suggested,
                        $this->ownerRef($request),
                        $this->ownerRef($request),
                    );
                } catch (\InvalidArgumentException) {
                }
            }
        }

        if ($module === 'psychiatry' && in_array($recordType, ['mental_status', 'risk_assessment', 'psych_plan'], true)) {
            $workflow = app(\App\Services\Care\Psychiatry\PsychiatryWorkflowService::class);
            $stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
            $suggested = match ($recordType) {
                'mental_status' => $workflow->stageFromHistory($record->payload ?? []),
                'risk_assessment' => $workflow->stageFromRisk($record->payload ?? []),
                'psych_plan' => $workflow->stageFromFormulation($record->payload ?? []),
                default => null,
            };
            $current = $visit->specialty_stage;
            $early = ['check_in', 'waiting', null, ''];
            $order = [
                'check_in' => 0,
                'history' => 1,
                'risk' => 2,
                'formulation' => 3,
                'review' => 4,
                'completed' => 5,
            ];
            if ($suggested && (! $current || in_array($current, $early, true))) {
                try {
                    $stageService->setStage(
                        $organization,
                        $visit,
                        'psychiatry',
                        $suggested,
                        $this->ownerRef($request),
                        $this->ownerRef($request),
                    );
                } catch (\InvalidArgumentException) {
                }
            } elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
                try {
                    $stageService->setStage(
                        $organization,
                        $visit,
                        'psychiatry',
                        $suggested,
                        $this->ownerRef($request),
                        $this->ownerRef($request),
                    );
                } catch (\InvalidArgumentException) {
                }
            }
        }

        if ($module === 'pediatrics' && in_array($recordType, ['ped_history', 'pediatric_exam', 'ped_investigation', 'ped_plan'], true)) {
            $workflow = app(\App\Services\Care\Pediatrics\PediatricsWorkflowService::class);
            $stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
            $suggested = match ($recordType) {
                'ped_history' => $workflow->stageFromHistory($record->payload ?? []),
                'pediatric_exam' => $workflow->stageFromExam($record->payload ?? []),
                'ped_investigation' => $workflow->stageFromInvestigation($record->payload ?? []),
                'ped_plan' => $workflow->stageFromPlan($record->payload ?? []),
                default => null,
            };
            $current = $visit->specialty_stage;
            $early = ['check_in', 'waiting', null, ''];
            $order = [
                'check_in' => 0,
                'history' => 1,
                'exam' => 2,
                'investigation' => 3,
                'plan' => 4,
                'treatment' => 5,
                'completed' => 6,
            ];
            if ($suggested && (! $current || in_array($current, $early, true))) {
                try {
                    $stageService->setStage(
                        $organization,
                        $visit,
                        'pediatrics',
                        $suggested,
                        $this->ownerRef($request),
                        $this->ownerRef($request),
                    );
                } catch (\InvalidArgumentException) {
                }
            } elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
                try {
                    $stageService->setStage(
                        $organization,
                        $visit,
                        'pediatrics',
                        $suggested,
                        $this->ownerRef($request),
                        $this->ownerRef($request),
                    );
                } catch (\InvalidArgumentException) {
                }
            }
        }

        if ($module === 'orthopedics' && in_array($recordType, ['ortho_history', 'ortho_exam', 'ortho_imaging', 'ortho_plan'], true)) {
            $workflow = app(\App\Services\Care\Orthopedics\OrthopedicsWorkflowService::class);
            $stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
            $suggested = match ($recordType) {
                'ortho_history' => $workflow->stageFromHistory($record->payload ?? []),
                'ortho_exam' => $workflow->stageFromExam($record->payload ?? []),
                'ortho_imaging' => $workflow->stageFromImaging($record->payload ?? []),
                'ortho_plan' => $workflow->stageFromPlan($record->payload ?? []),
                default => null,
            };
            $current = $visit->specialty_stage;
            $early = ['check_in', 'waiting', null, ''];
            $order = [
                'check_in' => 0,
                'history' => 1,
                'exam' => 2,
                'imaging' => 3,
                'plan' => 4,
                'procedure' => 5,
                'completed' => 6,
            ];
            if ($suggested && (! $current || in_array($current, $early, true))) {
                try {
                    $stageService->setStage(
                        $organization,
                        $visit,
                        'orthopedics',
                        $suggested,
                        $this->ownerRef($request),
                        $this->ownerRef($request),
                    );
                } catch (\InvalidArgumentException) {
                }
            } elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
                try {
                    $stageService->setStage(
                        $organization,
                        $visit,
                        'orthopedics',
                        $suggested,
                        $this->ownerRef($request),
                        $this->ownerRef($request),
                    );
                } catch (\InvalidArgumentException) {
                }
            }
        }

        if ($module === 'ent' && in_array($recordType, ['ent_history', 'ent_exam', 'ent_investigation', 'ent_plan'], true)) {
            $workflow = app(\App\Services\Care\Ent\EntWorkflowService::class);
            $stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
            $suggested = match ($recordType) {
                'ent_history' => $workflow->stageFromHistory($record->payload ?? []),
                'ent_exam' => $workflow->stageFromExam($record->payload ?? []),
                'ent_investigation' => $workflow->stageFromInvestigation($record->payload ?? []),
                'ent_plan' => $workflow->stageFromPlan($record->payload ?? []),
                default => null,
            };
            $current = $visit->specialty_stage;
            $early = ['check_in', 'waiting', null, ''];
            $order = [
                'check_in' => 0,
                'history' => 1,
                'exam' => 2,
                'investigation' => 3,
                'plan' => 4,
                'procedure' => 5,
                'completed' => 6,
            ];
            if ($suggested && (! $current || in_array($current, $early, true))) {
                try {
                    $stageService->setStage(
                        $organization,
                        $visit,
                        'ent',
                        $suggested,
                        $this->ownerRef($request),
                        $this->ownerRef($request),
                    );
                } catch (\InvalidArgumentException) {
                }
            } elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
                try {
                    $stageService->setStage(
                        $organization,
                        $visit,
                        'ent',
                        $suggested,
                        $this->ownerRef($request),
                        $this->ownerRef($request),
                    );
                } catch (\InvalidArgumentException) {
                }
            }
        }


        if ($module === 'oncology' && in_array($recordType, ['onc_history', 'onc_staging', 'onc_investigation', 'onc_plan'], true)) {
            $workflow = app(\App\Services\Care\Oncology\OncologyWorkflowService::class);
            $stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
            $suggested = match ($recordType) {
                'onc_history' => $workflow->stageFromHistory($record->payload ?? []),
                'onc_staging' => $workflow->stageFromStaging($record->payload ?? []),
                'onc_investigation' => $workflow->stageFromInvestigation($record->payload ?? []),
                'onc_plan' => $workflow->stageFromPlan($record->payload ?? []),
                default => null,
            };
            $current = $visit->specialty_stage;
            $early = ['check_in', 'waiting', null, ''];
            $order = [
                'check_in' => 0,
                'history' => 1,
                'staging' => 2,
                'investigation' => 3,
                'plan' => 4,
                'treatment' => 5,
                'completed' => 6,
            ];
            if ($suggested && (! $current || in_array($current, $early, true))) {
                try {
                    $stageService->setStage($organization, $visit, 'oncology', $suggested, $this->ownerRef($request), $this->ownerRef($request));
                } catch (\InvalidArgumentException) {
                }
            } elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
                try {
                    $stageService->setStage($organization, $visit, 'oncology', $suggested, $this->ownerRef($request), $this->ownerRef($request));
                } catch (\InvalidArgumentException) {
                }
            }
        }

        if ($module === 'renal' && in_array($recordType, ['renal_history', 'renal_exam', 'renal_session'], true)) {
            $workflow = app(\App\Services\Care\Renal\RenalWorkflowService::class);
            $stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
            $suggested = match ($recordType) {
                'renal_history' => $workflow->stageFromHistory($record->payload ?? []),
                'renal_exam' => $workflow->stageFromExam($record->payload ?? []),
                'renal_session' => $workflow->stageFromDialysis($record->payload ?? []),
                default => null,
            };
            $current = $visit->specialty_stage;
            $early = ['check_in', 'waiting', null, ''];
            $order = [
                'check_in' => 0,
                'history' => 1,
                'exam' => 2,
                'dialysis' => 3,
                'plan' => 4,
                'completed' => 5,
            ];
            if ($suggested && (! $current || in_array($current, $early, true))) {
                try {
                    $stageService->setStage($organization, $visit, 'renal', $suggested, $this->ownerRef($request), $this->ownerRef($request));
                } catch (\InvalidArgumentException) {
                }
            } elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
                try {
                    $stageService->setStage($organization, $visit, 'renal', $suggested, $this->ownerRef($request), $this->ownerRef($request));
                } catch (\InvalidArgumentException) {
                }
            }
        }

        if ($module === 'surgery' && in_array($recordType, ['surg_history', 'surg_exam', 'surg_investigation', 'surg_plan', 'surg_procedure'], true)) {
            $workflow = app(\App\Services\Care\Surgery\SurgeryWorkflowService::class);
            $stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
            $suggested = match ($recordType) {
                'surg_history' => $workflow->stageFromHistory($record->payload ?? []),
                'surg_exam' => $workflow->stageFromExam($record->payload ?? []),
                'surg_investigation' => $workflow->stageFromInvestigation($record->payload ?? []),
                'surg_plan' => $workflow->stageFromPlan($record->payload ?? []),
                'surg_procedure' => $workflow->stageFromProcedure($record->payload ?? []),
                default => null,
            };
            $current = $visit->specialty_stage;
            $early = ['check_in', 'waiting', null, ''];
            $order = [
                'check_in' => 0,
                'history' => 1,
                'exam' => 2,
                'investigation' => 3,
                'plan' => 4,
                'procedure' => 5,
                'postop' => 6,
                'completed' => 7,
            ];
            if ($suggested && (! $current || in_array($current, $early, true))) {
                try {
                    $stageService->setStage($organization, $visit, 'surgery', $suggested, $this->ownerRef($request), $this->ownerRef($request));
                } catch (\InvalidArgumentException) {
                }
            } elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
                try {
                    $stageService->setStage($organization, $visit, 'surgery', $suggested, $this->ownerRef($request), $this->ownerRef($request));
                } catch (\InvalidArgumentException) {
                }
            }
        }

        if ($module === 'vaccination' && in_array($recordType, ['vax_eligibility', 'vax_consent', 'vax_admin'], true)) {
            $workflow = app(\App\Services\Care\Vaccination\VaccinationWorkflowService::class);
            $stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
            $suggested = match ($recordType) {
                'vax_eligibility' => $workflow->stageFromEligibility($record->payload ?? []),
                'vax_consent' => $workflow->stageFromConsent($record->payload ?? []),
                'vax_admin' => $workflow->stageFromAdmin($record->payload ?? []),
                default => null,
            };
            $current = $visit->specialty_stage;
            $early = ['check_in', 'waiting', null, ''];
            $order = [
                'check_in' => 0,
                'eligibility' => 1,
                'consent' => 2,
                'administer' => 3,
                'observation' => 4,
                'completed' => 5,
            ];
            if ($suggested && (! $current || in_array($current, $early, true))) {
                try {
                    $stageService->setStage($organization, $visit, 'vaccination', $suggested, $this->ownerRef($request), $this->ownerRef($request));
                } catch (\InvalidArgumentException) {
                }
            } elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
                try {
                    $stageService->setStage($organization, $visit, 'vaccination', $suggested, $this->ownerRef($request), $this->ownerRef($request));
                } catch (\InvalidArgumentException) {
                }
            }
        }

        if ($module === 'pathology' && in_array($recordType, ['path_request', 'path_specimen', 'path_processing', 'path_report'], true)) {
            $workflow = app(\App\Services\Care\Pathology\PathologyWorkflowService::class);
            $stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
            $suggested = match ($recordType) {
                'path_request' => $workflow->stageFromRequest($record->payload ?? []),
                'path_specimen' => $workflow->stageFromSpecimen($record->payload ?? []),
                'path_processing' => $workflow->stageFromProcessing($record->payload ?? []),
                'path_report' => $workflow->stageFromReport($record->payload ?? []),
                default => null,
            };
            $current = $visit->specialty_stage;
            $early = ['check_in', 'waiting', null, ''];
            $order = [
                'check_in' => 0,
                'request' => 1,
                'specimen' => 2,
                'processing' => 3,
                'report' => 4,
                'verified' => 5,
                'completed' => 6,
            ];
            if ($suggested && (! $current || in_array($current, $early, true))) {
                try {
                    $stageService->setStage($organization, $visit, 'pathology', $suggested, $this->ownerRef($request), $this->ownerRef($request));
                } catch (\InvalidArgumentException) {
                }
            } elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
                try {
                    $stageService->setStage($organization, $visit, 'pathology', $suggested, $this->ownerRef($request), $this->ownerRef($request));
                } catch (\InvalidArgumentException) {
                }
            }
        }

        if ($module === 'infusion' && in_array($recordType, ['infusion_assessment', 'infusion_protocol', 'infusion_session'], true)) {
            $workflow = app(\App\Services\Care\Infusion\InfusionWorkflowService::class);
            $stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
            $suggested = match ($recordType) {
                'infusion_assessment' => $workflow->stageFromAssessment($record->payload ?? []),
                'infusion_protocol' => $workflow->stageFromProtocol($record->payload ?? []),
                'infusion_session' => $workflow->stageFromSession($record->payload ?? []),
                default => null,
            };
            $current = $visit->specialty_stage;
            $early = ['check_in', 'waiting', null, ''];
            $order = [
                'check_in' => 0,
                'assessment' => 1,
                'protocol' => 2,
                'session' => 3,
                'monitoring' => 4,
                'completed' => 5,
            ];
            if ($suggested && (! $current || in_array($current, $early, true))) {
                try {
                    $stageService->setStage($organization, $visit, 'infusion', $suggested, $this->ownerRef($request), $this->ownerRef($request));
                } catch (\InvalidArgumentException) {
                }
            } elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
                try {
                    $stageService->setStage($organization, $visit, 'infusion', $suggested, $this->ownerRef($request), $this->ownerRef($request));
                } catch (\InvalidArgumentException) {
                }
            }
        }

        if ($module === 'dermatology' && in_array($recordType, ['derm_history', 'skin_exam', 'derm_investigation', 'derm_plan'], true)) {
            $workflow = app(\App\Services\Care\Dermatology\DermatologyWorkflowService::class);
            $stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
            $suggested = match ($recordType) {
                'derm_history' => $workflow->stageFromHistory($record->payload ?? []),
                'skin_exam' => $workflow->stageFromExam($record->payload ?? []),
                'derm_investigation' => $workflow->stageFromInvestigation($record->payload ?? []),
                'derm_plan' => $workflow->stageFromPlan($record->payload ?? []),
                default => null,
            };
            $current = $visit->specialty_stage;
            $early = ['check_in', 'waiting', null, ''];
            $order = [
                'check_in' => 0,
                'history' => 1,
                'exam' => 2,
                'investigation' => 3,
                'plan' => 4,
                'procedure' => 5,
                'completed' => 6,
            ];
            if ($suggested && (! $current || in_array($current, $early, true))) {
                try {
                    $stageService->setStage($organization, $visit, 'dermatology', $suggested, $this->ownerRef($request), $this->ownerRef($request));
                } catch (\InvalidArgumentException) {
                }
            } elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
                try {
                    $stageService->setStage($organization, $visit, 'dermatology', $suggested, $this->ownerRef($request), $this->ownerRef($request));
                } catch (\InvalidArgumentException) {
                }
            }
        }

        if ($module === 'podiatry' && in_array($recordType, ['pod_history', 'foot_exam', 'pod_investigation', 'pod_plan'], true)) {
            $workflow = app(\App\Services\Care\Podiatry\PodiatryWorkflowService::class);
            $stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
            $suggested = match ($recordType) {
                'pod_history' => $workflow->stageFromHistory($record->payload ?? []),
                'foot_exam' => $workflow->stageFromExam($record->payload ?? []),
                'pod_investigation' => $workflow->stageFromInvestigation($record->payload ?? []),
                'pod_plan' => $workflow->stageFromPlan($record->payload ?? []),
                default => null,
            };
            $current = $visit->specialty_stage;
            $early = ['check_in', 'waiting', null, ''];
            $order = [
                'check_in' => 0,
                'history' => 1,
                'exam' => 2,
                'investigation' => 3,
                'plan' => 4,
                'procedure' => 5,
                'completed' => 6,
            ];
            if ($suggested && (! $current || in_array($current, $early, true))) {
                try {
                    $stageService->setStage($organization, $visit, 'podiatry', $suggested, $this->ownerRef($request), $this->ownerRef($request));
                } catch (\InvalidArgumentException) {
                }
            } elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
                try {
                    $stageService->setStage($organization, $visit, 'podiatry', $suggested, $this->ownerRef($request), $this->ownerRef($request));
                } catch (\InvalidArgumentException) {
                }
            }
        }

        if ($module === 'fertility' && in_array($recordType, ['fert_history', 'fert_exam', 'fert_investigation', 'fert_plan'], true)) {
            $workflow = app(\App\Services\Care\Fertility\FertilityWorkflowService::class);
            $stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
            $suggested = match ($recordType) {
                'fert_history' => $workflow->stageFromHistory($record->payload ?? []),
                'fert_exam' => $workflow->stageFromExam($record->payload ?? []),
                'fert_investigation' => $workflow->stageFromInvestigation($record->payload ?? []),
                'fert_plan' => $workflow->stageFromPlan($record->payload ?? []),
                default => null,
            };
            $current = $visit->specialty_stage;
            $early = ['check_in', 'waiting', null, ''];
            $order = [
                'check_in' => 0,
                'history' => 1,
                'exam' => 2,
                'investigation' => 3,
                'plan' => 4,
                'cycle' => 5,
                'completed' => 6,
            ];
            if ($suggested && (! $current || in_array($current, $early, true))) {
                try {
                    $stageService->setStage($organization, $visit, 'fertility', $suggested, $this->ownerRef($request), $this->ownerRef($request));
                } catch (\InvalidArgumentException) {
                }
            } elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
                try {
                    $stageService->setStage($organization, $visit, 'fertility', $suggested, $this->ownerRef($request), $this->ownerRef($request));
                } catch (\InvalidArgumentException) {
                }
            }
        }

        if ($module === 'child_welfare' && in_array($recordType, ['cwc_intake', 'cwc_assessment', 'cwc_plan'], true)) {
            $workflow = app(\App\Services\Care\ChildWelfare\ChildWelfareWorkflowService::class);
            $stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
            $suggested = match ($recordType) {
                'cwc_intake' => $workflow->stageFromIntake($record->payload ?? []),
                'cwc_assessment' => $workflow->stageFromAssessment($record->payload ?? []),
                'cwc_plan' => $workflow->stageFromPlan($record->payload ?? []),
                default => null,
            };
            $current = $visit->specialty_stage;
            $early = ['check_in', 'waiting', null, ''];
            $order = [
                'check_in' => 0,
                'intake' => 1,
                'assessment' => 2,
                'plan' => 3,
                'followup' => 4,
                'completed' => 5,
            ];
            if ($suggested && (! $current || in_array($current, $early, true))) {
                try {
                    $stageService->setStage($organization, $visit, 'child_welfare', $suggested, $this->ownerRef($request), $this->ownerRef($request));
                } catch (\InvalidArgumentException) {
                }
            } elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
                try {
                    $stageService->setStage($organization, $visit, 'child_welfare', $suggested, $this->ownerRef($request), $this->ownerRef($request));
                } catch (\InvalidArgumentException) {
                }
            }
        }

        if ($module === 'ambulance' && in_array($recordType, ['amb_dispatch', 'amb_scene', 'amb_en_route'], true)) {
            $workflow = app(\App\Services\Care\Ambulance\AmbulanceWorkflowService::class);
            $stageService = app(\App\Services\Care\SpecialtyVisitStageService::class);
            $suggested = match ($recordType) {
                'amb_dispatch' => $workflow->stageFromDispatch($record->payload ?? []),
                'amb_scene' => $workflow->stageFromScene($record->payload ?? []),
                'amb_en_route' => $workflow->stageFromEnRoute($record->payload ?? []),
                default => null,
            };
            $current = $visit->specialty_stage;
            $early = ['check_in', 'waiting', null, ''];
            $order = [
                'check_in' => 0,
                'dispatch' => 1,
                'on_scene' => 2,
                'transport' => 3,
                'handover' => 4,
                'completed' => 5,
            ];
            if ($suggested && (! $current || in_array($current, $early, true))) {
                try {
                    $stageService->setStage($organization, $visit, 'ambulance', $suggested, $this->ownerRef($request), $this->ownerRef($request));
                } catch (\InvalidArgumentException) {
                }
            } elseif ($suggested && $suggested !== $current && ($order[$suggested] ?? 0) > ($order[$current] ?? 0)) {
                try {
                    $stageService->setStage($organization, $visit, 'ambulance', $suggested, $this->ownerRef($request), $this->ownerRef($request));
                } catch (\InvalidArgumentException) {
                }
            }
        }

        return redirect()
            ->route('care.specialty.workspace', [
                'module' => $module,
                'visit' => $visit,
                'tab' => $tab,
            ])
            ->with('success', 'Saved '.$record->record_type.' record.');
    }

    public function uploadDocument(
        Request $request,
        string $module,
        Visit $visit,
        SpecialtyModuleService $modules,
    ): RedirectResponse {
        $definition = $modules->definition($module);
        abort_unless($definition, 404);

        $organization = $this->organization($request);
        $member = $this->member($request);
        // Viewing docs is workspace GET (memberCanAccess / memberCanView). Upload needs manage.
        abort_unless($modules->memberCanAccess($organization, $member, $module), 403);
        abort_unless($modules->memberCanManage($organization, $member, $module), 403);
        abort_unless($visit->organization_id === $organization->id, 404);
        abort_unless($visit->patient_id, 422);

        $validated = $request->validate([
            'attachment' => ['required', 'file', 'max:10240', 'mimes:pdf,jpeg,jpg,png,webp'],
        ]);

        $file = $validated['attachment'];
        $path = $file->store("care/patients/{$visit->patient_id}/attachments", 'public');

        PatientAttachment::create([
            'owner_ref' => $this->ownerRef($request),
            'patient_id' => $visit->patient_id,
            'file_path' => $path,
            'original_name' => $file->getClientOriginalName(),
            'mime_type' => $file->getMimeType(),
            'document_type' => 'specialty_'.$module,
            'uploaded_by' => $this->ownerRef($request),
        ]);

        return redirect()
            ->route('care.specialty.workspace', [
                'module' => $module,
                'visit' => $visit,
                'tab' => 'documents',
            ])
            ->with('success', 'Document uploaded.');
    }

    public function callNext(
        Request $request,
        string $module,
        SpecialtyModuleService $modules,
        CareQueueBridge $queueBridge,
        CareQueueSessionAdvance $advance,
    ): RedirectResponse {
        $definition = $modules->definition($module);
        abort_unless($definition, 404);

        $organization = $this->organization($request);
        $member = $this->member($request);
        $owner = $this->ownerRef($request);
        abort_unless($modules->memberCanAccess($organization, $member, $module), 403);
        abort_unless($modules->memberCanManage($organization, $member, $module), 403);
        abort_unless($queueBridge->isEnabled($organization), 404);

        $resolver = app(OrganizationResolver::class);
        $branchScope = $resolver->branchScope($member);
        $practitionerScope = $resolver->practitionerScope($organization, $member);
        $branchId = (int) ($request->input('branch_id') ?: $branchScope);
        $practitionerId = null;

        if ($practitionerScope !== null) {
            abort_unless($practitionerScope !== [], 422);
            $practitionerId = $practitionerScope[0];
            $pracBranch = (int) \App\Models\Practitioner::owned($owner)
                ->whereKey($practitionerId)
                ->value('branch_id');
            if ($pracBranch > 0) {
                $branchId = $pracBranch;
            }
        }

        abort_unless($branchId > 0, 422);

        if ($request->filled('appointment_id')) {
            $current = Appointment::owned($owner)
                ->where('organization_id', $organization->id)
                ->findOrFail((int) $request->input('appointment_id'));
            $advance->endCurrentEncounter($current, $owner, $owner);
        }

        $result = $queueBridge->callNext($organization, $module, $branchId, $member, $practitionerId);
        $ticket = $result['ticket'] ?? null;
        if (! $ticket) {
            $departmentIds = Department::owned($owner)
                ->where('type', $definition['department_type'] ?? 'general')
                ->where('is_active', true)
                ->when($branchScope, fn ($q) => $q->where('branch_id', $branchScope))
                ->pluck('id');

            $waitingAtBranch = Appointment::owned($owner)
                ->where('organization_id', $organization->id)
                ->where('branch_id', $branchId)
                ->whereIn('status', [Appointment::STATUS_WAITING, Appointment::STATUS_CHECKED_IN])
                ->when($departmentIds->isNotEmpty(), fn ($q) => $q->whereIn('department_id', $departmentIds))
                ->when($departmentIds->isEmpty(), fn ($q) => $q->whereRaw('1 = 0'))
                ->count();

            $waitingOrg = Appointment::owned($owner)
                ->where('organization_id', $organization->id)
                ->whereIn('status', [Appointment::STATUS_WAITING, Appointment::STATUS_CHECKED_IN])
                ->when($departmentIds->isNotEmpty(), fn ($q) => $q->whereIn('department_id', $departmentIds))
                ->when($departmentIds->isEmpty(), fn ($q) => $q->whereRaw('1 = 0'))
                ->count();

            $branchName = \App\Models\Branch::owned($owner)->whereKey($branchId)->value('name') ?: 'this branch';

            if ($waitingAtBranch > 0) {
                return back()->with(
                    'info',
                    "{$waitingAtBranch} patient(s) are waiting at {$branchName}, but none have a callable ticket at a service desk yet. Use Start on the queue, or check in again so a ticket is issued."
                );
            }

            if ($waitingOrg > $waitingAtBranch) {
                return back()->with(
                    'info',
                    "No patients waiting at {$branchName}. {$waitingOrg} are waiting at other branches — switch branch or open History."
                );
            }

            return back()->with('info', 'No patients waiting in this queue.');
        }

        $entity = $result['entity'] ?? null;
        if ($entity instanceof Appointment) {
            return $advance->redirectToOpenedPatient(
                $entity,
                $ticket,
                'care.queue.index',
            );
        }

        $name = $ticket['customer_name'] ?? 'patient';

        return back()->with('success', 'Called '.$ticket['ticket_number'].' — '.$name.'.');
    }

    /**
     * Refer a patient into this specialty queue (walk-in) without full clinical edit access.
     */
    public function refer(
        Request $request,
        string $module,
        SpecialtyModuleService $modules,
        AppointmentService $appointments,
    ): RedirectResponse {
        $definition = $modules->definition($module);
        abort_unless($definition, 404);

        $organization = $this->organization($request);
        $member = $this->member($request);
        abort_unless($modules->memberCanRefer($organization, $member, $module), 403);

        $owner = $this->ownerRef($request);
        $branchScope = app(OrganizationResolver::class)->branchScope($member);

        $validated = $request->validate([
            'patient_id' => ['required', 'integer', 'exists:care_patients,id'],
            'branch_id' => ['nullable', 'integer', 'exists:care_branches,id'],
            'reason' => ['nullable', 'string', 'max:500'],
            'notes' => ['nullable', 'string', 'max:2000'],
        ]);

        $branchId = (int) ($validated['branch_id'] ?? $branchScope ?? 0);
        abort_unless($branchId > 0, 422);
        $this->authorizeBranch($request, $branchId);

        $department = Department::owned($owner)
            ->where('type', $definition['department_type'] ?? 'general')
            ->where('branch_id', $branchId)
            ->where('is_active', true)
            ->orderBy('id')
            ->first();

        if (! $department) {
            return back()->with('error', 'No active '.($definition['label'] ?? $module).' department at this branch.');
        }

        $patient = \App\Models\Patient::owned($owner)
            ->where('organization_id', $organization->id)
            ->findOrFail((int) $validated['patient_id']);

        $appointment = $appointments->walkIn($organization, $owner, [
            'patient_id' => $patient->id,
            'branch_id' => $branchId,
            'department_id' => $department->id,
            'reason' => $validated['reason'] ?? ('Referral to '.($definition['label'] ?? $module)),
            'notes' => $validated['notes'] ?? null,
        ], $owner);

        \App\Services\Care\AuditLogger::record(
            $owner,
            'specialty.referral',
            $organization->id,
            $owner,
            Appointment::class,
            $appointment->id,
            ['module' => $module, 'department_id' => $department->id],
        );

        return redirect()
            ->route('care.specialty.show', $module)
            ->with('success', 'Referred '.$patient->fullName().' to '.($definition['label'] ?? $module).'.');
    }

    protected function renderShell(
        Request $request,
        string $module,
        string $section,
        SpecialtyModuleService $modules,
        SpecialtyShellService $shell,
        CareQueueBridge $queueBridge,
        ?Visit $visit = null,
    ): View {
        $module = $modules->normalizeKey($module);
        $definition = $modules->definition($module);
        abort_unless($definition, 404);

        $organization = $this->organization($request);
        $member = $this->member($request);
        abort_unless($modules->memberCanAccess($organization, $member, $module), 403);

        $canManageSpecialty = $modules->memberCanManage($organization, $member, $module);
        $canViewSpecialty = $modules->memberCanView($organization, $member, $module);
        $canReferSpecialty = $modules->memberCanRefer($organization, $member, $module);
        $specialtyAccessLevel = $modules->memberAccessLevel($organization, $member, $module);

        $owner = $this->ownerRef($request);
        $resolver = app(OrganizationResolver::class);
        $branchScope = $resolver->branchScope($member);
        $practitionerScope = $resolver->practitionerScope($organization, $member);

        $departments = Department::owned($owner)
            ->where('type', $definition['department_type'] ?? 'general')
            ->where('is_active', true)
            ->when($branchScope, fn ($q) => $q->where('branch_id', $branchScope))
            ->with('branch')
            ->orderBy('name')
            ->get();

        $departmentIds = $departments->pluck('id')->all();

        $branchId = (int) ($branchScope ?: $departments->first()?->branch_id);
        if ($practitionerScope !== null && $practitionerScope !== []) {
            $pracBranch = (int) \App\Models\Practitioner::owned($owner)
                ->whereKey($practitionerScope[0])
                ->value('branch_id');
            if ($pracBranch > 0) {
                $branchId = $pracBranch;
            }
        }

        // Match Call next: when the member has no branch scope (e.g. hospital admin),
        // KPIs / waiting lists use the same branch as queue ops so WAITING isn't org-wide
        // while Call next is local.
        $kpiBranch = $branchScope ?? ($branchId > 0 ? $branchId : null);

        $waiting = Appointment::owned($owner)
            ->where('organization_id', $organization->id)
            ->whereIn('status', [Appointment::STATUS_WAITING, Appointment::STATUS_CHECKED_IN])
            ->when($departmentIds !== [], fn ($q) => $q->whereIn('department_id', $departmentIds))
            ->when($departmentIds === [], fn ($q) => $q->whereRaw('1 = 0'))
            ->when($kpiBranch, fn ($q) => $q->where('branch_id', $kpiBranch))
            ->when(
                $practitionerScope !== null,
                fn ($q) => $q->whereIn('practitioner_id', $practitionerScope ?: [0]),
            )
            ->with(['patient', 'practitioner', 'department', 'visit.currentStageAdvance.stage'])
            ->orderBy('queue_position')
            ->orderBy('checked_in_at')
            ->limit(50)
            ->get();

        $inConsultation = Appointment::owned($owner)
            ->where('organization_id', $organization->id)
            ->where('status', Appointment::STATUS_IN_CONSULTATION)
            ->when($departmentIds !== [], fn ($q) => $q->whereIn('department_id', $departmentIds))
            ->when($departmentIds === [], fn ($q) => $q->whereRaw('1 = 0'))
            ->when($kpiBranch, fn ($q) => $q->where('branch_id', $kpiBranch))
            ->when(
                $practitionerScope !== null,
                fn ($q) => $q->whereIn('practitioner_id', $practitionerScope ?: [0]),
            )
            ->with(['patient', 'practitioner', 'consultation', 'visit'])
            ->orderBy('started_at')
            ->limit(50)
            ->get();

        $shellDefinition = $shell->definition($module);
        $kpis = $shell->kpis($organization, $module, $owner, $kpiBranch, $practitionerScope);
        $openVisits = $shell->openVisits($organization, $module, $owner, $kpiBranch, $practitionerScope);
        $visitHistory = $section === 'history'
            ? $shell->visitHistory($organization, $module, $owner, $kpiBranch, $practitionerScope)
            : collect();
        $services = $shell->provisionedServices($organization, $module);

        $permissions = app(\App\Services\Care\CarePermissions::class);
        // Ability-based for every role (doctor, nurse, receptionist, lab, pharmacist, …).
        // Module canManage alone is not enough — flags must match what mutate routes authorize.
        $canConsult = $permissions->can($member, 'consultations.manage') && $canManageSpecialty;
        $canAdvanceStage = $canConsult
            || ($module === 'blood_bank'
                && $canManageSpecialty
                && $permissions->can($member, 'blood_bank.manage'))
            || ($module === 'ambulance'
                && $canManageSpecialty
                && $permissions->can($member, 'ambulance.manage'));
        $canStartConsultation = $canConsult;
        // Same ability as GP consultation chart — not consultations.manage alone.
        $canPrescribe = $permissions->can($member, 'prescriptions.manage') && $canManageSpecialty;
        // Ambulance is dispatch-out EMS — not a desk Call next line.
        $canCallNext = $module !== 'ambulance' && $canManageSpecialty;
        $canManageClinical = $canManageSpecialty;
        $canManageVitals = $canManageSpecialty && (
            $permissions->can($member, 'vitals.manage')
            || $permissions->can($member, 'consultations.manage')
        );
        $canManageQueue = ($permissions->can($member, 'appointments.manage') && $canManageSpecialty)
            || ($module === 'ambulance' && $canManageSpecialty);
        $canAccessPatientQueue = $permissions->canAccessPatientQueue($member);
        $canBookAppointments = $permissions->can($member, 'appointments.manage');
        $canViewPatients = $permissions->can($member, 'patients.view');
        $canViewAppointments = $permissions->can($member, 'appointments.view');
        $branchLabel = $branchId
            ? (string) (\App\Models\Branch::owned($owner)->whereKey($branchId)->value('name') ?? '')
            : '';

        $ambulanceDispatchBoard = null;
        if ($module === 'ambulance' && in_array($section, ['visits', 'overview'], true)) {
            $ambulanceDispatchBoard = app(AmbulanceDispatchBoardService::class)->board(
                $organization,
                $owner,
                $kpiBranch,
                $practitionerScope,
            );
        }

        $done = Appointment::owned($owner)
            ->where('organization_id', $organization->id)
            ->where('status', Appointment::STATUS_COMPLETED)
            ->whereDate('completed_at', today())
            ->when($departmentIds !== [], fn ($q) => $q->whereIn('department_id', $departmentIds))
            ->when($departmentIds === [], fn ($q) => $q->whereRaw('1 = 0'))
            ->when($kpiBranch, fn ($q) => $q->where('branch_id', $kpiBranch))
            ->when(
                $practitionerScope !== null,
                fn ($q) => $q->whereIn('practitioner_id', $practitionerScope ?: [0]),
            )
            ->with(['patient', 'practitioner'])
            ->orderByDesc('completed_at')
            ->limit(20)
            ->get();

        $workspaceVisit = null;
        $patientHeader = null;
        $timeline = [];
        $clinicalRecord = null;
        $clinicalFields = [];
        $clinicalAlerts = [];
        $visitDocuments = collect();
        $investigationTypes = collect();
        $dentalChart = null;
        $dentalTeethMap = [];
        $dentalPlan = null;
        $dentalPlanHistory = collect();
        $dentalProcedures = collect();
        $dentalImages = collect();
        $dentalVisitNote = null;
        $dentalCatalog = [];
        $dentalRows = [];
        $dentalConditions = [];
        $dentalStatuses = [];
        $dentalSurfaces = [];
        $dentalModalities = [];
        $dentalDentitions = [];
        $dentalPerioExam = null;
        $dentalPerioSurfaces = [];
        $dentalLabCases = collect();
        $dentalLabCaseTypes = [];
        $dentalLabCaseStatuses = [];
        $dentalRecalls = collect();
        $dentalStageCodes = [];
        $emergencyTriage = null;
        $emergencyClinicalNote = null;
        $emergencyObservation = null;
        $emergencyDisposition = null;
        $emergencyVitals = collect();
        $emergencyLatestVitals = null;
        $emergencyStageCodes = [];
        $emergencyStageFlow = [];
        $bloodBankRequest = null;
        $bloodBankInventory = null;
        $bloodBankIssue = null;
        $bloodBankTransfusion = null;
        $bloodBankStageCodes = [];
        $bloodBankStageFlow = [];
        $ophthalmologyRefraction = null;
        $ophthalmologyExam = null;
        $ophthalmologyInvestigation = null;
        $ophthalmologyPlan = null;
        $ophthalmologyProcedure = null;
        $ophthalmologyStageCodes = [];
        $ophthalmologyStageFlow = [];
        $physiotherapyAssessment = null;
        $physiotherapyPlan = null;
        $physiotherapySession = null;
        $physiotherapyHomeProgram = null;
        $physiotherapyStageCodes = [];
        $physiotherapyStageFlow = [];
        $maternityHistory = null;
        $maternityExam = null;
        $maternityFetal = null;
        $maternityInvestigation = null;
        $maternityPlan = null;
        $maternityPostnatal = null;
        $maternityStageCodes = [];
        $maternityStageFlow = [];
        $radiologyRequest = null;
        $radiologyAcquisition = null;
        $radiologyReport = null;
        $radiologyVerification = null;
        $radiologyStageCodes = [];
        $radiologyStageFlow = [];
        $cardiologyHistory = null;
        $cardiologyExam = null;
        $cardiologyInvestigation = null;
        $cardiologyPlan = null;
        $cardiologyProcedure = null;
        $cardiologyStageCodes = [];
        $cardiologyStageFlow = [];
        $psychiatryHistory = null;
        $psychiatryRisk = null;
        $psychiatryPlan = null;
        $psychiatryFollowup = null;
        $psychiatryStageCodes = [];
        $psychiatryStageFlow = [];
        $pediatricsHistory = null;
        $pediatricsExam = null;
        $pediatricsInvestigation = null;
        $pediatricsPlan = null;
        $pediatricsTreatment = null;
        $pediatricsStageCodes = [];
        $pediatricsStageFlow = [];
        $orthopedicsHistory = null;
        $orthopedicsExam = null;
        $orthopedicsImaging = null;
        $orthopedicsPlan = null;
        $orthopedicsProcedure = null;
        $orthopedicsStageCodes = [];
        $orthopedicsStageFlow = [];
        $entHistory = null;
        $entExam = null;
        $entInvestigation = null;
        $entPlan = null;
        $entProcedure = null;
        $entStageCodes = [];
        $entStageFlow = [];
        $oncologyHistory = null;
        $oncologyStaging = null;
        $oncologyInvestigation = null;
        $oncologyPlan = null;
        $oncologyTreatment = null;
        $oncologyStageCodes = [];
        $oncologyStageFlow = [];
        $renalHistory = null;
        $renalExam = null;
        $renalDialysis = null;
        $renalPlan = null;
        $renalStageCodes = [];
        $renalStageFlow = [];
        $surgeryHistory = null;
        $surgeryExam = null;
        $surgeryInvestigation = null;
        $surgeryPlan = null;
        $surgeryProcedure = null;
        $surgeryPostop = null;
        $surgeryStageCodes = [];
        $surgeryStageFlow = [];
        $vaccinationEligibility = null;
        $vaccinationConsent = null;
        $vaccinationAdmin = null;
        $vaccinationObservation = null;
        $vaccinationStageCodes = [];
        $vaccinationStageFlow = [];
        $pathologyRequest = null;
        $pathologySpecimen = null;
        $pathologyProcessing = null;
        $pathologyReport = null;
        $pathologyVerification = null;
        $pathologyStageCodes = [];
        $pathologyStageFlow = [];
        $infusionAssessment = null;
        $infusionProtocol = null;
        $infusionSession = null;
        $infusionMonitoring = null;
        $infusionStageCodes = [];
        $infusionStageFlow = [];
        $dermatologyHistory = null;
        $dermatologyExam = null;
        $dermatologyInvestigation = null;
        $dermatologyPlan = null;
        $dermatologyProcedure = null;
        $dermatologyStageCodes = [];
        $dermatologyStageFlow = [];
        $podiatryHistory = null;
        $podiatryExam = null;
        $podiatryInvestigation = null;
        $podiatryPlan = null;
        $podiatryProcedure = null;
        $podiatryStageCodes = [];
        $podiatryStageFlow = [];
        $fertilityHistory = null;
        $fertilityExam = null;
        $fertilityInvestigation = null;
        $fertilityPlan = null;
        $fertilityCycle = null;
        $fertilityStageCodes = [];
        $fertilityStageFlow = [];
        $childWelfareIntake = null;
        $childWelfareAssessment = null;
        $childWelfarePlan = null;
        $childWelfareFollowup = null;
        $childWelfareStageCodes = [];
        $childWelfareStageFlow = [];
        $ambulanceDispatch = null;
        $ambulanceScene = null;
        $ambulanceEnRoute = null;
        $ambulanceHandover = null;
        $ambulanceStageCodes = [];
        $ambulanceStageFlow = [];
        $activeTab = (string) $request->query('tab', array_key_first($shell->workspaceTabs($module)) ?: 'overview');
        $clinical = app(SpecialtyClinicalRecordService::class);

        if ($visit) {
            abort_unless($visit->organization_id === $organization->id, 404);
            $visit->load([
                'patient.allergies',
                'patient.emergencyContacts',
                'patient.attachments',
                'appointment.practitioner',
                'appointment.consultation.investigationRequests.investigationType',
                'bill.lineItems',
                'consultations.investigationRequests.investigationType',
            ]);
            $workspaceVisit = $visit;
            if ($visit->patient) {
                $patientHeader = array_merge(
                    ['patient' => $visit->patient, 'visit' => $visit, 'appointment' => $visit->appointment],
                    $shell->patientHeaderMeta($visit->patient),
                );
                $timeline = $shell->patientTimeline($visit->patient);
            }
        }

        if ($workspaceVisit && $section === 'workspace') {
            $recordType = $clinical->recordTypeForTab($module, $activeTab);
            if ($recordType) {
                $clinicalRecord = $clinical->findForVisit($workspaceVisit, $module, $recordType);
                $clinicalFields = $clinical->fieldsFor($module, $recordType);
            }
            $clinicalAlerts = $clinical->alertsForVisit($workspaceVisit, $module);

            if ($module === 'dentistry' && $workspaceVisit->patient) {
                $chartService = app(\App\Services\Care\Dentistry\DentalChartService::class);
                $planService = app(\App\Services\Care\Dentistry\DentalTreatmentPlanService::class);
                $analytics = app(\App\Services\Care\Dentistry\DentalAnalyticsService::class);
                $perioService = app(\App\Services\Care\Dentistry\DentalPerioService::class);
                $labService = app(\App\Services\Care\Dentistry\DentalLabCaseService::class);
                $recallService = app(\App\Services\Care\Dentistry\DentalRecallService::class);

                $dentalChart = $chartService->chartForPatient($organization, $workspaceVisit->patient, $owner);
                $dentalTeethMap = $chartService->teethMap($dentalChart);
                $dentalPlan = $planService->activePlanForPatient($organization, $workspaceVisit->patient, $owner);
                $dentalPlanHistory = $planService->plansForPatient($organization, $workspaceVisit->patient, $owner);
                $dentalProcedures = \App\Models\DentalProcedure::owned($owner)
                    ->where('visit_id', $workspaceVisit->id)
                    ->orderByDesc('id')
                    ->get();
                $dentalImages = \App\Models\DentalImage::owned($owner)
                    ->where(function ($q) use ($workspaceVisit) {
                        $q->where('visit_id', $workspaceVisit->id)
                            ->orWhere(function ($q2) use ($workspaceVisit) {
                                $q2->where('patient_id', $workspaceVisit->patient_id)
                                    ->whereNull('visit_id');
                            });
                    })
                    ->with('attachment')
                    ->orderByDesc('id')
                    ->limit(40)
                    ->get();
                $dentalVisitNote = \App\Models\DentalVisitNote::owned($owner)
                    ->where('visit_id', $workspaceVisit->id)
                    ->first();
                $dentalCatalog = $shell->provisionedServices($organization, 'dentistry');
                $dentition = $dentalChart->dentition ?: \App\Services\Care\Dentistry\DentalCatalog::DENTITION_ADULT;
                $dentalRows = \App\Services\Care\Dentistry\DentalCatalog::odontogramRows($dentition);
                $dentalConditions = \App\Services\Care\Dentistry\DentalCatalog::conditions();
                $dentalStatuses = \App\Services\Care\Dentistry\DentalCatalog::toothStatuses();
                $dentalSurfaces = \App\Services\Care\Dentistry\DentalCatalog::surfaces();
                $dentalModalities = \App\Services\Care\Dentistry\DentalCatalog::modalities();
                $dentalDentitions = \App\Services\Care\Dentistry\DentalCatalog::dentitions();
                $dentalPerioExam = $perioService->latestForPatient($organization, $workspaceVisit->patient, $owner);
                $dentalPerioSurfaces = \App\Services\Care\Dentistry\DentalCatalog::perioSurfaces();
                $dentalLabCases = $labService->casesForPatient($organization, $workspaceVisit->patient, $owner);
                $dentalLabCaseTypes = \App\Services\Care\Dentistry\DentalCatalog::labCaseTypes();
                $dentalLabCaseStatuses = \App\Services\Care\Dentistry\DentalCatalog::labCaseStatuses();
                $dentalRecalls = $recallService->recallsForPatient($organization, $workspaceVisit->patient, $owner);
                $dentalStageCodes = collect($shell->stages('dentistry'))->pluck('code')->all();

                $clinicalAlerts = array_merge(
                    $clinicalAlerts,
                    $analytics->alertsForPatient($organization, $workspaceVisit->patient, $owner),
                );
            }

            if ($module === 'emergency') {
                $emergencyTriage = $clinical->findForVisit($workspaceVisit, 'emergency', 'triage');
                $emergencyClinicalNote = $clinical->findForVisit($workspaceVisit, 'emergency', 'clinical_note');
                $emergencyObservation = $clinical->findForVisit($workspaceVisit, 'emergency', 'observation');
                $emergencyDisposition = $clinical->findForVisit($workspaceVisit, 'emergency', 'disposition');
                $vitalsService = app(\App\Services\Care\Emergency\EmergencyVitalsService::class);
                $emergencyVitals = $vitalsService->forVisit($workspaceVisit);
                $emergencyLatestVitals = $vitalsService->latestForVisit($workspaceVisit);
                $emergencyStageCodes = collect($shell->stages('emergency'))->pluck('code')->all();
                $emergencyStageFlow = app(\App\Services\Care\Emergency\EmergencyWorkflowService::class)->stageFlow();
            }

            if ($module === 'blood_bank') {
                $bloodBankRequest = $clinical->findForVisit($workspaceVisit, 'blood_bank', 'blood_request');
                $bloodBankInventory = $clinical->findForVisit($workspaceVisit, 'blood_bank', 'inventory_note');
                $bloodBankIssue = $clinical->findForVisit($workspaceVisit, 'blood_bank', 'issue_note');
                $bloodBankTransfusion = $clinical->findForVisit($workspaceVisit, 'blood_bank', 'transfusion_note');
                $bloodBankStageCodes = collect($shell->stages('blood_bank'))->pluck('code')->all();
                $bloodBankStageFlow = app(\App\Services\Care\BloodBank\BloodBankWorkflowService::class)->stageFlow();
            }

            if ($module === 'ophthalmology') {
                $ophthalmologyRefraction = $clinical->findForVisit($workspaceVisit, 'ophthalmology', 'refraction');
                $ophthalmologyExam = $clinical->findForVisit($workspaceVisit, 'ophthalmology', 'eye_exam');
                $ophthalmologyInvestigation = $clinical->findForVisit($workspaceVisit, 'ophthalmology', 'eye_investigation');
                $ophthalmologyPlan = $clinical->findForVisit($workspaceVisit, 'ophthalmology', 'eye_plan');
                $ophthalmologyProcedure = $clinical->findForVisit($workspaceVisit, 'ophthalmology', 'eye_procedure');
                $ophthalmologyStageCodes = collect($shell->stages('ophthalmology'))->pluck('code')->all();
                $ophthalmologyStageFlow = app(\App\Services\Care\Ophthalmology\OphthalmologyWorkflowService::class)->stageFlow();
            }

            if ($module === 'physiotherapy') {
                $physiotherapyAssessment = $clinical->findForVisit($workspaceVisit, 'physiotherapy', 'pt_assessment');
                $physiotherapyPlan = $clinical->findForVisit($workspaceVisit, 'physiotherapy', 'pt_plan');
                $physiotherapySession = $clinical->findForVisit($workspaceVisit, 'physiotherapy', 'pt_session');
                $physiotherapyHomeProgram = $clinical->findForVisit($workspaceVisit, 'physiotherapy', 'pt_home_program');
                $physiotherapyStageCodes = collect($shell->stages('physiotherapy'))->pluck('code')->all();
                $physiotherapyStageFlow = app(\App\Services\Care\Physiotherapy\PhysiotherapyWorkflowService::class)->stageFlow();
            }

            if ($module === 'womens_health') {
                $maternityHistory = $clinical->findForVisit($workspaceVisit, 'womens_health', 'anc_history');
                $maternityExam = $clinical->findForVisit($workspaceVisit, 'womens_health', 'obstetric_exam');
                $maternityFetal = $clinical->findForVisit($workspaceVisit, 'womens_health', 'fetal_notes');
                $maternityInvestigation = $clinical->findForVisit($workspaceVisit, 'womens_health', 'mat_investigation');
                $maternityPlan = $clinical->findForVisit($workspaceVisit, 'womens_health', 'mat_plan');
                $maternityPostnatal = $clinical->findForVisit($workspaceVisit, 'womens_health', 'postnatal_note');
                $maternityStageCodes = collect($shell->stages('womens_health'))->pluck('code')->all();
                $maternityStageFlow = app(\App\Services\Care\WomensHealth\WomensHealthWorkflowService::class)->stageFlow();
            }

            if ($module === 'radiology') {
                $radiologyRequest = $clinical->findForVisit($workspaceVisit, 'radiology', 'imaging_request');
                $radiologyAcquisition = $clinical->findForVisit($workspaceVisit, 'radiology', 'imaging_acquisition');
                $radiologyReport = $clinical->findForVisit($workspaceVisit, 'radiology', 'imaging_report');
                $radiologyVerification = $clinical->findForVisit($workspaceVisit, 'radiology', 'imaging_verification');
                $radiologyStageCodes = collect($shell->stages('radiology'))->pluck('code')->all();
                $radiologyStageFlow = app(\App\Services\Care\Radiology\RadiologyWorkflowService::class)->stageFlow();
            }

            if ($module === 'cardiology') {
                $cardiologyHistory = $clinical->findForVisit($workspaceVisit, 'cardiology', 'cardio_history');
                $cardiologyExam = $clinical->findForVisit($workspaceVisit, 'cardiology', 'cardiac_exam');
                $cardiologyInvestigation = $clinical->findForVisit($workspaceVisit, 'cardiology', 'cardio_investigation');
                $cardiologyPlan = $clinical->findForVisit($workspaceVisit, 'cardiology', 'cardio_plan');
                $cardiologyProcedure = $clinical->findForVisit($workspaceVisit, 'cardiology', 'cardio_procedure');
                $cardiologyStageCodes = collect($shell->stages('cardiology'))->pluck('code')->all();
                $cardiologyStageFlow = app(\App\Services\Care\Cardiology\CardiologyWorkflowService::class)->stageFlow();
            }

            if ($module === 'psychiatry') {
                $psychiatryHistory = $clinical->findForVisit($workspaceVisit, 'psychiatry', 'mental_status');
                $psychiatryRisk = $clinical->findForVisit($workspaceVisit, 'psychiatry', 'risk_assessment');
                $psychiatryPlan = $clinical->findForVisit($workspaceVisit, 'psychiatry', 'psych_plan');
                $psychiatryFollowup = $clinical->findForVisit($workspaceVisit, 'psychiatry', 'psych_followup');
                $psychiatryStageCodes = collect($shell->stages('psychiatry'))->pluck('code')->all();
                $psychiatryStageFlow = app(\App\Services\Care\Psychiatry\PsychiatryWorkflowService::class)->stageFlow();
            }

            if ($module === 'pediatrics') {
                $pediatricsHistory = $clinical->findForVisit($workspaceVisit, 'pediatrics', 'ped_history');
                $pediatricsExam = $clinical->findForVisit($workspaceVisit, 'pediatrics', 'pediatric_exam');
                $pediatricsInvestigation = $clinical->findForVisit($workspaceVisit, 'pediatrics', 'ped_investigation');
                $pediatricsPlan = $clinical->findForVisit($workspaceVisit, 'pediatrics', 'ped_plan');
                $pediatricsTreatment = $clinical->findForVisit($workspaceVisit, 'pediatrics', 'ped_treatment');
                $pediatricsStageCodes = collect($shell->stages('pediatrics'))->pluck('code')->all();
                $pediatricsStageFlow = app(\App\Services\Care\Pediatrics\PediatricsWorkflowService::class)->stageFlow();
            }

            if ($module === 'orthopedics') {
                $orthopedicsHistory = $clinical->findForVisit($workspaceVisit, 'orthopedics', 'ortho_history');
                $orthopedicsExam = $clinical->findForVisit($workspaceVisit, 'orthopedics', 'ortho_exam');
                $orthopedicsImaging = $clinical->findForVisit($workspaceVisit, 'orthopedics', 'ortho_imaging');
                $orthopedicsPlan = $clinical->findForVisit($workspaceVisit, 'orthopedics', 'ortho_plan');
                $orthopedicsProcedure = $clinical->findForVisit($workspaceVisit, 'orthopedics', 'ortho_procedure');
                $orthopedicsStageCodes = collect($shell->stages('orthopedics'))->pluck('code')->all();
                $orthopedicsStageFlow = app(\App\Services\Care\Orthopedics\OrthopedicsWorkflowService::class)->stageFlow();
            }

            if ($module === 'ent') {
                $entHistory = $clinical->findForVisit($workspaceVisit, 'ent', 'ent_history');
                $entExam = $clinical->findForVisit($workspaceVisit, 'ent', 'ent_exam');
                $entInvestigation = $clinical->findForVisit($workspaceVisit, 'ent', 'ent_investigation');
                $entPlan = $clinical->findForVisit($workspaceVisit, 'ent', 'ent_plan');
                $entProcedure = $clinical->findForVisit($workspaceVisit, 'ent', 'ent_procedure');
                $entStageCodes = collect($shell->stages('ent'))->pluck('code')->all();
                $entStageFlow = app(\App\Services\Care\Ent\EntWorkflowService::class)->stageFlow();
            }

            if ($module === 'oncology') {
                $oncologyHistory = $clinical->findForVisit($workspaceVisit, 'oncology', 'onc_history');
                $oncologyStaging = $clinical->findForVisit($workspaceVisit, 'oncology', 'onc_staging');
                $oncologyInvestigation = $clinical->findForVisit($workspaceVisit, 'oncology', 'onc_investigation');
                $oncologyPlan = $clinical->findForVisit($workspaceVisit, 'oncology', 'onc_plan');
                $oncologyTreatment = $clinical->findForVisit($workspaceVisit, 'oncology', 'onc_treatment');
                $oncologyStageCodes = collect($shell->stages('oncology'))->pluck('code')->all();
                $oncologyStageFlow = app(\App\Services\Care\Oncology\OncologyWorkflowService::class)->stageFlow();
            }

            if ($module === 'renal') {
                $renalHistory = $clinical->findForVisit($workspaceVisit, 'renal', 'renal_history');
                $renalExam = $clinical->findForVisit($workspaceVisit, 'renal', 'renal_exam');
                $renalDialysis = $clinical->findForVisit($workspaceVisit, 'renal', 'renal_session');
                $renalPlan = $clinical->findForVisit($workspaceVisit, 'renal', 'renal_plan');
                $renalStageCodes = collect($shell->stages('renal'))->pluck('code')->all();
                $renalStageFlow = app(\App\Services\Care\Renal\RenalWorkflowService::class)->stageFlow();
            }

            if ($module === 'surgery') {
                $surgeryHistory = $clinical->findForVisit($workspaceVisit, 'surgery', 'surg_history');
                $surgeryExam = $clinical->findForVisit($workspaceVisit, 'surgery', 'surg_exam');
                $surgeryInvestigation = $clinical->findForVisit($workspaceVisit, 'surgery', 'surg_investigation');
                $surgeryPlan = $clinical->findForVisit($workspaceVisit, 'surgery', 'surg_plan');
                $surgeryProcedure = $clinical->findForVisit($workspaceVisit, 'surgery', 'surg_procedure');
                $surgeryPostop = $clinical->findForVisit($workspaceVisit, 'surgery', 'surg_postop');
                $surgeryStageCodes = collect($shell->stages('surgery'))->pluck('code')->all();
                $surgeryStageFlow = app(\App\Services\Care\Surgery\SurgeryWorkflowService::class)->stageFlow();
            }

            if ($module === 'vaccination') {
                $vaccinationEligibility = $clinical->findForVisit($workspaceVisit, 'vaccination', 'vax_eligibility');
                $vaccinationConsent = $clinical->findForVisit($workspaceVisit, 'vaccination', 'vax_consent');
                $vaccinationAdmin = $clinical->findForVisit($workspaceVisit, 'vaccination', 'vax_admin');
                $vaccinationObservation = $clinical->findForVisit($workspaceVisit, 'vaccination', 'vax_observation');
                $vaccinationStageCodes = collect($shell->stages('vaccination'))->pluck('code')->all();
                $vaccinationStageFlow = app(\App\Services\Care\Vaccination\VaccinationWorkflowService::class)->stageFlow();
            }

            if ($module === 'pathology') {
                $pathologyRequest = $clinical->findForVisit($workspaceVisit, 'pathology', 'path_request');
                $pathologySpecimen = $clinical->findForVisit($workspaceVisit, 'pathology', 'path_specimen');
                $pathologyProcessing = $clinical->findForVisit($workspaceVisit, 'pathology', 'path_processing');
                $pathologyReport = $clinical->findForVisit($workspaceVisit, 'pathology', 'path_report');
                $pathologyVerification = $clinical->findForVisit($workspaceVisit, 'pathology', 'path_verification');
                $pathologyStageCodes = collect($shell->stages('pathology'))->pluck('code')->all();
                $pathologyStageFlow = app(\App\Services\Care\Pathology\PathologyWorkflowService::class)->stageFlow();
            }

            if ($module === 'infusion') {
                $infusionAssessment = $clinical->findForVisit($workspaceVisit, 'infusion', 'infusion_assessment');
                $infusionProtocol = $clinical->findForVisit($workspaceVisit, 'infusion', 'infusion_protocol');
                $infusionSession = $clinical->findForVisit($workspaceVisit, 'infusion', 'infusion_session');
                $infusionMonitoring = $clinical->findForVisit($workspaceVisit, 'infusion', 'infusion_monitoring');
                $infusionStageCodes = collect($shell->stages('infusion'))->pluck('code')->all();
                $infusionStageFlow = app(\App\Services\Care\Infusion\InfusionWorkflowService::class)->stageFlow();
            }

            if ($module === 'dermatology') {
                $dermatologyHistory = $clinical->findForVisit($workspaceVisit, 'dermatology', 'derm_history');
                $dermatologyExam = $clinical->findForVisit($workspaceVisit, 'dermatology', 'skin_exam');
                $dermatologyInvestigation = $clinical->findForVisit($workspaceVisit, 'dermatology', 'derm_investigation');
                $dermatologyPlan = $clinical->findForVisit($workspaceVisit, 'dermatology', 'derm_plan');
                $dermatologyProcedure = $clinical->findForVisit($workspaceVisit, 'dermatology', 'derm_procedure');
                $dermatologyStageCodes = collect($shell->stages('dermatology'))->pluck('code')->all();
                $dermatologyStageFlow = app(\App\Services\Care\Dermatology\DermatologyWorkflowService::class)->stageFlow();
            }

            if ($module === 'podiatry') {
                $podiatryHistory = $clinical->findForVisit($workspaceVisit, 'podiatry', 'pod_history');
                $podiatryExam = $clinical->findForVisit($workspaceVisit, 'podiatry', 'foot_exam');
                $podiatryInvestigation = $clinical->findForVisit($workspaceVisit, 'podiatry', 'pod_investigation');
                $podiatryPlan = $clinical->findForVisit($workspaceVisit, 'podiatry', 'pod_plan');
                $podiatryProcedure = $clinical->findForVisit($workspaceVisit, 'podiatry', 'pod_procedure');
                $podiatryStageCodes = collect($shell->stages('podiatry'))->pluck('code')->all();
                $podiatryStageFlow = app(\App\Services\Care\Podiatry\PodiatryWorkflowService::class)->stageFlow();
            }

            if ($module === 'fertility') {
                $fertilityHistory = $clinical->findForVisit($workspaceVisit, 'fertility', 'fert_history');
                $fertilityExam = $clinical->findForVisit($workspaceVisit, 'fertility', 'fert_exam');
                $fertilityInvestigation = $clinical->findForVisit($workspaceVisit, 'fertility', 'fert_investigation');
                $fertilityPlan = $clinical->findForVisit($workspaceVisit, 'fertility', 'fert_plan');
                $fertilityCycle = $clinical->findForVisit($workspaceVisit, 'fertility', 'fert_cycle');
                $fertilityStageCodes = collect($shell->stages('fertility'))->pluck('code')->all();
                $fertilityStageFlow = app(\App\Services\Care\Fertility\FertilityWorkflowService::class)->stageFlow();
            }

            if ($module === 'child_welfare') {
                $childWelfareIntake = $clinical->findForVisit($workspaceVisit, 'child_welfare', 'cwc_intake');
                $childWelfareAssessment = $clinical->findForVisit($workspaceVisit, 'child_welfare', 'cwc_assessment');
                $childWelfarePlan = $clinical->findForVisit($workspaceVisit, 'child_welfare', 'cwc_plan');
                $childWelfareFollowup = $clinical->findForVisit($workspaceVisit, 'child_welfare', 'cwc_followup');
                $childWelfareStageCodes = collect($shell->stages('child_welfare'))->pluck('code')->all();
                $childWelfareStageFlow = app(\App\Services\Care\ChildWelfare\ChildWelfareWorkflowService::class)->stageFlow();
            }

            if ($module === 'ambulance') {
                $ambulanceDispatch = $clinical->findForVisit($workspaceVisit, 'ambulance', 'amb_dispatch');
                $ambulanceScene = $clinical->findForVisit($workspaceVisit, 'ambulance', 'amb_scene');
                $ambulanceEnRoute = $clinical->findForVisit($workspaceVisit, 'ambulance', 'amb_en_route');
                $ambulanceHandover = $clinical->findForVisit($workspaceVisit, 'ambulance', 'amb_handover');
                $ambulanceStageCodes = collect($shell->stages('ambulance'))->pluck('code')->all();
                $ambulanceStageFlow = app(\App\Services\Care\Ambulance\AmbulanceWorkflowService::class)->stageFlow();
            }

            if ($patientHeader !== null) {
                $patientHeader['clinical_alerts'] = $clinicalAlerts;
            }
            $visitDocuments = $workspaceVisit->patient
                ? $workspaceVisit->patient->attachments()
                    ->where(function ($q) use ($module) {
                        $q->where('document_type', 'specialty_'.$module)
                            ->orWhere('document_type', 'other')
                            ->orWhereNull('document_type');
                    })
                    ->orderByDesc('id')
                    ->limit(20)
                    ->get()
                : collect();

            if ($activeTab === 'orders' && $canConsult) {
                $investigationTypes = InvestigationType::query()
                    ->where('organization_id', $organization->id)
                    ->where('is_active', true)
                    ->orderBy('name')
                    ->get();
            }
        }

        return view('care.specialty.shell', [
            'organization' => $organization,
            'moduleKey' => $module,
            'definition' => $shellDefinition,
            'section' => $section,
            'navItems' => $shell->navItems($module),
            'waiting' => $waiting,
            'queue' => $waiting,
            'inConsultation' => $inConsultation,
            'done' => $done,
            'openVisits' => $openVisits,
            'visitHistory' => $visitHistory,
            'kpis' => $kpis,
            'stages' => $shell->stages($module),
            'specialtyStageFlow' => $shell->stageFlow($module),
            'specialtyStageRoute' => $shell->stageAdvanceRoute($module),
            'services' => $services,
            'workspaceTabs' => $shell->workspaceTabs($module),
            'actions' => $shell->actions($module),
            'activeTab' => $activeTab,
            'workspaceVisit' => $workspaceVisit,
            'patientHeader' => $patientHeader,
            'timeline' => $timeline,
            'clinicalRecord' => $clinicalRecord,
            'clinicalFields' => $clinicalFields,
            'clinicalAlerts' => $clinicalAlerts,
            'visitDocuments' => $visitDocuments,
            'investigationTypes' => $investigationTypes,
            'dentalChart' => $dentalChart,
            'dentalTeethMap' => $dentalTeethMap,
            'dentalPlan' => $dentalPlan,
            'dentalPlanHistory' => $dentalPlanHistory,
            'dentalProcedures' => $dentalProcedures,
            'dentalImages' => $dentalImages,
            'dentalVisitNote' => $dentalVisitNote,
            'dentalCatalog' => $dentalCatalog,
            'dentalRows' => $dentalRows,
            'dentalConditions' => $dentalConditions,
            'dentalStatuses' => $dentalStatuses,
            'dentalSurfaces' => $dentalSurfaces,
            'dentalModalities' => $dentalModalities,
            'dentalDentitions' => $dentalDentitions,
            'dentalPerioExam' => $dentalPerioExam,
            'dentalPerioSurfaces' => $dentalPerioSurfaces,
            'dentalLabCases' => $dentalLabCases,
            'dentalLabCaseTypes' => $dentalLabCaseTypes,
            'dentalLabCaseStatuses' => $dentalLabCaseStatuses,
            'dentalRecalls' => $dentalRecalls,
            'dentalStageCodes' => $dentalStageCodes,
            'emergencyTriage' => $emergencyTriage,
            'emergencyClinicalNote' => $emergencyClinicalNote,
            'emergencyObservation' => $emergencyObservation,
            'emergencyDisposition' => $emergencyDisposition,
            'emergencyVitals' => $emergencyVitals,
            'emergencyLatestVitals' => $emergencyLatestVitals,
            'emergencyStageCodes' => $emergencyStageCodes,
            'emergencyStageFlow' => $emergencyStageFlow,
            'bloodBankRequest' => $bloodBankRequest,
            'bloodBankInventory' => $bloodBankInventory,
            'bloodBankIssue' => $bloodBankIssue,
            'bloodBankTransfusion' => $bloodBankTransfusion,
            'bloodBankStageCodes' => $bloodBankStageCodes,
            'bloodBankStageFlow' => $bloodBankStageFlow,
            'ophthalmologyRefraction' => $ophthalmologyRefraction,
            'ophthalmologyExam' => $ophthalmologyExam,
            'ophthalmologyInvestigation' => $ophthalmologyInvestigation,
            'ophthalmologyPlan' => $ophthalmologyPlan,
            'ophthalmologyProcedure' => $ophthalmologyProcedure,
            'ophthalmologyStageCodes' => $ophthalmologyStageCodes,
            'ophthalmologyStageFlow' => $ophthalmologyStageFlow,
            'physiotherapyAssessment' => $physiotherapyAssessment,
            'physiotherapyPlan' => $physiotherapyPlan,
            'physiotherapySession' => $physiotherapySession,
            'physiotherapyHomeProgram' => $physiotherapyHomeProgram,
            'physiotherapyStageCodes' => $physiotherapyStageCodes,
            'physiotherapyStageFlow' => $physiotherapyStageFlow,
            'maternityHistory' => $maternityHistory,
            'maternityExam' => $maternityExam,
            'maternityFetal' => $maternityFetal,
            'maternityInvestigation' => $maternityInvestigation,
            'maternityPlan' => $maternityPlan,
            'maternityPostnatal' => $maternityPostnatal,
            'maternityStageCodes' => $maternityStageCodes,
            'maternityStageFlow' => $maternityStageFlow,
            'radiologyRequest' => $radiologyRequest,
            'radiologyAcquisition' => $radiologyAcquisition,
            'radiologyReport' => $radiologyReport,
            'radiologyVerification' => $radiologyVerification,
            'radiologyStageCodes' => $radiologyStageCodes,
            'radiologyStageFlow' => $radiologyStageFlow,
            'cardiologyHistory' => $cardiologyHistory,
            'cardiologyExam' => $cardiologyExam,
            'cardiologyInvestigation' => $cardiologyInvestigation,
            'cardiologyPlan' => $cardiologyPlan,
            'cardiologyProcedure' => $cardiologyProcedure,
            'cardiologyStageCodes' => $cardiologyStageCodes,
            'cardiologyStageFlow' => $cardiologyStageFlow,
            'psychiatryHistory' => $psychiatryHistory,
            'psychiatryRisk' => $psychiatryRisk,
            'psychiatryPlan' => $psychiatryPlan,
            'psychiatryFollowup' => $psychiatryFollowup,
            'psychiatryStageCodes' => $psychiatryStageCodes,
            'psychiatryStageFlow' => $psychiatryStageFlow,
            'pediatricsHistory' => $pediatricsHistory,
            'pediatricsExam' => $pediatricsExam,
            'pediatricsInvestigation' => $pediatricsInvestigation,
            'pediatricsPlan' => $pediatricsPlan,
            'pediatricsTreatment' => $pediatricsTreatment,
            'pediatricsStageCodes' => $pediatricsStageCodes,
            'pediatricsStageFlow' => $pediatricsStageFlow,
            'orthopedicsHistory' => $orthopedicsHistory,
            'orthopedicsExam' => $orthopedicsExam,
            'orthopedicsImaging' => $orthopedicsImaging,
            'orthopedicsPlan' => $orthopedicsPlan,
            'orthopedicsProcedure' => $orthopedicsProcedure,
            'orthopedicsStageCodes' => $orthopedicsStageCodes,
            'orthopedicsStageFlow' => $orthopedicsStageFlow,
            'entHistory' => $entHistory,
            'entExam' => $entExam,
            'entInvestigation' => $entInvestigation,
            'entPlan' => $entPlan,
            'entProcedure' => $entProcedure,
            'entStageCodes' => $entStageCodes,
            'entStageFlow' => $entStageFlow,
            'oncologyHistory' => $oncologyHistory,
            'oncologyStaging' => $oncologyStaging,
            'oncologyInvestigation' => $oncologyInvestigation,
            'oncologyPlan' => $oncologyPlan,
            'oncologyTreatment' => $oncologyTreatment,
            'oncologyStageCodes' => $oncologyStageCodes,
            'oncologyStageFlow' => $oncologyStageFlow,
            'renalHistory' => $renalHistory,
            'renalExam' => $renalExam,
            'renalDialysis' => $renalDialysis,
            'renalPlan' => $renalPlan,
            'renalStageCodes' => $renalStageCodes,
            'renalStageFlow' => $renalStageFlow,
            'surgeryHistory' => $surgeryHistory,
            'surgeryExam' => $surgeryExam,
            'surgeryInvestigation' => $surgeryInvestigation,
            'surgeryPlan' => $surgeryPlan,
            'surgeryProcedure' => $surgeryProcedure,
            'surgeryPostop' => $surgeryPostop,
            'surgeryStageCodes' => $surgeryStageCodes,
            'surgeryStageFlow' => $surgeryStageFlow,
            'vaccinationEligibility' => $vaccinationEligibility,
            'vaccinationConsent' => $vaccinationConsent,
            'vaccinationAdmin' => $vaccinationAdmin,
            'vaccinationObservation' => $vaccinationObservation,
            'vaccinationStageCodes' => $vaccinationStageCodes,
            'vaccinationStageFlow' => $vaccinationStageFlow,
            'pathologyRequest' => $pathologyRequest,
            'pathologySpecimen' => $pathologySpecimen,
            'pathologyProcessing' => $pathologyProcessing,
            'pathologyReport' => $pathologyReport,
            'pathologyVerification' => $pathologyVerification,
            'pathologyStageCodes' => $pathologyStageCodes,
            'pathologyStageFlow' => $pathologyStageFlow,
            'infusionAssessment' => $infusionAssessment,
            'infusionProtocol' => $infusionProtocol,
            'infusionSession' => $infusionSession,
            'infusionMonitoring' => $infusionMonitoring,
            'infusionStageCodes' => $infusionStageCodes,
            'infusionStageFlow' => $infusionStageFlow,
            'dermatologyHistory' => $dermatologyHistory,
            'dermatologyExam' => $dermatologyExam,
            'dermatologyInvestigation' => $dermatologyInvestigation,
            'dermatologyPlan' => $dermatologyPlan,
            'dermatologyProcedure' => $dermatologyProcedure,
            'dermatologyStageCodes' => $dermatologyStageCodes,
            'dermatologyStageFlow' => $dermatologyStageFlow,
            'podiatryHistory' => $podiatryHistory,
            'podiatryExam' => $podiatryExam,
            'podiatryInvestigation' => $podiatryInvestigation,
            'podiatryPlan' => $podiatryPlan,
            'podiatryProcedure' => $podiatryProcedure,
            'podiatryStageCodes' => $podiatryStageCodes,
            'podiatryStageFlow' => $podiatryStageFlow,
            'fertilityHistory' => $fertilityHistory,
            'fertilityExam' => $fertilityExam,
            'fertilityInvestigation' => $fertilityInvestigation,
            'fertilityPlan' => $fertilityPlan,
            'fertilityCycle' => $fertilityCycle,
            'fertilityStageCodes' => $fertilityStageCodes,
            'fertilityStageFlow' => $fertilityStageFlow,
            'childWelfareIntake' => $childWelfareIntake,
            'childWelfareAssessment' => $childWelfareAssessment,
            'childWelfarePlan' => $childWelfarePlan,
            'childWelfareFollowup' => $childWelfareFollowup,
            'childWelfareStageCodes' => $childWelfareStageCodes,
            'childWelfareStageFlow' => $childWelfareStageFlow,
            'ambulanceDispatch' => $ambulanceDispatch,
            'ambulanceScene' => $ambulanceScene,
            'ambulanceEnRoute' => $ambulanceEnRoute,
            'ambulanceHandover' => $ambulanceHandover,
            'ambulanceStageCodes' => $ambulanceStageCodes,
            'ambulanceStageFlow' => $ambulanceStageFlow,
            'ambulanceDispatchBoard' => $ambulanceDispatchBoard ?? null,
            'queueStubs' => $modules->queueStubsFor($organization, $module),
            'branchId' => $branchId,
            'branchLabel' => $branchLabel,
            'practitionerScope' => $practitionerScope,
            'lockToPractitioner' => $practitionerScope !== null,
            'canConsult' => $canConsult,
            'canAdvanceStage' => $canAdvanceStage,
            'canStartConsultation' => $canStartConsultation,
            'canPrescribe' => $canPrescribe,
            'canCallNext' => $canCallNext,
            'canManageClinical' => $canManageClinical,
            'canManageVitals' => $canManageVitals,
            'canManageQueue' => $canManageQueue,
            'canAccessPatientQueue' => $canAccessPatientQueue,
            'canBookAppointments' => $canBookAppointments,
            'canViewPatients' => $canViewPatients,
            'canViewAppointments' => $canViewAppointments,
            'canManageSpecialty' => $canManageSpecialty,
            'canViewSpecialty' => $canViewSpecialty,
            'canReferSpecialty' => $canReferSpecialty,
            'specialtyAccessLevel' => $specialtyAccessLevel,
            'queueIntegration' => $branchId
                ? $queueBridge->listMeta($organization, $module, $branchId)
                : ['enabled' => false],
            'currency' => strtoupper((string) config('care.billing.currency', config('care.currency', 'GHS'))),
        ]);
    }
}
