<?php

use Modules\ClinicCore\Http\Controllers\InstallController;
use Modules\ClinicCore\Http\Controllers\DataController;
use Modules\ClinicCore\Http\Controllers\ClcDashboardController;
use Modules\ClinicCore\Http\Controllers\ClcDepartmentController;
use Modules\ClinicCore\Http\Controllers\ClcDoctorController;
use Modules\ClinicCore\Http\Controllers\ClcPatientContactController;
use Modules\ClinicCore\Http\Controllers\ClcPatientController;
use Modules\ClinicCore\Http\Controllers\ClcClinicalPhotoController;
use Modules\ClinicCore\Http\Controllers\ClcTreatmentPlanController;
use Modules\ClinicCore\Http\Controllers\ClcMedicalConditionController;
use Modules\ClinicCore\Http\Controllers\ClcAppointmentController;
use Modules\ClinicCore\Http\Controllers\ClcAppointmentTypeController;
use Modules\ClinicCore\Http\Controllers\ClcAppointmentReasonController;
use Modules\ClinicCore\Http\Controllers\ClcClinicLocationController;
use Modules\ClinicCore\Http\Controllers\ClcPrescriptionController;
use Modules\ClinicCore\Http\Controllers\ClcVaccinationController;
use Modules\ClinicCore\Http\Controllers\ClcMedicineController;
use Modules\ClinicCore\Http\Controllers\ClcReportController;
use Modules\ClinicCore\Http\Controllers\ClcVaccineTypeController;
use Modules\ClinicCore\Http\Controllers\ClcMedicalReportController;
use Modules\ClinicCore\Http\Controllers\ClcBirthDeathRecordController;
use Modules\ClinicCore\Http\Controllers\ClcSettingsController;
use Modules\ClinicCore\Http\Controllers\ClcSoapOptionController;
use Modules\ClinicCore\Http\Controllers\ClcExamController;
use Modules\ClinicCore\Http\Controllers\ClcOwnerBlockingController;
use Modules\ClinicCore\Http\Controllers\ClcVitalRangeController;
use Modules\ClinicCore\Http\Controllers\ClcSystemFindingController;
use Modules\ClinicCore\Http\Controllers\ClcReminderController;
use Modules\ClinicCore\Http\Controllers\ClcProductPickerController;
use Modules\ClinicCore\Http\Controllers\ClcEvaluationController;
use Modules\ClinicCore\Http\Controllers\ClcEvaluationQuestionController;
use Modules\ClinicCore\Http\Controllers\ClcAppointmentEditRequestController;
use Modules\ClinicCore\Http\Controllers\ClcDoctorChangeRequestController;
use Modules\ClinicCore\Http\Controllers\ClcConsentTemplateController;
use Modules\ClinicCore\Http\Controllers\ClcConsentController;
use Modules\ClinicCore\Http\Controllers\ClcConsentVerifyController;
use Modules\ClinicCore\Http\Controllers\ClcVaccinationVerifyController;
use Modules\ClinicCore\Http\Controllers\ClcQuotationController;
use Modules\ClinicCore\Http\Controllers\ClcWellnessController;
use Modules\ClinicCore\Http\Controllers\ClcImagingController;
use Modules\ClinicCore\Http\Controllers\ClcImagingReportController;
use Modules\ClinicCore\Http\Controllers\ClcImagingWorklistController;
use Modules\ClinicCore\Http\Controllers\ClcRoleLandingController;
use Modules\ClinicCore\Http\Controllers\ClcControlledRegisterController;
use Modules\ClinicCore\Http\Controllers\ClcAuthorizedVetController;
use Modules\ClinicCore\Http\Controllers\ClcConfidentialNoteController;
use Modules\ClinicCore\Http\Controllers\ClcPatientBaselineController;
use Modules\ClinicCore\Http\Controllers\ClcPatientMergeController;
use Modules\ClinicCore\Http\Controllers\ClcEncounterController;
use Modules\ClinicCore\Http\Controllers\ClcVitalsController;
use Modules\ClinicCore\Http\Controllers\ClcOrderController;
use Modules\ClinicCore\Http\Controllers\ClcScheduleExceptionController;
use Modules\ClinicCore\Http\Controllers\ClcWaitlistController;
use Modules\ClinicCore\Http\Controllers\ClcQueueController;
use Modules\ClinicCore\Http\Controllers\ClcPharmacyController;
use Modules\ClinicCore\Http\Controllers\ClcReferralController;
use Modules\ClinicCore\Http\Controllers\DevLoginController;

// Public routes (no auth required)
Route::middleware(['web'])->prefix('clinic')->group(function () {
    Route::get('/confirm-email/{token}', [ClcPatientContactController::class, 'confirmEmail'])->name('clinic.patient-contacts.confirm-email');
    Route::get('/verify-consent/{hash}', [ClcConsentVerifyController::class, 'show'])->name('clinic.consents.verify');
    Route::get('/verify-vaccinations/{token}', [ClcVaccinationVerifyController::class, 'show'])->name('clinic.vaccinations.verify');

    // Public quotation approval. Tokens are 48-char hex (bin2hex(random_bytes(24))),
    // so constrain {token} to long alphanumerics — otherwise this catch-all would
    // shadow authed routes like /quotations/search.
    Route::get('/quotations/{token}',          [ClcQuotationController::class, 'publicView'])->name('clinic.quotations.public.view')->where('token', '[A-Za-z0-9]{16,}');
    Route::post('/quotations/{token}/approve', [ClcQuotationController::class, 'publicApprove'])->name('clinic.quotations.public.approve')->where('token', '[A-Za-z0-9]{16,}');
    Route::post('/quotations/{token}/reject',  [ClcQuotationController::class, 'publicReject'])->name('clinic.quotations.public.reject')->where('token', '[A-Za-z0-9]{16,}');
});

// Dev quick-login (no auth) — hard-gated inside the controller by
// config('cliniccore.dev_login'); 404s unless VET_DEV_LOGIN=true in .env.
Route::middleware(['web'])->group(function () {
    Route::get('/dev-login',       [DevLoginController::class, 'index'])->name('clinic.dev-login.index');
    Route::get('/dev-login/{key}', [DevLoginController::class, 'login'])->name('clinic.dev-login.login');
});

// Install / Update routes
Route::middleware(['web', 'auth'])->prefix('clinic')->group(function () {
    Route::get('/install',   [InstallController::class, 'index']);
    Route::post('/install',  [InstallController::class, 'install']);
    Route::get('/uninstall', [InstallController::class, 'uninstall']);
    Route::get('/update',    [InstallController::class, 'update']);
    Route::get('/repair',    [InstallController::class, 'repair']);
});

// Admin routes
Route::group([
    'middleware' => ['web', 'auth', 'SetSessionData', 'language', 'timezone', 'AdminSidebarMenu', 'module:ClinicCore'],
    'prefix'     => 'clinic',
], function () {

    // Dashboard
    Route::get('/', [ClcDashboardController::class, 'index'])->name('clinic.dashboard');

    // Departments
    Route::get('/departments',          [ClcDepartmentController::class, 'index'])->name('clinic.departments.index');
    Route::get('/departments/list',     [ClcDepartmentController::class, 'list'])->name('clinic.departments.list');
    Route::post('/departments/store',   [ClcDepartmentController::class, 'store'])->name('clinic.departments.store');
    Route::get('/departments/{id}/edit',[ClcDepartmentController::class, 'edit'])->name('clinic.departments.edit');
    Route::post('/departments/{id}/update', [ClcDepartmentController::class, 'update'])->name('clinic.departments.update');
    Route::delete('/departments/{id}',  [ClcDepartmentController::class, 'destroy'])->name('clinic.departments.destroy');

    // Doctors
    Route::get('/doctors/search',                    [ClcDoctorController::class, 'search'])->name('clinic.doctors.search');
    Route::get('/doctors/schedule-summary',          [ClcDoctorController::class, 'scheduleSummary'])->name('clinic.doctors.schedule-summary');
    Route::get('/doctors/{id}/schedules',            [ClcDoctorController::class, 'schedules'])->name('clinic.doctors.schedules');
    Route::post('/doctors/{id}/schedules/store',     [ClcDoctorController::class, 'storeSchedule'])->name('clinic.doctors.schedules.store');
    Route::post('/doctors/schedules/{sid}/update',   [ClcDoctorController::class, 'updateSchedule'])->name('clinic.doctors.schedules.update');
    Route::delete('/doctors/schedules/{sid}',        [ClcDoctorController::class, 'destroySchedule'])->name('clinic.doctors.schedules.destroy');
    Route::get('/doctors',              [ClcDoctorController::class, 'index'])->name('clinic.doctors.index');
    Route::get('/doctors/list',         [ClcDoctorController::class, 'list'])->name('clinic.doctors.list');
    Route::post('/doctors/store',       [ClcDoctorController::class, 'store'])->name('clinic.doctors.store');
    Route::get('/doctors/{id}/edit',    [ClcDoctorController::class, 'edit'])->name('clinic.doctors.edit');
    Route::post('/doctors/{id}/update', [ClcDoctorController::class, 'update'])->name('clinic.doctors.update');
    Route::delete('/doctors/{id}',      [ClcDoctorController::class, 'destroy'])->name('clinic.doctors.destroy');

    // Pet Owners  (static routes MUST come before /{id} wildcard)
    Route::get('/patient-contacts',                    [ClcPatientContactController::class, 'index'])->name('clinic.patient-contacts.index');
    Route::get('/patient-contacts/list',               [ClcPatientContactController::class, 'list'])->name('clinic.patient-contacts.list');
    Route::get('/patient-contacts/create',             [ClcPatientContactController::class, 'create'])->name('clinic.patient-contacts.create');
    Route::get('/patient-contacts/search',             [ClcPatientContactController::class, 'search'])->name('clinic.patient-contacts.search');
    Route::post('/patient-contacts/store',             [ClcPatientContactController::class, 'store'])->name('clinic.patient-contacts.store');
    Route::get('/patient-contacts/{id}',               [ClcPatientContactController::class, 'show'])->name('clinic.patient-contacts.show');
    Route::get('/patient-contacts/{id}/edit',          [ClcPatientContactController::class, 'edit'])->name('clinic.patient-contacts.edit');
    Route::post('/patient-contacts/{id}/update',          [ClcPatientContactController::class, 'update'])->name('clinic.patient-contacts.update');
    Route::post('/patient-contacts/{id}/resend-confirmation', [ClcPatientContactController::class, 'resendConfirmation'])->name('clinic.patient-contacts.resend-confirmation');

    // Pets
    Route::get('/patients',                   [ClcPatientController::class, 'index'])->name('clinic.patients.index');
    Route::get('/patients/list',              [ClcPatientController::class, 'list'])->name('clinic.patients.list');
    Route::get('/patients/create',            [ClcPatientController::class, 'create'])->name('clinic.patients.create');
    Route::post('/patients/store',            [ClcPatientController::class, 'store'])->name('clinic.patients.store');
    Route::get('/patients/{id}',              [ClcPatientController::class, 'show'])->name('clinic.patients.show');
    Route::get('/patients/{id}/edit',         [ClcPatientController::class, 'edit'])->name('clinic.patients.edit');
    Route::post('/patients/{id}/update',      [ClcPatientController::class, 'update'])->name('clinic.patients.update');
    Route::delete('/patients/{id}',           [ClcPatientController::class, 'destroy'])->name('clinic.patients.destroy');
    Route::post('/patients/{id}/mark-deceased', [ClcPatientController::class, 'markDeceased'])->name('clinic.patients.mark-deceased');
    Route::get('/patients/{id}/conditions',   [ClcPatientController::class, 'getConditions'])->name('clinic.patients.conditions');
    Route::post('/patients/{id}/conditions/add', [ClcPatientController::class, 'addCondition'])->name('clinic.patients.conditions.add');
    Route::delete('/patients/conditions/{conditionId}', [ClcPatientController::class, 'removeCondition'])->name('clinic.patients.conditions.remove');
    Route::post('/patients/conditions/{conditionId}/update', [ClcPatientController::class, 'updateCondition'])->name('clinic.patients.conditions.update');
    Route::get('/patients/by-owner/{contactId}', [ClcPatientController::class, 'byOwner'])->name('clinic.patients.by-owner');
    Route::get('/patients/{id}/preferred-doctor', [ClcPatientController::class, 'preferredDoctor'])->name('clinic.patients.preferred-doctor');
    Route::get('/patients/{id}/print-vaccinations', [ClcPatientController::class, 'printVaccinations'])->name('clinic.patients.print-vaccinations');

    // Before/after clinical photos
    Route::get('/patients/{id}/photos',        [ClcClinicalPhotoController::class, 'index'])->name('clinic.patients.photos.index');
    Route::post('/patients/{id}/photos',       [ClcClinicalPhotoController::class, 'store'])->name('clinic.patients.photos.store');
    Route::post('/photos/{photoId}/update',    [ClcClinicalPhotoController::class, 'update'])->name('clinic.photos.update');
    Route::delete('/photos/{photoId}',         [ClcClinicalPhotoController::class, 'destroy'])->name('clinic.photos.destroy');

    // Treatment plans & sessions (multi-session courses)
    Route::get('/patients/{id}/treatment-plans',  [ClcTreatmentPlanController::class, 'patientPlans'])->name('clinic.patients.plans.index');
    Route::post('/patients/{id}/treatment-plans', [ClcTreatmentPlanController::class, 'assignPlan'])->name('clinic.patients.plans.assign');
    Route::post('/treatment-plans/{planId}/record', [ClcTreatmentPlanController::class, 'recordSession'])->name('clinic.plans.record');
    Route::post('/treatment-plans/{planId}/cancel', [ClcTreatmentPlanController::class, 'cancelPlan'])->name('clinic.plans.cancel');
    // Package catalogue (settings)
    Route::get('/treatment-packages',           [ClcTreatmentPlanController::class, 'packages'])->name('clinic.packages.index');
    Route::get('/treatment-packages/list',      [ClcTreatmentPlanController::class, 'packagesList'])->name('clinic.packages.list');
    Route::post('/treatment-packages/store',    [ClcTreatmentPlanController::class, 'storePackage'])->name('clinic.packages.store');
    Route::post('/treatment-packages/{id}/update', [ClcTreatmentPlanController::class, 'updatePackage'])->name('clinic.packages.update');
    Route::delete('/treatment-packages/{id}',   [ClcTreatmentPlanController::class, 'destroyPackage'])->name('clinic.packages.destroy');

    // Medical Conditions (catalogue)
    Route::get('/medical-conditions',             [ClcMedicalConditionController::class, 'index'])->name('clinic.medical-conditions.index');
    Route::get('/medical-conditions/list',        [ClcMedicalConditionController::class, 'list'])->name('clinic.medical-conditions.list');
    Route::post('/medical-conditions/store',      [ClcMedicalConditionController::class, 'store'])->name('clinic.medical-conditions.store');
    Route::get('/medical-conditions/{id}/edit',   [ClcMedicalConditionController::class, 'edit'])->name('clinic.medical-conditions.edit');
    Route::post('/medical-conditions/{id}/update',[ClcMedicalConditionController::class, 'update'])->name('clinic.medical-conditions.update');
    Route::delete('/medical-conditions/{id}',     [ClcMedicalConditionController::class, 'destroy'])->name('clinic.medical-conditions.destroy');
    Route::get('/medical-conditions/search',      [ClcMedicalConditionController::class, 'search'])->name('clinic.medical-conditions.search');

    // Appointments — AJAX helpers (static routes before wildcard)
    Route::get('/appointments/locations-by-date',  [ClcAppointmentController::class, 'locationsByDate'])->name('clinic.appointments.locations-by-date');
    Route::get('/appointments/depts-by-location',  [ClcAppointmentController::class, 'deptsByLocation'])->name('clinic.appointments.depts-by-location');
    Route::get('/appointments/doctors-by-dept',    [ClcAppointmentController::class, 'doctorsByDept'])->name('clinic.appointments.doctors-by-dept');
    Route::get('/appointments/slots',              [ClcAppointmentController::class, 'availableSlots'])->name('clinic.appointments.slots');
    Route::get('/appointments/search-invoices',    [ClcAppointmentController::class, 'searchInvoices'])->name('clinic.appointments.search-invoices');
    Route::get('/appointments',                    [ClcAppointmentController::class, 'index'])->name('clinic.appointments.index');
    Route::get('/appointments/calendar',           [ClcAppointmentController::class, 'calendar'])->name('clinic.appointments.calendar');
    Route::get('/appointments/list',               [ClcAppointmentController::class, 'list'])->name('clinic.appointments.list');
    Route::get('/appointments/events',             [ClcAppointmentController::class, 'events'])->name('clinic.appointments.events');
    Route::get('/appointments/create',             [ClcAppointmentController::class, 'create'])->name('clinic.appointments.create');
    Route::post('/appointments/store',             [ClcAppointmentController::class, 'store'])->name('clinic.appointments.store');
    Route::get('/appointments/{id}',               [ClcAppointmentController::class, 'show'])->name('clinic.appointments.show');
    Route::get('/appointments/{id}/print',         [ClcAppointmentController::class, 'print'])->name('clinic.appointments.print');
    Route::get('/appointments/{id}/edit',          [ClcAppointmentController::class, 'edit'])->name('clinic.appointments.edit');
    Route::post('/appointments/{id}/update',       [ClcAppointmentController::class, 'update'])->name('clinic.appointments.update');
    Route::post('/appointments/{id}/status',       [ClcAppointmentController::class, 'updateStatus'])->name('clinic.appointments.status');
    Route::delete('/appointments/{id}',            [ClcAppointmentController::class, 'destroy'])->name('clinic.appointments.destroy');
    Route::post('/appointments/{id}/notes/store',   [ClcAppointmentController::class, 'storeNote'])->name('clinic.appointments.notes.store');

    // ── Item 1.4 - structured Objective exam endpoints ─────────────
    Route::get   ('/appointments/{id}/exam/templates',                 [ClcExamController::class, 'templates'])    ->name('clinic.appointments.exam.templates');
    Route::get   ('/appointments/{id}/exam/findings',                  [ClcExamController::class, 'findings'])     ->name('clinic.appointments.exam.findings');
    Route::post  ('/appointments/{id}/exam/findings',                  [ClcExamController::class, 'saveFinding'])  ->name('clinic.appointments.exam.findings.save');
    Route::delete('/appointments/{id}/exam/findings/{findingId}',      [ClcExamController::class, 'deleteFinding'])->name('clinic.appointments.exam.findings.delete');

    Route::post('/appointments/{id}/consultation',  [ClcAppointmentController::class, 'saveConsultation'])->name('clinic.appointments.consultation');
    Route::post('/appointments/{id}/documents',     [ClcAppointmentController::class, 'uploadDocument'])->name('clinic.appointments.documents.upload');
    Route::delete('/appointments/{id}/documents/{docId}', [ClcAppointmentController::class, 'deleteDocument'])->name('clinic.appointments.documents.delete');
    Route::get('/appointments/{id}/launch-pos',    [ClcAppointmentController::class, 'launchPos'])->name('clinic.appointments.launch-pos');
    Route::post('/appointments/{id}/link-invoice', [ClcAppointmentController::class, 'linkInvoice'])->name('clinic.appointments.link-invoice');
    Route::post('/prescriptions/from-consultation', [ClcPrescriptionController::class, 'storeFromConsultation'])->name('clinic.prescriptions.from-consultation');

    // Appointment Types (settings)
    Route::get('/appointment-types',              [ClcAppointmentTypeController::class, 'index'])->name('clinic.apt-types.index');
    Route::get('/appointment-types/list',         [ClcAppointmentTypeController::class, 'list'])->name('clinic.apt-types.list');
    Route::post('/appointment-types/store',       [ClcAppointmentTypeController::class, 'store'])->name('clinic.apt-types.store');
    Route::get('/appointment-types/{id}/edit',    [ClcAppointmentTypeController::class, 'edit'])->name('clinic.apt-types.edit');
    Route::post('/appointment-types/{id}/update', [ClcAppointmentTypeController::class, 'update'])->name('clinic.apt-types.update');
    Route::delete('/appointment-types/{id}',      [ClcAppointmentTypeController::class, 'destroy'])->name('clinic.apt-types.destroy');

    // Appointment Reasons (settings)
    Route::get('/appointment-reasons',              [ClcAppointmentReasonController::class, 'index'])->name('clinic.apt-reasons.index');
    Route::get('/appointment-reasons/list',         [ClcAppointmentReasonController::class, 'list'])->name('clinic.apt-reasons.list');
    Route::post('/appointment-reasons/store',       [ClcAppointmentReasonController::class, 'store'])->name('clinic.apt-reasons.store');
    Route::get('/appointment-reasons/{id}/edit',    [ClcAppointmentReasonController::class, 'edit'])->name('clinic.apt-reasons.edit');
    Route::post('/appointment-reasons/{id}/update', [ClcAppointmentReasonController::class, 'update'])->name('clinic.apt-reasons.update');
    Route::delete('/appointment-reasons/{id}',      [ClcAppointmentReasonController::class, 'destroy'])->name('clinic.apt-reasons.destroy');

    // Module Settings
    Route::get('/settings',              [ClcSettingsController::class, 'index'])->name('clinic.settings.index');
    Route::post('/settings/save',        [ClcSettingsController::class, 'save'])->name('clinic.settings.save');
    Route::post('/settings/apply-preset',[ClcSettingsController::class, 'applyPreset'])->name('clinic.settings.apply-preset');

    // AI medical assistant (via AiCore, soft-guarded)
    Route::post('/ai/ask', [\Modules\ClinicCore\Http\Controllers\ClcAiController::class, 'ask'])->name('clinic.ai.ask');
    Route::post('/ai/ask-stream', [\Modules\ClinicCore\Http\Controllers\ClcAiController::class, 'askStream'])->name('clinic.ai.ask-stream');
    // Clean recognised text from the browser Web Speech path (which skips the
    // server), so Web Speech dictation gets the same non-medical side-talk cleanup.
    Route::post('/ai/clean-transcript', [\Modules\ClinicCore\Http\Controllers\ClcAiController::class, 'cleanTranscript'])->name('clinic.ai.clean-transcript');
    // AI prescription safety check (allergy / interaction / contraindication / duplicate).
    Route::post('/prescriptions/check-safety', [ClcPrescriptionController::class, 'checkSafety'])->name('clinic.prescriptions.check-safety');

    // PWA Portal Brand (settings → pet-owner PWA branding)
    Route::get('/portal-brand',          [\Modules\ClinicCore\Http\Controllers\ClcPortalBrandController::class, 'index'])->name('clinic.portal-brand.index');
    Route::post('/portal-brand/save',    [\Modules\ClinicCore\Http\Controllers\ClcPortalBrandController::class, 'save'])->name('clinic.portal-brand.save');
    Route::post('/portal-brand/logo',    [\Modules\ClinicCore\Http\Controllers\ClcPortalBrandController::class, 'uploadLogo'])->name('clinic.portal-brand.logo');

    // PWA Engagement (analytics + broadcast push + per-owner detail)
    Route::get('/portal-engagement',                       [\Modules\ClinicCore\Http\Controllers\ClcPortalEngagementController::class, 'index'])->name('clinic.portal-engagement.index');
    Route::post('/portal-engagement/broadcast',            [\Modules\ClinicCore\Http\Controllers\ClcPortalEngagementController::class, 'broadcast'])->name('clinic.portal-engagement.broadcast');
    Route::get('/portal-engagement/owner/{id}',            [\Modules\ClinicCore\Http\Controllers\ClcPortalEngagementController::class, 'ownerDetail'])->where('id', '[0-9]+')->name('clinic.portal-engagement.owner');
    Route::post('/portal-engagement/owner/{id}/sign-out',  [\Modules\ClinicCore\Http\Controllers\ClcPortalEngagementController::class, 'signOutEverywhere'])->where('id', '[0-9]+')->name('clinic.portal-engagement.owner.sign-out');

    // SOAP Options (settings + AJAX)
    Route::get('/soap-options',               [ClcSoapOptionController::class, 'index'])->name('clinic.soap-options.index');
    Route::get('/soap-options/data',          [ClcSoapOptionController::class, 'data'])->name('clinic.soap-options.data');
    Route::get('/soap-options/search',        [ClcSoapOptionController::class, 'search'])->name('clinic.soap-options.search');
    Route::post('/soap-options/store',            [ClcSoapOptionController::class, 'store'])->name('clinic.soap-options.store');
    Route::post('/soap-options/group/update',     [ClcSoapOptionController::class, 'updateGroup'])->name('clinic.soap-options.group.update');
    Route::post('/soap-options/{id}/update',      [ClcSoapOptionController::class, 'update'])->name('clinic.soap-options.update');
    Route::delete('/soap-options/{id}',           [ClcSoapOptionController::class, 'destroy'])->name('clinic.soap-options.destroy');
    Route::post('/soap-options/{id}/toggle',      [ClcSoapOptionController::class, 'toggleStatus'])->name('clinic.soap-options.toggle');

    // Clinic Locations (settings)
    Route::get('/locations',              [ClcClinicLocationController::class, 'index'])->name('clinic.locations.index');
    Route::get('/locations/list',         [ClcClinicLocationController::class, 'list'])->name('clinic.locations.list');
    Route::post('/locations/store',       [ClcClinicLocationController::class, 'store'])->name('clinic.locations.store');
    Route::get('/locations/{id}/edit',    [ClcClinicLocationController::class, 'edit'])->name('clinic.locations.edit');
    Route::post('/locations/{id}/update', [ClcClinicLocationController::class, 'update'])->name('clinic.locations.update');
    Route::delete('/locations/{id}',      [ClcClinicLocationController::class, 'destroy'])->name('clinic.locations.destroy');

    // Vaccinations
    Route::get('/vaccinations',                     [ClcVaccinationController::class, 'index'])->name('clinic.vaccinations.index');
    Route::get('/vaccinations/list',                [ClcVaccinationController::class, 'list'])->name('clinic.vaccinations.list');
    Route::post('/vaccinations/store',              [ClcVaccinationController::class, 'store'])->name('clinic.vaccinations.store');
    Route::get('/vaccinations/{id}/edit',           [ClcVaccinationController::class, 'edit'])->name('clinic.vaccinations.edit');
    Route::post('/vaccinations/{id}/update',        [ClcVaccinationController::class, 'update'])->name('clinic.vaccinations.update');
    Route::delete('/vaccinations/{id}',             [ClcVaccinationController::class, 'destroy'])->name('clinic.vaccinations.destroy');
    Route::get('/vaccine-types/search',             [ClcVaccinationController::class, 'searchVaccineTypes'])->name('clinic.vaccine-types.search');
    Route::post('/vaccinations/{id}/remind',              [ClcVaccinationController::class, 'markReminded'])->name('clinic.vaccinations.remind');
    Route::post('/vaccinations/{id}/send-email-reminder', [ClcVaccinationController::class, 'sendEmailReminder'])->name('clinic.vaccinations.send-email-reminder');
    Route::post('/vaccinations/{id}/waive',               [ClcVaccinationController::class, 'waive'])->name('clinic.vaccinations.waive');
    Route::post('/vaccinations/{id}/unwaive',             [ClcVaccinationController::class, 'unwaive'])->name('clinic.vaccinations.unwaive');

    // Prescriptions
    Route::get('/prescriptions',                    [ClcPrescriptionController::class, 'index'])->name('clinic.prescriptions.index');
    Route::get('/prescriptions/list',               [ClcPrescriptionController::class, 'list'])->name('clinic.prescriptions.list');
    Route::get('/prescriptions/create',             [ClcPrescriptionController::class, 'create'])->name('clinic.prescriptions.create');
    Route::post('/prescriptions/store',             [ClcPrescriptionController::class, 'store'])->name('clinic.prescriptions.store');
    Route::get('/prescriptions/{id}',               [ClcPrescriptionController::class, 'show'])->name('clinic.prescriptions.show');
    Route::get('/prescriptions/{id}/edit',          [ClcPrescriptionController::class, 'edit'])->name('clinic.prescriptions.edit');
    Route::post('/prescriptions/{id}/update',       [ClcPrescriptionController::class, 'update'])->name('clinic.prescriptions.update');
    Route::delete('/prescriptions/{id}',            [ClcPrescriptionController::class, 'destroy'])->name('clinic.prescriptions.destroy');
    Route::get('/prescriptions/{id}/print',         [ClcPrescriptionController::class, 'print'])->name('clinic.prescriptions.print');
    // NOTE: the per-item dispense-options + dispense endpoints are registered once
    // in the "P4 pharmacy/referrals" block below (ClcPharmacyController), and are
    // used by BOTH the pharmacy queue and the Rx show-view dispense modal.

    // Medicines (pharmacy catalogue)
    Route::get('/medicines',                        [ClcMedicineController::class, 'index'])->name('clinic.medicines.index');
    Route::get('/medicines/list',                   [ClcMedicineController::class, 'list'])->name('clinic.medicines.list');
    Route::post('/medicines/store',                 [ClcMedicineController::class, 'store'])->name('clinic.medicines.store');
    Route::get('/medicines/{id}/edit',              [ClcMedicineController::class, 'edit'])->name('clinic.medicines.edit');
    Route::post('/medicines/{id}/update',           [ClcMedicineController::class, 'update'])->name('clinic.medicines.update');
    Route::delete('/medicines/{id}',                [ClcMedicineController::class, 'destroy'])->name('clinic.medicines.destroy');
    Route::get('/medicines/product-search',          [ClcMedicineController::class, 'productSearch'])->name('clinic.medicines.product-search');
    Route::get('/medicines/search',                 [ClcMedicineController::class, 'search'])->name('clinic.medicines.search');

    // Reports
    Route::get('/reports',                          [ClcReportController::class, 'index'])->name('clinic.reports.index');
    Route::get('/reports/kpi',                      [ClcReportController::class, 'kpiDashboard'])->name('clinic.reports.kpi');
    Route::get('/reports/appointments',             [ClcReportController::class, 'appointments'])->name('clinic.reports.appointments');
    Route::get('/reports/critical-check',            [ClcReportController::class, 'criticalCheck'])->name('clinic.reports.critical-check');

    // ── Item 3.1 / 3.2 / 2.2 — Owner blocking ──────────────────────
    // Item #2 - preferred doctor change endpoints (owner-level + pet-level)
    Route::post('/patient-contacts/{id}/preferred-doctor', [ClcPatientContactController::class, 'setPreferredDoctor'])->name('clinic.patient-contacts.set-preferred-doctor');
    Route::post('/patients/{id}/preferred-doctor',       [ClcPatientController::class, 'setPreferredDoctor'])    ->name('clinic.patients.set-preferred-doctor');
    Route::post('/patient-contacts/{id}/whatsapp',         [ClcPatientContactController::class, 'setWhatsappState'])->name('clinic.patient-contacts.set-whatsapp');
    Route::post('/patient-contacts/{id}/send-message',     [ClcPatientContactController::class, 'sendMessage'])     ->name('clinic.patient-contacts.send-message');
    // Item #8 - professional PDF clinical history (dompdf, with QR)
    Route::get ('/patients/{id}/clinical-history.pdf',   [ClcPatientController::class, 'printClinicalHistoryPdf'])->name('clinic.patients.clinical-history.pdf');

    // Item #1 - vital-range admin CRUD
    Route::get   ('/vital-ranges',                   [ClcVitalRangeController::class, 'index'])  ->name('clinic.vital-ranges.index');
    Route::get   ('/vital-ranges/create',            [ClcVitalRangeController::class, 'create']) ->name('clinic.vital-ranges.create');
    Route::post  ('/vital-ranges',                   [ClcVitalRangeController::class, 'store'])  ->name('clinic.vital-ranges.store');
    Route::get   ('/vital-ranges/{id}/edit',         [ClcVitalRangeController::class, 'edit'])   ->name('clinic.vital-ranges.edit');
    Route::post  ('/vital-ranges/{id}',              [ClcVitalRangeController::class, 'update']) ->name('clinic.vital-ranges.update');
    Route::delete('/vital-ranges/{id}',              [ClcVitalRangeController::class, 'destroy'])->name('clinic.vital-ranges.destroy');

    // Item #4a - body-system finding catalogues (admin CRUD + JSON for appointment page)
    Route::get   ('/system-findings',                                [ClcSystemFindingController::class, 'index'])    ->name('clinic.system-findings.index');
    Route::get   ('/system-findings/catalogue/{systemKey}.json',     [ClcSystemFindingController::class, 'catalogue'])->name('clinic.system-findings.catalogue');
    Route::get   ('/system-findings/{systemKey}',                    [ClcSystemFindingController::class, 'list'])    ->name('clinic.system-findings.list');
    Route::get   ('/system-findings/{systemKey}/create',             [ClcSystemFindingController::class, 'create'])  ->name('clinic.system-findings.create');
    Route::post  ('/system-findings',                                [ClcSystemFindingController::class, 'store'])   ->name('clinic.system-findings.store');
    Route::get   ('/system-findings/edit/{id}',                      [ClcSystemFindingController::class, 'edit'])    ->name('clinic.system-findings.edit');
    Route::post  ('/system-findings/edit/{id}',                      [ClcSystemFindingController::class, 'update'])  ->name('clinic.system-findings.update');
    Route::delete('/system-findings/{id}',                           [ClcSystemFindingController::class, 'destroy']) ->name('clinic.system-findings.destroy');

    Route::get ('/owner-blocking',                    [ClcOwnerBlockingController::class, 'index'])      ->name('clinic.owner-blocking.index');
    Route::get ('/owner-blocking/settings',           [ClcOwnerBlockingController::class, 'settings'])   ->name('clinic.owner-blocking.settings');
    Route::post('/owner-blocking/settings',           [ClcOwnerBlockingController::class, 'saveSettings'])->name('clinic.owner-blocking.save');
    Route::post('/owner-blocking/{id}/block',         [ClcOwnerBlockingController::class, 'block'])      ->name('clinic.owner-blocking.block');
    Route::post('/owner-blocking/{id}/unblock',       [ClcOwnerBlockingController::class, 'unblock'])    ->name('clinic.owner-blocking.unblock');
    // Item 1.3 - live vital ranges for inline form warnings
    Route::get('/appointments/{id}/vital-ranges',    [ClcAppointmentController::class, 'vitalRanges'])->name('clinic.appointments.vital-ranges');
    Route::get('/reports/vaccinations-due',         [ClcReportController::class, 'vaccinationsDue'])->name('clinic.reports.vaccinations-due');
    Route::get('/reports/pet-registrations',        [ClcReportController::class, 'petRegistrations'])->name('clinic.reports.pet-registrations');
    Route::get('/reports/doctor-activity',          [ClcReportController::class, 'doctorActivity'])->name('clinic.reports.doctor-activity');
    Route::get('/reports/evaluations',              [ClcReportController::class, 'evaluations'])->name('clinic.reports.evaluations');
    Route::get('/reports/time-tracking',            [ClcReportController::class, 'timeTracking'])->name('clinic.reports.time-tracking');
    Route::get('/reports/owner-geography',          [ClcReportController::class, 'ownerGeography'])->name('clinic.reports.owner-geography');
    Route::get('/reports/visit-patterns',           [ClcReportController::class, 'visitPatterns'])->name('clinic.reports.visit-patterns');
    Route::get('/reports/inactive-owners',          [ClcReportController::class, 'inactiveOwners'])->name('clinic.reports.inactive-owners');
    Route::get('/reports/preferred-doctor-changes', [ClcReportController::class, 'preferredDoctorChanges'])->name('clinic.reports.preferred-doctor-changes');

    // Evaluation Questions (settings)
    Route::get('/evaluation-questions',              [ClcEvaluationQuestionController::class, 'index'])->name('clinic.evaluation-questions.index');
    Route::get('/evaluation-questions/list',         [ClcEvaluationQuestionController::class, 'list'])->name('clinic.evaluation-questions.list');
    Route::post('/evaluation-questions/store',       [ClcEvaluationQuestionController::class, 'store'])->name('clinic.evaluation-questions.store');
    Route::get('/evaluation-questions/{id}/edit',    [ClcEvaluationQuestionController::class, 'edit'])->name('clinic.evaluation-questions.edit');
    Route::post('/evaluation-questions/{id}/update', [ClcEvaluationQuestionController::class, 'update'])->name('clinic.evaluation-questions.update');
    Route::delete('/evaluation-questions/{id}',      [ClcEvaluationQuestionController::class, 'destroy'])->name('clinic.evaluation-questions.destroy');

    // Evaluations (per appointment)
    Route::get('/appointments/{id}/evaluation/form',   [ClcEvaluationController::class, 'form'])->name('clinic.evaluations.form');
    Route::post('/appointments/{id}/evaluation',       [ClcEvaluationController::class, 'store'])->name('clinic.evaluations.store');
    Route::get('/appointments/{id}/evaluation/status', [ClcEvaluationController::class, 'status'])->name('clinic.evaluations.status');
    Route::post('/evaluations/{id}/review',            [ClcEvaluationController::class, 'review'])->name('clinic.evaluations.review');

    // Appointment edit requests (post-completion edit approval workflow)
    Route::post('/appointments/{id}/edit-request',           [ClcAppointmentEditRequestController::class, 'store'])->name('clinic.edit-requests.store');
    Route::get('/appointment-edit-requests',                 [ClcAppointmentEditRequestController::class, 'index'])->name('clinic.edit-requests.index');
    Route::get('/appointment-edit-requests/list',            [ClcAppointmentEditRequestController::class, 'list'])->name('clinic.edit-requests.list');
    Route::post('/appointment-edit-requests/{id}/approved',  [ClcAppointmentEditRequestController::class, 'approve'])->name('clinic.edit-requests.approve');
    Route::post('/appointment-edit-requests/{id}/rejected',  [ClcAppointmentEditRequestController::class, 'reject'])->name('clinic.edit-requests.reject');

    // Doctor-change requests (preferred-doctor exception approval workflow)
    Route::post('/appointments/{id}/doctor-change-request',  [ClcDoctorChangeRequestController::class, 'store'])->name('clinic.doctor-change-requests.store');
    Route::get('/doctor-change-requests',                    [ClcDoctorChangeRequestController::class, 'index'])->name('clinic.doctor-change-requests.index');
    Route::get('/doctor-change-requests/list',               [ClcDoctorChangeRequestController::class, 'list'])->name('clinic.doctor-change-requests.list');
    Route::post('/doctor-change-requests/{id}/approved',     [ClcDoctorChangeRequestController::class, 'approve'])->name('clinic.doctor-change-requests.approve');
    Route::post('/doctor-change-requests/{id}/rejected',     [ClcDoctorChangeRequestController::class, 'reject'])->name('clinic.doctor-change-requests.reject');

    // Role Landing Pages (per-role post-login redirect)
    Route::get('/role-landing',       [ClcRoleLandingController::class, 'index'])->name('clinic.role-landing.index');
    Route::post('/role-landing/save', [ClcRoleLandingController::class, 'save'])->name('clinic.role-landing.save');

    // Confidential notes (polymorphic — pet or owner)
    Route::get('/notes/{subject_type}/{subject_id}',  [ClcConfidentialNoteController::class, 'index'])->name('clinic.notes.index');
    Route::post('/notes/{subject_type}/{subject_id}', [ClcConfidentialNoteController::class, 'store'])->name('clinic.notes.store');
    Route::post('/notes/{id}/update',                  [ClcConfidentialNoteController::class, 'update'])->name('clinic.notes.update');
    Route::delete('/notes/{id}',                       [ClcConfidentialNoteController::class, 'destroy'])->name('clinic.notes.destroy');

    // Controlled-drug register (Phase 1 — flag medicines + log IN/OUT movements)
    Route::get('/controlled-register',        [ClcControlledRegisterController::class, 'index'])->name('clinic.controlled-register.index');
    Route::get('/controlled-register/list',   [ClcControlledRegisterController::class, 'list'])->name('clinic.controlled-register.list');
    Route::post('/controlled-register/store', [ClcControlledRegisterController::class, 'store'])->name('clinic.controlled-register.store');
    Route::get('/controlled-register/print',  [ClcControlledRegisterController::class, 'print'])->name('clinic.controlled-register.print');
    Route::get('/controlled-register/reconcile',  [ClcControlledRegisterController::class, 'reconcile'])->name('clinic.controlled-register.reconcile');
    Route::post('/controlled-register/reconcile', [ClcControlledRegisterController::class, 'recordReconciliation'])->name('clinic.controlled-register.reconcile.store');
    Route::get('/controlled-register/expected-balance', [ClcControlledRegisterController::class, 'expectedBalance'])->name('clinic.controlled-register.expected-balance');

    // Vet quotation wrapper
    Route::get('/quotations/search',                       [ClcQuotationController::class, 'search'])->name('clinic.quotations.search');
    Route::get('/appointments/{id}/quotations',            [ClcQuotationController::class, 'appointmentList'])->name('clinic.quotations.appointment-list');
    Route::post('/appointments/{id}/quotations/link',      [ClcQuotationController::class, 'link'])->name('clinic.quotations.link');
    Route::delete('/quotations/meta/{id}',                 [ClcQuotationController::class, 'unlink'])->name('clinic.quotations.unlink');
    Route::post('/quotations/meta/{id}/send-approval',     [ClcQuotationController::class, 'sendApproval'])->name('clinic.quotations.send-approval');
    Route::post('/quotations/meta/{id}/mark-converted',    [ClcQuotationController::class, 'markConverted'])->name('clinic.quotations.mark-converted');

    // Wellness plans (P6)
    Route::get('/wellness',                       [ClcWellnessController::class, 'index'])->name('clinic.wellness.index');
    Route::post('/wellness/plans',                [ClcWellnessController::class, 'storePlan'])->name('clinic.wellness.store-plan');
    Route::post('/wellness/plans/{id}/benefits',  [ClcWellnessController::class, 'addBenefit'])->name('clinic.wellness.add-benefit');
    Route::post('/wellness/subscribe',            [ClcWellnessController::class, 'subscribe'])->name('clinic.wellness.subscribe');
    Route::post('/wellness/subscriptions/{id}/cancel', [ClcWellnessController::class, 'cancel'])->name('clinic.wellness.cancel');
    Route::get('/wellness/active',                [ClcWellnessController::class, 'active'])->name('clinic.wellness.active');
    Route::post('/wellness/redeem',               [ClcWellnessController::class, 'redeem'])->name('clinic.wellness.redeem');

    // Imaging (P5.2)
    Route::get('/imaging',                            [ClcImagingController::class, 'index'])->name('clinic.imaging.index');
    Route::post('/imaging',                           [ClcImagingController::class, 'store'])->name('clinic.imaging.store');
    Route::post('/imaging/{id}/status',               [ClcImagingController::class, 'updateStatus'])->name('clinic.imaging.status');
    Route::post('/imaging/{id}/study',                [ClcImagingController::class, 'uploadStudy'])->name('clinic.imaging.upload-study');
    Route::delete('/imaging/studies/{id}',            [ClcImagingController::class, 'deleteStudy'])->name('clinic.imaging.delete-study');
    Route::post('/controlled-register/{id}/resolve', [ClcControlledRegisterController::class, 'resolveUnverified'])->name('clinic.controlled-register.resolve');
    Route::get('/controlled-register/verify',        [ClcControlledRegisterController::class, 'verifyChain'])->name('clinic.controlled-register.verify');
    Route::post('/controlled-register/seal',         [ClcControlledRegisterController::class, 'sealNow'])->name('clinic.controlled-register.seal');

    // Authorised vets (Phase 2 — permit-holders for dispensing controlled drugs)
    Route::get('/authorized-vets',       [ClcAuthorizedVetController::class, 'index'])->name('clinic.authorized-vets.index');
    Route::post('/authorized-vets',      [ClcAuthorizedVetController::class, 'store'])->name('clinic.authorized-vets.store');
    Route::delete('/authorized-vets/{id}',[ClcAuthorizedVetController::class, 'destroy'])->name('clinic.authorized-vets.destroy');

    // Consent Templates (settings) + issued consents
    Route::get('/consent-templates',              [ClcConsentTemplateController::class, 'index'])->name('clinic.consent-templates.index');
    Route::get('/consent-templates/list',         [ClcConsentTemplateController::class, 'list'])->name('clinic.consent-templates.list');
    Route::post('/consent-templates/store',       [ClcConsentTemplateController::class, 'store'])->name('clinic.consent-templates.store');
    Route::get('/consent-templates/{id}/edit',    [ClcConsentTemplateController::class, 'edit'])->name('clinic.consent-templates.edit');
    Route::post('/consent-templates/{id}/update', [ClcConsentTemplateController::class, 'update'])->name('clinic.consent-templates.update');
    Route::post('/consent-templates/{id}/clone',  [ClcConsentTemplateController::class, 'clone'])->name('clinic.consent-templates.clone');
    Route::delete('/consent-templates/{id}',      [ClcConsentTemplateController::class, 'destroy'])->name('clinic.consent-templates.destroy');

    Route::get('/appointments/{id}/consents',       [ClcConsentController::class, 'appointmentList'])->name('clinic.consents.appointment-list');
    Route::post('/appointments/{id}/consents/issue',[ClcConsentController::class, 'issue'])->name('clinic.consents.issue');
    Route::get('/consents/{id}/print',              [ClcConsentController::class, 'print'])->name('clinic.consents.print');
    Route::get('/consents/{id}/sign',               [ClcConsentController::class, 'sign'])->name('clinic.consents.sign');
    Route::post('/consents/{id}/sign',              [ClcConsentController::class, 'storeSignature'])->name('clinic.consents.store-signature');
    Route::post('/consents/{id}/archive',           [ClcConsentController::class, 'archive'])->name('clinic.consents.archive');
    Route::post('/consents/{id}/signed',            [ClcConsentController::class, 'uploadSigned'])->name('clinic.consents.upload-signed');
    Route::delete('/consents/{id}/signed',          [ClcConsentController::class, 'removeSigned'])->name('clinic.consents.remove-signed');
    Route::delete('/consents/{id}',                 [ClcConsentController::class, 'destroy'])->name('clinic.consents.destroy');

    // Vaccine Types (catalogue management)
    Route::get('/vaccine-types',                    [ClcVaccineTypeController::class, 'index'])->name('clinic.vaccine-types.index');
    Route::get('/vaccine-types/list',               [ClcVaccineTypeController::class, 'list'])->name('clinic.vaccine-types.list');
    Route::post('/vaccine-types/store',             [ClcVaccineTypeController::class, 'store'])->name('clinic.vaccine-types.store');
    Route::get('/vaccine-types/{id}/edit',          [ClcVaccineTypeController::class, 'edit'])->name('clinic.vaccine-types.edit');
    Route::post('/vaccine-types/{id}/update',       [ClcVaccineTypeController::class, 'update'])->name('clinic.vaccine-types.update');
    Route::delete('/vaccine-types/{id}',            [ClcVaccineTypeController::class, 'destroy'])->name('clinic.vaccine-types.destroy');

    // Product picker (links vet catalogue items → ERP products)
    Route::get('/products/search',                  [ClcProductPickerController::class, 'search'])->name('clinic.products.search');
    Route::get('/products/{id}/lookup',             [ClcProductPickerController::class, 'lookup'])->name('clinic.products.lookup');

    // Exam not-done reasons (used inside the consultation exam status panel)
    Route::get('/exam-not-done-reasons',            [ClcAppointmentController::class, 'examNotDoneReasons'])->name('clinic.exam-not-done-reasons.list');

    // Medical Reports
    Route::get('/medical-reports',                  [ClcMedicalReportController::class, 'index'])->name('clinic.medical-reports.index');
    Route::get('/medical-reports/list',             [ClcMedicalReportController::class, 'list'])->name('clinic.medical-reports.list');
    Route::get('/medical-reports/create',           [ClcMedicalReportController::class, 'create'])->name('clinic.medical-reports.create');
    Route::post('/medical-reports/store',           [ClcMedicalReportController::class, 'store'])->name('clinic.medical-reports.store');
    Route::get('/medical-reports/{id}',             [ClcMedicalReportController::class, 'show'])->name('clinic.medical-reports.show');
    Route::get('/medical-reports/{id}/edit',        [ClcMedicalReportController::class, 'edit'])->name('clinic.medical-reports.edit');
    Route::post('/medical-reports/{id}/update',     [ClcMedicalReportController::class, 'update'])->name('clinic.medical-reports.update');
    Route::delete('/medical-reports/{id}',          [ClcMedicalReportController::class, 'destroy'])->name('clinic.medical-reports.destroy');

    // Birth & Death Records
    Route::get('/birth-death',                      [ClcBirthDeathRecordController::class, 'index'])->name('clinic.birth-death.index');
    Route::get('/birth-death/list',                 [ClcBirthDeathRecordController::class, 'list'])->name('clinic.birth-death.list');
    Route::post('/birth-death/store',               [ClcBirthDeathRecordController::class, 'store'])->name('clinic.birth-death.store');
    Route::get('/birth-death/{id}/edit',            [ClcBirthDeathRecordController::class, 'edit'])->name('clinic.birth-death.edit');
    Route::post('/birth-death/{id}/update',         [ClcBirthDeathRecordController::class, 'update'])->name('clinic.birth-death.update');
    Route::delete('/birth-death/{id}',              [ClcBirthDeathRecordController::class, 'destroy'])->name('clinic.birth-death.destroy');

    // Reminder Settings & Templates
    Route::get('/reminders/settings',                        [ClcReminderController::class, 'settings'])->name('clinic.reminders.settings');
    Route::post('/reminders/settings/save',                  [ClcReminderController::class, 'saveSettings'])->name('clinic.reminders.settings.save');
    Route::get('/reminders/templates',                       [ClcReminderController::class, 'templates'])->name('clinic.reminders.templates');
    Route::get('/reminders/templates/{id}/edit',             [ClcReminderController::class, 'editTemplate'])->name('clinic.reminders.templates.edit');
    Route::post('/reminders/templates/{id}/update',          [ClcReminderController::class, 'updateTemplate'])->name('clinic.reminders.templates.update');
    Route::post('/reminders/send-now',                       [ClcReminderController::class, 'sendNow'])->name('clinic.reminders.send-now');
    Route::post('/reminders/send-manual/{id}',               [ClcReminderController::class, 'sendManual'])->name('clinic.reminders.send-manual');

    // ─────────────────────────────────────────────────────────────────────
    // P3 patient master (SIFA P3-T1 patient master extensions + P3-T8 alerts)
    // Structured clinical baseline CRUD, patient merge / duplicate detection,
    // and medical-alert acknowledge/resolve — all business-scoped + perm-gated.
    // ─────────────────────────────────────────────────────────────────────

    // Structured allergies (clinic.allergy.manage)
    Route::post  ('/patients/{id}/allergies',           [ClcPatientBaselineController::class, 'storeAllergy'])->name('clinic.patients.allergies.store');
    Route::post  ('/patients/allergies/{allergyId}/update', [ClcPatientBaselineController::class, 'updateAllergy'])->name('clinic.patients.allergies.update');
    Route::delete('/patients/allergies/{allergyId}',    [ClcPatientBaselineController::class, 'destroyAllergy'])->name('clinic.patients.allergies.destroy');

    // Current medications (home meds, outside our Rx)
    Route::post  ('/patients/{id}/medications',         [ClcPatientBaselineController::class, 'storeMedication'])->name('clinic.patients.medications.store');
    Route::post  ('/patients/medications/{medId}/update', [ClcPatientBaselineController::class, 'updateMedication'])->name('clinic.patients.medications.update');
    Route::delete('/patients/medications/{medId}',      [ClcPatientBaselineController::class, 'destroyMedication'])->name('clinic.patients.medications.destroy');

    // Insurance cards (Phase-4 claims are separate)
    Route::post  ('/patients/{id}/insurances',          [ClcPatientBaselineController::class, 'storeInsurance'])->name('clinic.patients.insurances.store');
    Route::post  ('/patients/insurances/{insId}/update',[ClcPatientBaselineController::class, 'updateInsurance'])->name('clinic.patients.insurances.update');
    Route::delete('/patients/insurances/{insId}',       [ClcPatientBaselineController::class, 'destroyInsurance'])->name('clinic.patients.insurances.destroy');

    // Medical alerts (P3-T8): manual raise + acknowledge/resolve
    Route::post ('/patients/{id}/alerts',               [ClcPatientBaselineController::class, 'storeAlert'])->name('clinic.patients.alerts.store');
    Route::post ('/patients/alerts/{alertId}/acknowledge', [ClcPatientBaselineController::class, 'acknowledgeAlert'])->name('clinic.patients.alerts.acknowledge');
    Route::post ('/patients/alerts/{alertId}/resolve',  [ClcPatientBaselineController::class, 'resolveAlert'])->name('clinic.patients.alerts.resolve');

    // Patient merge / duplicate detection (clinic.patient.merge)
    Route::get  ('/patients-duplicates',                [ClcPatientMergeController::class, 'index'])->name('clinic.patients.duplicates');
    Route::post ('/patients-duplicates/merge',          [ClcPatientMergeController::class, 'merge'])->name('clinic.patients.merge');

    // ─────────────────────────────────────────────────────────────────────
    // P3 encounters/notes/vitals (SIFA P3-T2 encounters, P3-T3 clinical notes,
    // P3-T4 vitals). All business-scoped + permission-gated; the appointment is
    // the encounter (decision D3). Layered on top of the existing consultation
    // save flow — legacy endpoints are untouched.
    // ─────────────────────────────────────────────────────────────────────

    // Encounter meta + check-in (P3-T2)
    Route::post ('/appointments/{id}/encounter/meta',        [ClcEncounterController::class, 'updateMeta'])->name('clinic.appointments.encounter.meta');
    Route::post ('/appointments/{id}/encounter/check-in',    [ClcEncounterController::class, 'checkIn'])->name('clinic.appointments.encounter.check-in');

    // Encounter diagnoses (P3-T2) — assessment-area CRUD + add-to-problem-list
    Route::get   ('/appointments/{id}/diagnoses',            [ClcEncounterController::class, 'listDiagnoses'])->name('clinic.appointments.diagnoses.list');
    Route::post  ('/appointments/{id}/diagnoses',            [ClcEncounterController::class, 'storeDiagnosis'])->name('clinic.appointments.diagnoses.store');
    Route::post  ('/appointments/diagnoses/{diagnosisId}/update',        [ClcEncounterController::class, 'updateDiagnosis'])->name('clinic.appointments.diagnoses.update');
    Route::delete('/appointments/diagnoses/{diagnosisId}',   [ClcEncounterController::class, 'destroyDiagnosis'])->name('clinic.appointments.diagnoses.destroy');
    Route::post  ('/appointments/diagnoses/{diagnosisId}/to-problem-list', [ClcEncounterController::class, 'addDiagnosisToProblemList'])->name('clinic.appointments.diagnoses.to-problem-list');

    // Clinical notes: sign/lock + amendments + typed notes (P3-T3)
    Route::post ('/appointments/{id}/note/sign',             [ClcEncounterController::class, 'signNote'])->name('clinic.appointments.note.sign');
    Route::post ('/appointments/{id}/note/amend',            [ClcEncounterController::class, 'amendNote'])->name('clinic.appointments.note.amend');
    Route::get  ('/appointments/{id}/note/amendments',       [ClcEncounterController::class, 'listAmendments'])->name('clinic.appointments.note.amendments');
    Route::post ('/appointments/{id}/typed-note',            [ClcEncounterController::class, 'storeTypedNote'])->name('clinic.appointments.typed-note.store');

    // Voice dictation → AiCore transcriber (P3-T3, graceful when absent)
    Route::post ('/appointments/{id}/dictate',              [ClcVitalsController::class, 'dictate'])->name('clinic.appointments.dictate');

    // Vitals: dual-write record + trend view (P3-T4)
    Route::post ('/appointments/{id}/vitals',                [ClcVitalsController::class, 'store'])->name('clinic.appointments.vitals.store');
    Route::get  ('/patients/{id}/vitals-trends',            [ClcVitalsController::class, 'trends'])->name('clinic.patients.vitals-trends');

    // ─────────────────────────────────────────────────────────────────────
    // P3 Rx/orders (SIFA P3-T5 prescriptions upgrade + P3-T6 unified orders).
    // Additive on top of the existing Rx + imaging/lab flows — legacy routes
    // above are untouched. All business-scoped + permission-gated.
    // ─────────────────────────────────────────────────────────────────────

    // Prescriptions upgrade (P3-T5): deterministic safety dry-run + refill.
    Route::post('/prescriptions/safety-check',                    [ClcPrescriptionController::class, 'safetyCheck'])->name('clinic.prescriptions.safety-check');
    Route::post('/prescriptions/items/{itemId}/refill',           [ClcPrescriptionController::class, 'refillItem'])->name('clinic.prescriptions.refill');

    // Unified orders (P3-T6): index + list + placement + view/verify + print.
    Route::get   ('/orders',                     [ClcOrderController::class, 'index'])->name('clinic.orders.index');
    Route::get   ('/orders/list',                [ClcOrderController::class, 'list'])->name('clinic.orders.list');
    Route::post  ('/orders',                     [ClcOrderController::class, 'store'])->name('clinic.orders.store');
    Route::get   ('/orders/{id}',                [ClcOrderController::class, 'show'])->where('id', '[0-9]+')->name('clinic.orders.show');
    Route::get   ('/orders/{id}/print',          [ClcOrderController::class, 'print'])->where('id', '[0-9]+')->name('clinic.orders.print');
    Route::post  ('/orders/{id}/verify',         [ClcOrderController::class, 'verify'])->where('id', '[0-9]+')->name('clinic.orders.verify');
    Route::post  ('/orders/items/{itemId}/update', [ClcOrderController::class, 'updateItem'])->name('clinic.orders.items.update');

    // ─────────────────────────────────────────────────────────────────────
    // P3 scheduling (SIFA P3-T7 scheduling upgrade). Schedule exceptions,
    // waitlist and today's-queue flow board — all business-scoped and
    // permission-gated. The pattern-column fields on clc_doctor_schedules and
    // the booking-source select reuse the existing doctor-schedule + appointment
    // endpoints above; only the genuinely new surfaces get routes here.
    // ─────────────────────────────────────────────────────────────────────

    // Schedule exceptions (clinic.schedule.manage_exceptions) — per-doctor AJAX
    Route::get   ('/doctors/{id}/schedule-exceptions',  [ClcScheduleExceptionController::class, 'list'])->name('clinic.schedule-exceptions.list');
    Route::post  ('/doctors/{id}/schedule-exceptions',  [ClcScheduleExceptionController::class, 'store'])->name('clinic.schedule-exceptions.store');
    Route::delete('/doctors/schedule-exceptions/{id}',  [ClcScheduleExceptionController::class, 'destroy'])->name('clinic.schedule-exceptions.destroy');

    // Waitlist (clinic.waitlist.manage)
    Route::get   ('/waitlist',              [ClcWaitlistController::class, 'index'])->name('clinic.waitlist.index');
    Route::get   ('/waitlist/list',         [ClcWaitlistController::class, 'list'])->name('clinic.waitlist.list');
    Route::post  ('/waitlist',              [ClcWaitlistController::class, 'store'])->name('clinic.waitlist.store');
    Route::post  ('/waitlist/{id}/cancel',  [ClcWaitlistController::class, 'cancel'])->where('id', '[0-9]+')->name('clinic.waitlist.cancel');
    Route::get   ('/waitlist/{id}/book-now', [ClcWaitlistController::class, 'bookNow'])->where('id', '[0-9]+')->name('clinic.waitlist.book-now');

    // Today's queue (clinic.queue.view)
    Route::get   ('/queue',        [ClcQueueController::class, 'index'])->name('clinic.queue.index');
    Route::get   ('/queue/board',  [ClcQueueController::class, 'board'])->name('clinic.queue.board');

    // ─────────────────────────────────────────────────────────────────────
    // P4 pharmacy/referrals (SIFA P4-T3 pharmacy dispensing + P4-T6 referrals).
    // Additive on top of the existing Rx flow. Dispensing is a CLINICAL act —
    // no ERP stock is decremented here; MedBilling's capture→bill sell does that
    // (no double deduction). All business-scoped + permission-gated.
    // ─────────────────────────────────────────────────────────────────────

    // Pharmacy dispense queue (clinic.rx.dispense)
    Route::get ('/pharmacy',                      [ClcPharmacyController::class, 'index'])->name('clinic.pharmacy.index');
    Route::get ('/pharmacy/list',                 [ClcPharmacyController::class, 'list'])->name('clinic.pharmacy.list');
    Route::get ('/pharmacy/{prescriptionId}/items', [ClcPharmacyController::class, 'queueItems'])->where('prescriptionId', '[0-9]+')->name('clinic.pharmacy.items');
    // Per-item dispense options + action (shared by the pharmacy queue AND the Rx show view).
    Route::get ('/prescriptions/items/{itemId}/dispense-options', [ClcPharmacyController::class, 'dispenseOptions'])->name('clinic.pharmacy.dispense-options');
    Route::post('/prescriptions/items/{itemId}/dispense',         [ClcPharmacyController::class, 'dispenseItem'])->name('clinic.pharmacy.dispense');

    // Referrals (clinic.referral.manage)
    Route::get   ('/referrals',                  [ClcReferralController::class, 'index'])->name('clinic.referrals.index');
    Route::get   ('/referrals/list',             [ClcReferralController::class, 'list'])->name('clinic.referrals.list');
    Route::get   ('/referrals/prefill',          [ClcReferralController::class, 'prefill'])->name('clinic.referrals.prefill');
    Route::post  ('/referrals',                  [ClcReferralController::class, 'store'])->name('clinic.referrals.store');
    Route::get   ('/referrals/{id}',             [ClcReferralController::class, 'show'])->where('id', '[0-9]+')->name('clinic.referrals.show');
    Route::get   ('/referrals/{id}/print',       [ClcReferralController::class, 'print'])->where('id', '[0-9]+')->name('clinic.referrals.print');
    Route::post  ('/referrals/{id}/transition',  [ClcReferralController::class, 'transition'])->where('id', '[0-9]+')->name('clinic.referrals.transition');
    Route::delete('/referrals/{id}',             [ClcReferralController::class, 'destroy'])->where('id', '[0-9]+')->name('clinic.referrals.destroy');

    // ─────────────────────────────────────────────────────────────────────
    // P5 radiology (SIFA P5-T1 imaging reports + modality worklist, P5-T5
    // diagnostic-center modalities as data). Additive on top of the existing
    // imaging worklist/upload flow above — legacy routes are untouched. All
    // business-scoped + permission-gated (clinic.imaging.report / .verify).
    // ─────────────────────────────────────────────────────────────────────

    // Modality worklist board (clinic.view_imaging)
    Route::get('/imaging/worklist', [ClcImagingWorklistController::class, 'index'])->name('clinic.imaging.worklist');

    // Structured imaging report editor (clinic.imaging.report / .verify)
    Route::get ('/imaging/requests/{requestId}/report',           [ClcImagingReportController::class, 'edit'])->where('requestId', '[0-9]+')->name('clinic.imaging.report.edit');
    Route::post('/imaging/requests/{requestId}/report',           [ClcImagingReportController::class, 'save'])->where('requestId', '[0-9]+')->name('clinic.imaging.report.save');
    Route::post('/imaging/requests/{requestId}/report/finalise',  [ClcImagingReportController::class, 'finalise'])->where('requestId', '[0-9]+')->name('clinic.imaging.report.finalise');
    Route::post('/imaging/requests/{requestId}/report/amend',     [ClcImagingReportController::class, 'amend'])->where('requestId', '[0-9]+')->name('clinic.imaging.report.amend');
});
