<?php

declare(strict_types=1);

/**
 * DentalCare v0.8.0.5 adaptive encounter safety rules.
 *
 * The care path changes documentation requirements, not professional judgment.
 * Allergy/medicine review, diagnosis, treatment attribution, consent, billing,
 * and final signature controls remain enforced for every path.
 */

function dental_adaptive_encounter_schema_ready(): bool
{
    return schema_column_exists(table('clinical_encounters'), 'care_path')
        && schema_column_exists(table('clinical_encounters'), 'vitals_skip_reason')
        && schema_column_exists(table('clinical_encounters'), 'care_path_decided_by')
        && schema_column_exists(table('clinical_encounters'), 'care_path_decided_at');
}

function dental_encounter_care_paths(): array
{
    return [
        'focused_dental' => [
            'label' => 'Focused dental treatment',
            'summary' => 'Teeth-first workflow for routine restorative, preventive, or localized dental care.',
            'default_target' => 'charting',
        ],
        'comprehensive' => [
            'label' => 'Comprehensive dental assessment',
            'summary' => 'Uses the completed first-seating safety review, then opens the full dental examination, charting, diagnosis, and treatment-planning workflow.',
            'default_target' => 'examination',
        ],
        'emergency' => [
            'label' => 'Emergency dental visit',
            'summary' => 'Uses the completed first-seating safety review and indicated measurements, then opens focused emergency dental examination, stabilization, and disposition.',
            'default_target' => 'examination',
        ],
        'follow_up' => [
            'label' => 'Follow-up / continuation',
            'summary' => 'Resume the relevant tooth, plan item, procedure, progress note, and outcome without repeating unchanged intake.',
            'default_target' => 'charting',
        ],
    ];
}

function dental_encounter_care_path(?string $value): string
{
    $value = trim((string) $value);
    return array_key_exists($value, dental_encounter_care_paths()) ? $value : 'comprehensive';
}

function dental_encounter_care_path_label(?string $value): string
{
    $path = dental_encounter_care_path($value);
    return (string) (dental_encounter_care_paths()[$path]['label'] ?? 'Comprehensive dental assessment');
}

function dental_encounter_default_care_path(array $context): string
{
    $existing = trim((string) ($context['care_path'] ?? ''));
    if ($existing !== '') return dental_encounter_care_path($existing);

    $haystack = mb_strtolower(trim(implode(' ', [
        (string) ($context['service_name'] ?? ''),
        (string) ($context['queue_service'] ?? ''),
        (string) ($context['reason'] ?? ''),
        (string) ($context['queue_reason'] ?? ''),
    ])));
    if ($haystack !== '' && preg_match('/emergency|trauma|swelling|uncontrolled pain|bleeding|avuls|fracture|abscess/u', $haystack)) return 'emergency';
    if ($haystack !== '' && preg_match('/follow[ -]?up|continuation|post[ -]?op|recall|review|suture removal|adjustment/u', $haystack)) return 'follow_up';
    return 'focused_dental';
}

function dental_encounter_condensed_intake(string $path): bool
{
    return in_array(dental_encounter_care_path($path), ['focused_dental', 'follow_up'], true);
}

function dental_encounter_requires_full_assessment(string $path): bool
{
    return in_array(dental_encounter_care_path($path), ['comprehensive', 'emergency'], true);
}

function dental_encounter_risk_text_is_high_risk(string $text): bool
{
    $text = mb_strtolower(trim($text));
    if ($text === '') return false;
    return (bool) preg_match('/extract|odontect|impacted|surg|implant|sedat|general\s+anesth|local\s+anesth|nerve\s+block|biopsy|incision|drainage|alveol|bone\s+graft|apico|flap|gingivect|pulpotom|pulpectom|root\s+canal|endodont|hemosta|bleeding/u', $text);
}

function dental_encounter_procedure_is_high_risk(array $procedureRows): bool
{
    $highRiskPrivileges = ['simple_extraction','surgical_extraction','implant_placement','periodontal_surgery','sedation','root_canal'];
    foreach ($procedureRows as $row) {
        $riskText = implode(' ', [
            (string) ($row['procedure_name'] ?? ''),
            (string) ($row['service_name_snapshot'] ?? ''),
            (string) ($row['service_code'] ?? ''),
            (string) ($row['notes'] ?? ''),
        ]);
        if (dental_encounter_risk_text_is_high_risk($riskText)) return true;
        $privilege = trim((string) ($row['required_privilege_code'] ?? ''));
        if ($privilege !== '' && in_array($privilege, $highRiskPrivileges, true)) return true;
    }
    return false;
}

function dental_encounter_usage_is_high_risk(array $usageRows): bool
{
    foreach ($usageRows as $row) {
        $type = strtolower(trim((string) ($row['usage_type'] ?? '')));
        $description = (string) ($row['description'] ?? $row['inventory_name'] ?? '');
        if (in_array($type, ['medication_administered','sedation','local_anesthetic','diagnostic_service'], true)) return true;
        if (dental_encounter_risk_text_is_high_risk($description)) return true;
    }
    return false;
}

function dental_encounter_requires_vitals(
    string $path,
    array $procedureRows = [],
    string $clinicalDisposition = '',
    bool $hasMedicalAlerts = false,
    array $usageRows = []
): bool {
    $path = dental_encounter_care_path($path);
    if ($path === 'emergency') return true;
    if ($hasMedicalAlerts) return true;
    if (in_array($clinicalDisposition, ['emergency_stabilization', 'medication_administered'], true)) return true;
    if (dental_encounter_procedure_is_high_risk($procedureRows)) return true;
    return dental_encounter_usage_is_high_risk($usageRows);
}

function dental_encounter_care_path_target(string $path): string
{
    $path = dental_encounter_care_path($path);
    return (string) (dental_encounter_care_paths()[$path]['default_target'] ?? 'intake');
}

function dental_encounter_vitals_row_has_measurement(array $row): bool
{
    foreach ([
        'blood_pressure_systolic','blood_pressure_diastolic','bp_repeat_systolic','bp_repeat_diastolic',
        'pulse_rate','temperature_c','respiratory_rate','oxygen_saturation','weight_kg','height_cm','blood_glucose'
    ] as $field) {
        if (array_key_exists($field, $row) && $row[$field] !== null && $row[$field] !== '') return true;
    }
    return false;
}
