<?php

declare(strict_types=1);

/**
 * DentalCare v0.7.9.2 clinical workflow stability helpers.
 *
 * These helpers keep the active encounter/patient context explicit and record
 * the Dentist's assistant-or-none decision as a first-class workflow state.
 */

function clinical_flow_stability_schema_ready(): bool
{
    try {
        foreach (['assistant_decision','assistant_decided_by','assistant_decided_at'] as $column) {
            if (!schema_column_exists(table('clinical_encounters'), $column)) return false;
        }
        return true;
    } catch (Throwable) {
        return false;
    }
}

function clinical_assistant_decision(array $encounter): string
{
    $decision = strtolower(trim((string)($encounter['assistant_decision'] ?? '')));
    if (in_array($decision, ['assigned','none'], true)) return $decision;
    if ((int)($encounter['assistant_user_id'] ?? 0) > 0) return 'assigned';
    return '';
}

function clinical_assistant_decision_complete(array $encounter): bool
{
    return in_array(clinical_assistant_decision($encounter), ['assigned','none'], true);
}

function clinical_context_activate(array $encounter): void
{
    $encounterId = (int)($encounter['id'] ?? 0);
    $patientId = (int)($encounter['patient_id'] ?? 0);
    if ($encounterId < 1 || $patientId < 1) return;
    $_SESSION['dental_active_clinical_context'] = [
        'encounter_id' => $encounterId,
        'patient_id' => $patientId,
        'queue_entry_id' => (int)($encounter['queue_entry_id'] ?? 0),
        'appointment_id' => (int)($encounter['appointment_id'] ?? 0),
        'patient_no' => trim((string)($encounter['patient_no'] ?? '')),
        'patient_name' => function_exists('patient_full_name') ? patient_full_name($encounter) : trim((string)($encounter['first_name'] ?? '') . ' ' . (string)($encounter['last_name'] ?? '')),
        'activated_at' => time(),
    ];
}

function clinical_context_current(): ?array
{
    $context = $_SESSION['dental_active_clinical_context'] ?? null;
    if (!is_array($context)) return null;
    if ((int)($context['encounter_id'] ?? 0) < 1 || (int)($context['patient_id'] ?? 0) < 1) return null;
    return $context;
}

function clinical_context_clear(): void
{
    unset($_SESSION['dental_active_clinical_context']);
}

function clinical_context_url(string $url, array $encounter): string
{
    $encounterId = (int)($encounter['id'] ?? 0);
    $patientId = (int)($encounter['patient_id'] ?? 0);
    if ($encounterId < 1 || $patientId < 1) return $url;
    $separator = str_contains($url, '?') ? '&' : '?';
    return $url . $separator . 'encounter_id=' . $encounterId . '&patient_id=' . $patientId;
}

function clinical_context_return_url(array $encounter, string $fallback = 'clinical_workspace.php'): string
{
    $encounterId = (int)($encounter['id'] ?? 0);
    return $encounterId > 0 ? 'clinical_workspace.php?encounter_id=' . $encounterId : $fallback;
}
