<?php

declare(strict_types=1);

function help_support_schema_ready(): bool
{
    return function_exists('support_request_schema_ready') && support_request_schema_ready();
}

function help_support_categories(): array
{
    return [
        'workflow' => 'Workflow or task question',
        'access' => 'Access or permission',
        'patient_flow' => 'Appointment, queue, or patient flow',
        'clinical' => 'Clinical workspace or record',
        'billing' => 'Billing, payment, or insurance',
        'inventory' => 'Inventory or sterilization',
        'reporting' => 'Report, print, or export',
        'technical' => 'Technical error or page failure',
        'account' => 'Account, password, or profile',
        'other' => 'Other support request',
    ];
}

function help_support_route_catalog(): array
{
    return [
        'dashboard' => [
            'title' => 'Dashboard',
            'summary' => 'Review work that needs attention today and open the correct operational module.',
            'actions' => ['Start with priority tasks that have a non-zero count', 'Open the relevant record instead of resolving work from summary cards', 'Use the role guide to confirm what belongs to this Task View'],
            'tips' => ['Counts update from the current role and branch scope', 'Task View changes what is displayed; it does not change the signed-in identity'],
        ],
        'patients' => [
            'title' => 'Patient records',
            'summary' => 'Find, register, review, and maintain the patient information allowed for the active role.',
            'actions' => ['Search before creating a new patient to prevent duplicates', 'Confirm identity before changing demographics', 'Use the patient timeline for encounter-specific history'],
            'tips' => ['Clinical, financial, and portal data remain role restricted', 'Use the active-treatment return bar when working with a patient already in treatment'],
        ],
        'appointment_requests' => [
            'title' => 'Appointment requests',
            'summary' => 'Review public requests, verify patient identity, select an available provider, and convert approved requests into appointments.',
            'actions' => ['Check for an existing patient and duplicate request', 'Confirm service, branch, date, and provider eligibility', 'Record contact or rescheduling notes before closing the request'],
        ],
        'portal_requests' => [
            'title' => 'Patient portal requests',
            'summary' => 'Review patient-submitted portal activity and route it to the responsible clinic workflow.',
            'actions' => ['Verify the patient and linked appointment', 'Respond or route the request', 'Keep clinical questions with the responsible Dentist'],
        ],
        'waitlist' => [
            'title' => 'Appointment waitlist',
            'summary' => 'Match waiting patients to suitable cancelled or newly available appointment slots.',
            'actions' => ['Filter by service and preferred schedule', 'Contact the patient before assigning a released slot', 'Record the outcome if the patient declines or cannot be reached'],
        ],
        'appointments' => [
            'title' => 'Appointments',
            'summary' => 'Book and maintain patient appointments while respecting provider, chair, service, and branch availability.',
            'actions' => ['Use Month to review appointment volume by day', 'Select a day to open its detailed weekly schedule', 'Use only eligible providers and record reschedule or cancellation reasons'],
            'tips' => ['Month shows counts only; Week contains patient-level details', 'Queue progress updates appointment status automatically', 'Ctrl or Cmd + S saves supported forms'],
        ],
        'queue' => [
            'title' => 'Clinic queue',
            'summary' => 'Move each patient through check-in, calling, seating, treatment, Cashier, and completion in the correct order.',
            'actions' => ['Confirm the correct patient before every transition', 'Assign the responsible Dentist and chair before treatment', 'Use exception reasons for cancellations, no-shows, or unusual transitions'],
            'tips' => ['Queue views update automatically', 'Do not refresh while entering a transition note or clinical data'],
        ],
        'inhouse_checkups' => [
            'title' => 'In-house checkups',
            'summary' => 'Document non-Dentist clinic services using an accountable employee and the required shared resources.',
            'actions' => ['Confirm the service is configured as in-house', 'Assign the responsible employee', 'Escalate diagnostic concerns to a Dentist'],
        ],
        'visit_workflow' => [
            'title' => 'Patient journey',
            'summary' => 'Review the linked appointment, queue, encounter, billing, and completion state for one patient visit.',
            'actions' => ['Open the source record that is inconsistent', 'Use the Reconciliation Center for controlled repairs', 'Do not overwrite clinical or financial history to make statuses appear correct'],
        ],
        'visit_exceptions' => [
            'title' => 'Reconciliation Center',
            'summary' => 'Detect and resolve contradictions between patient flow, clinical care, billing, approvals, and inventory.',
            'actions' => ['Start with Critical issues', 'Open the underlying record before applying a repair', 'Assign or dismiss an exception only with a documented reason'],
            'tips' => ['Approval decisions remain in their original module', 'Resolution actions are audited'],
        ],
        'doctor_treatment' => [
            'title' => 'Dentist treatment dashboard',
            'summary' => 'Manage the Dentist’s current chairside patients and return directly to the active encounter.',
            'actions' => ['Open the current active patient first', 'Assign the Dental Assistant for the encounter', 'Resume the same encounter after reviewing patient data or imaging'],
            'tips' => ['Only one active treatment should exist for a Dentist at a time', 'The active-treatment return bar remains available across clinical pages'],
        ],
        'clinical_day' => [
            'title' => 'Clinical day',
            'summary' => 'Review today’s clinical workload, treatment status, and incomplete records for the selected Dentist.',
            'actions' => ['Prioritize seated and in-treatment patients', 'Complete overdue drafts', 'Review treatment and follow-up handoffs before leaving'],
        ],
        'clinical' => [
            'title' => 'Clinical encounters',
            'summary' => 'Review encounter drafts, pending Dentist verification, finalized records, and patient-specific clinical history.',
            'actions' => ['Open the encounter linked to the actual visit', 'Finish drafts under the responsible clinical identity', 'Never create a second encounter to bypass an incomplete one'],
        ],
        'clinical_workspace' => [
            'title' => 'Active treatment workspace',
            'summary' => 'Review, assess, treat, and close the current patient encounter without losing treatment context.',
            'actions' => ['Complete intake and medical-alert review', 'Record examination, charting, diagnosis, and performed treatment', 'Verify delegated assistant entries before finalization', 'Complete instructions, follow-up, and billing handoff'],
            'tips' => ['The Dentist remains the responsible clinician', 'Assistant-entered procedures require explicit Dentist verification'],
        ],
        'clinical_tasks' => [
            'title' => 'Clinical tasks',
            'summary' => 'Route a specific procedure to a qualified Dentist without transferring ownership of the full treatment plan.',
            'actions' => ['Review the exact procedure and patient context', 'Accept only work covered by current credentials and privileges', 'Close the task after the delegated procedure is documented'],
        ],
        'odontogram' => [
            'title' => 'Odontogram and tooth findings',
            'summary' => 'Record tooth-specific findings, surfaces, status, and treatment relationships for the selected encounter.',
            'actions' => ['Confirm the tooth and surface before saving', 'Separate findings from completed procedures', 'Link treatment-plan items to the correct finding'],
        ],
        'periodontal' => [
            'title' => 'Periodontal charting',
            'summary' => 'Record periodontal measurements and findings under the selected patient encounter.',
            'actions' => ['Confirm tooth/site orientation', 'Complete measurements consistently', 'Save under the responsible clinical encounter'],
        ],
        'treatment' => [
            'title' => 'Treatment plans',
            'summary' => 'Create, approve, schedule, and track patient treatment items without confusing planned and performed work.',
            'actions' => ['Record clinical rationale and affected tooth/site', 'Confirm patient acceptance', 'Mark performed work from the active encounter rather than directly from the plan'],
        ],
        'prescriptions' => [
            'title' => 'Prescriptions',
            'summary' => 'Create and review prescriptions issued by the authenticated responsible Dentist.',
            'actions' => ['Check allergies and current medication history', 'Record dosage, frequency, route, and duration', 'Cancel or replace prescriptions without deleting history'],
        ],
        'documents' => [
            'title' => 'Clinical documents and imaging',
            'summary' => 'Upload and review protected clinical files linked to the correct patient and encounter.',
            'actions' => ['Choose the correct document type', 'Link imaging to the relevant encounter', 'Use descriptive notes without exposing files publicly'],
        ],
        'consents' => [
            'title' => 'Consents',
            'summary' => 'Prepare, capture, and verify informed consent for the correct patient and procedure.',
            'actions' => ['Use the consent applicable to the planned treatment', 'Confirm signer identity and relationship', 'Do not treat an unsigned consent as completed'],
        ],
        'referrals' => [
            'title' => 'Referrals',
            'summary' => 'Document referrals, destination providers, clinical reasons, and follow-through.',
            'actions' => ['State the clinical reason and urgency', 'Attach relevant records only when authorized', 'Track whether the patient completed the referral'],
        ],
        'laboratory' => [
            'title' => 'Laboratory cases',
            'summary' => 'Track laboratory work, due dates, case status, delivery, and patient linkage.',
            'actions' => ['Link the case to the correct patient and Dentist', 'Record dispatch and expected return', 'Escalate overdue or incorrect work'],
        ],
        'billing' => [
            'title' => 'Billing and Cashier',
            'summary' => 'Verify finalized charges, receive payment, issue receipts, and keep the patient transaction focused until completed or cancelled.',
            'actions' => ['Select the patient from the Cashier queue', 'Verify the procedure breakdown and approved adjustments', 'Enter the digital reference for card or electronic payments', 'Complete or cancel the focused transaction before opening another patient'],
        ],
        'insurance' => [
            'title' => 'Insurance and HMO',
            'summary' => 'Record payor coverage, claim-related financial information, and authorized patient responsibility.',
            'actions' => ['Verify the payor and coverage reference', 'Separate clinic charges from approved coverage', 'Keep diagnosis and clinical finalization with the Dentist'],
        ],
        'inventory' => [
            'title' => 'Inventory operations',
            'summary' => 'Maintain item balances, lots, movement documents, treatment consumption, transfers, returns, and controlled write-offs.',
            'actions' => ['Choose the correct transaction workflow', 'Use FEFO lots and confirm available quantity', 'Link treatment consumption to the active encounter and performed procedure', 'Use original-issue linkage for returns'],
        ],
        'sterilization' => [
            'title' => 'Sterilization',
            'summary' => 'Record instrument loads, cycles, release checks, and accountable staff handling.',
            'actions' => ['Identify the load and instruments', 'Record cycle parameters and result', 'Release only after the required verification'],
        ],
        'reports' => [
            'title' => 'Reports',
            'summary' => 'Review authorized clinic, clinical, financial, and inventory summaries for the active role and branch.',
            'actions' => ['Choose the correct date and branch scope', 'Confirm totals against source records', 'Export only information authorized for the current role'],
        ],
        'print_center' => [
            'title' => 'Records and printing',
            'summary' => 'Print authorized patient, clinical, financial, appointment, and operational records with an audit reason.',
            'actions' => ['Select the correct document and patient', 'Use the requested date or encounter scope', 'Confirm sensitive sections are allowed for the current role'],
        ],
        'administration' => [
            'title' => 'Administration Center',
            'summary' => 'Open configuration, staffing, schedules, communication, and operational-control modules.',
            'actions' => ['Use the dedicated module for each change', 'Review critical operations and reconciliation issues', 'Keep clinical signing with the authenticated Dentist'],
        ],
        'staff' => [
            'title' => 'Staff and Dentists',
            'summary' => 'Create and manage attributable staff accounts, roles, branch assignments, and credential-related profiles.',
            'actions' => ['Use one account per person', 'Correct invitation email before activation', 'Deactivate used accounts instead of deleting history'],
        ],
        'doctor_schedule' => [
            'title' => 'Doctor schedule',
            'summary' => 'Maintain published provider availability, leave, exceptions, and affected future appointments.',
            'actions' => ['Build recurring availability', 'Submit or approve schedule exceptions', 'Review patients affected by unavailable time'],
        ],
        'availability' => [
            'title' => 'Doctor availability',
            'summary' => 'Maintain the signed-in Dentist’s working hours and schedule exceptions.',
            'actions' => ['Confirm branch hours first', 'Publish only actual availability', 'Record leave or blocked time with the correct date and reason'],
        ],
        'settings' => [
            'title' => 'Website content',
            'summary' => 'Maintain public clinic information, contact details, and patient-facing website content.',
            'actions' => ['Use current clinic contact details', 'Review the public page after saving', 'Do not publish confidential internal information'],
        ],
        'system_setup' => [
            'title' => 'Superuser settings',
            'summary' => 'Apply updates, review environment health, manage permissions, backups, and protected system configuration.',
            'actions' => ['Back up before structural updates', 'Apply all pending updates in order', 'Review update history and environment checks after installation'],
        ],
    ];
}

function help_support_context(?string $route = null, ?string $role = null): array
{
    $route = task_route_key($route ?? dental_request_script());
    $role ??= active_role();
    $workspace = task_workspace($role);
    $catalog = help_support_route_catalog();
    $page = $catalog[$route] ?? [
        'title' => ucwords(str_replace('_', ' ', $route !== '' ? $route : 'Current page')),
        'summary' => 'Use this page only for work available to the active role and signed-in account.',
        'actions' => ['Confirm the selected patient, branch, date, or record before saving', 'Use the source workflow rather than bypassing a required step', 'Escalate work outside the active role'],
        'tips' => [],
    ];
    $page['route'] = $route;
    $page['role_label'] = (string)($workspace['label'] ?? role_profile($role)['name'] ?? 'Staff');
    $page['role_purpose'] = (string)($workspace['purpose'] ?? 'Complete authorized clinic work.');
    $page['role_limits'] = (string)($workspace['limits'] ?? 'Actions remain subject to the signed-in account permissions.');
    $page['role_steps'] = array_values((array)($workspace['steps'] ?? []));
    return $page;
}

function help_support_reference(int $id): string
{
    return 'SUP-' . str_pad((string)max(0, $id), 6, '0', STR_PAD_LEFT);
}

function help_support_status_label(string $status): string
{
    return match ($status) {
        'open' => 'Open',
        'in_review' => 'In review',
        'waiting_user' => 'Waiting for requester',
        'resolved' => 'Resolved',
        'closed' => 'Closed',
        default => ucwords(str_replace('_', ' ', $status)),
    };
}

function help_support_priority_label(string $priority): string
{
    return match ($priority) {
        'urgent' => 'Urgent',
        'high' => 'High',
        'normal' => 'Normal',
        'low' => 'Low',
        default => ucfirst($priority),
    };
}
