<?php

declare(strict_types=1);

require DENTAL_ROOT . '/app/bootstrap.php';
require_login();
require_roles(['super_admin','clinic_admin','dentist','dental_assistant']);
require DENTAL_ROOT . '/app/layout.php';
require_once DENTAL_ROOT . '/app/transaction_integrity.php';
require_once DENTAL_ROOT . '/app/clinical_safety.php';
require_once DENTAL_ROOT . '/app/adaptive_encounter.php';

$pdo = db();
$user = current_user() ?? [];
$userId = (int)($user['id'] ?? 0);
$role = active_role();
$queueId = (int)($_GET['queue_id'] ?? $_POST['queue_id'] ?? 0);
if ($queueId < 1) {
    flash('warning', 'Select a seated patient from the clinic queue.');
    header('Location: queue.php');
    exit;
}

function dental_safety_queue_row(PDO $pdo, int $queueId, bool $forUpdate = false): ?array
{
    $sql = 'SELECT q.*,p.patient_no,p.first_name,p.middle_name,p.last_name,p.birth_date,p.medical_alerts,'
        . 'a.start_at appointment_start,a.status appointment_status '
        . 'FROM `' . table('queue_entries') . '` q '
        . 'JOIN `' . table('patients') . '` p ON p.id=q.patient_id '
        . 'LEFT JOIN `' . table('appointments') . '` a ON a.id=q.appointment_id '
        . 'WHERE q.id=? LIMIT 1' . ($forUpdate ? ' FOR UPDATE' : '');
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$queueId]);
    return $stmt->fetch() ?: null;
}

$queue = dental_safety_queue_row($pdo, $queueId);
if (!$queue) {
    flash('error', 'Queue entry not found.');
    header('Location: queue.php');
    exit;
}
require_record_branch_scope((int)($queue['branch_id'] ?? 0), (int)$queue['patient_id']);
if (($queue['provider_type'] ?? 'dentist') !== 'dentist') {
    flash('warning', 'This first-seating assessment is for Dentist-led dental visits.');
    header('Location: queue.php');
    exit;
}

$assessmentLocked = (string)($queue['status'] ?? '') === 'in_treatment';
$isAssignedDentist = active_role_is('dentist') && (int)($queue['dentist_user_id'] ?? 0) === $userId;
$isDentalAssistant = active_role_is('dental_assistant');
$canAssess = !$assessmentLocked && ($isAssignedDentist || $isDentalAssistant)
    && can('dental_safety.assess', ['dentist','dental_assistant']);
$canVerify = !$assessmentLocked && $isAssignedDentist
    && can('dental_safety.verify', ['dentist']);
$assessment = dental_safety_assessment_for_queue($queueId);
$history = dental_safety_latest_history($pdo, (int)$queue['patient_id']);
$intake = active_patient_intake((int)$queue['patient_id'], $queueId, (int)($queue['appointment_id'] ?? 0) ?: null) ?: [];
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        verify_csrf();
        if (!dental_safety_assessment_schema_ready()) throw new RuntimeException('Apply v0.9.1.0 before recording the first-seating assessment.');
        if (!$canAssess) throw new RuntimeException('Only the assigned Dentist or an authorized Dental Assistant can complete first seating.');

        $pdo->beginTransaction();
        $queue = dental_safety_queue_row($pdo, $queueId, true);
        if (!$queue) throw new RuntimeException('Queue entry not found.');
        if (!in_array((string)$queue['status'], ['seated','in_treatment'], true)) {
            throw new RuntimeException('Seat the patient before completing the dental treatment safety assessment.');
        }
        if ((string)$queue['status'] === 'in_treatment') {
            throw new RuntimeException('First seating is locked after treatment starts. Record newly reported information as a dated clinical addendum and apply it to the next treatment decision.');
        }

        $identityConfirmed = isset($_POST['identity_confirmed']);
        $allergiesReviewed = isset($_POST['allergies_reviewed']);
        $medicinesReviewed = isset($_POST['medicines_reviewed']);
        $conditionsReviewed = isset($_POST['conditions_reviewed']);
        $anesthesiaReviewed = isset($_POST['anesthesia_history_reviewed']);
        $bleedingReviewed = isset($_POST['bleeding_risk_reviewed']);
        $pregnancyReviewed = isset($_POST['pregnancy_relevance_reviewed']);
        if (!$identityConfirmed || !$allergiesReviewed || !$medicinesReviewed || !$conditionsReviewed || !$anesthesiaReviewed || !$bleedingReviewed || !$pregnancyReviewed) {
            throw new RuntimeException('Complete every dental-safety review confirmation before saving first seating.');
        }

        $changeStatus = (string)($_POST['change_status'] ?? '');
        if (!in_array($changeStatus, ['none','reported','unknown'], true)) throw new RuntimeException('Confirm whether the patient reported any change.');
        $changesSummary = trim((string)($_POST['changes_summary'] ?? ''));
        if ($changeStatus !== 'none' && mb_strlen($changesSummary) < 5) throw new RuntimeException('Describe the reported or uncertain change.');

        $latestHistory = dental_safety_latest_history($pdo, (int)$queue['patient_id']);
        $firstHistory = !$latestHistory;
        $allergies = trim((string)($_POST['allergies_value'] ?? ($latestHistory['allergies'] ?? '')));
        $medicines = trim((string)($_POST['medicines_value'] ?? ($latestHistory['medications'] ?? '')));
        $conditions = trim((string)($_POST['conditions_value'] ?? ($latestHistory['conditions'] ?? '')));
        $dentalHistory = trim((string)($_POST['dental_history_value'] ?? ($latestHistory['dental_history'] ?? '')));
        if ($firstHistory || $changeStatus === 'reported') {
            if ($allergies === '' || $medicines === '' || $conditions === '') {
                throw new RuntimeException('For a first visit or reported change, record allergies, current medicines, and health conditions relevant to dental care. Enter “None known” when applicable.');
            }
        }

        $bpIndication = (string)($_POST['bp_indication'] ?? 'not_required');
        $allowedIndications = ['not_required','dentist_request','local_anesthetic','invasive_procedure','sedation','existing_dental_alert'];
        if (!in_array($bpIndication, $allowedIndications, true)) $bpIndication = 'not_required';
        $recommendedCarePath = dental_encounter_default_care_path($queue);
        $measurementRequired = dental_safety_measurement_required($queue, $recommendedCarePath);
        if ($measurementRequired && $bpIndication === 'not_required') {
            throw new RuntimeException('This dental visit requires an indicated blood-pressure assessment at first seating.');
        }
        $bpSystolic = trim((string)($_POST['blood_pressure_systolic'] ?? ''));
        $bpDiastolic = trim((string)($_POST['blood_pressure_diastolic'] ?? ''));
        $pulseRate = trim((string)($_POST['pulse_rate'] ?? ''));
        if ($bpIndication !== 'not_required') {
            if ($bpSystolic === '' || $bpDiastolic === '' || !ctype_digit($bpSystolic) || !ctype_digit($bpDiastolic)) {
                throw new RuntimeException('Enter both blood-pressure values when a dental indication requires measurement.');
            }
        }
        $bpSys = $bpSystolic !== '' ? (int)$bpSystolic : null;
        $bpDia = $bpDiastolic !== '' ? (int)$bpDiastolic : null;
        $pulse = $pulseRate !== '' && ctype_digit($pulseRate) ? (int)$pulseRate : null;
        if ($bpSys !== null && ($bpSys < 40 || $bpSys > 300)) throw new RuntimeException('Systolic blood pressure is outside the supported entry range.');
        if ($bpDia !== null && ($bpDia < 20 || $bpDia > 200)) throw new RuntimeException('Diastolic blood pressure is outside the supported entry range.');
        if ($pulse !== null && ($pulse < 20 || $pulse > 250)) throw new RuntimeException('Pulse is outside the supported entry range.');

        $requestedOutcome = (string)($_POST['outcome'] ?? 'ready');
        if (!in_array($requestedOutcome, ['ready','needs_dentist_review','hold'], true)) $requestedOutcome = 'ready';
        $payload = [
            'change_status' => $changeStatus,
            'blood_pressure_systolic' => $bpSys,
            'blood_pressure_diastolic' => $bpDia,
        ];
        $needsDentistReview = dental_safety_assessment_requires_dentist_review($payload, $queue, $firstHistory);
        $status = $requestedOutcome;
        if ($role === 'dental_assistant' && $status === 'ready' && $needsDentistReview) $status = 'needs_dentist_review';
        if ($canVerify && $requestedOutcome === 'ready') $status = 'verified';
        if ($status === 'hold' && mb_strlen(trim((string)($_POST['outcome_note'] ?? ''))) < 10) {
            throw new RuntimeException('Document why dental treatment is on hold.');
        }
        if ($status === 'needs_dentist_review' && mb_strlen(trim((string)($_POST['outcome_note'] ?? ''))) < 5) {
            throw new RuntimeException('Document what the Dentist must review.');
        }
        $outcomeNote = trim((string)($_POST['outcome_note'] ?? '')) ?: null;

        $values = [
            (int)($queue['branch_id'] ?? 0) ?: null,
            (int)$queue['patient_id'],
            (int)($queue['appointment_id'] ?? 0) ?: null,
            $queueId,
            (int)($intake['id'] ?? 0) ?: null,
            $firstHistory ? 'first_visit' : 'returning_review',
            1,1,1,1,1,1,1,
            $changeStatus,
            $changesSummary ?: null,
            $allergies ?: null,
            $medicines ?: null,
            $conditions ?: null,
            $dentalHistory ?: null,
            $bpIndication,
            $bpSys,$bpDia,$pulse,
            trim((string)($_POST['measurement_notes'] ?? '')) ?: null,
            $status,$outcomeNote,$userId ?: null,
            in_array($status, ['verified','hold'], true) && $canVerify ? $userId : null,
            in_array($status, ['verified','hold'], true) && $canVerify ? date('Y-m-d H:i:s') : null,
        ];

        $sql = 'INSERT INTO `' . table('dental_safety_assessments') . '` '
            . '(branch_id,patient_id,appointment_id,queue_entry_id,intake_id,assessment_type,identity_confirmed,allergies_reviewed,medicines_reviewed,conditions_reviewed,anesthesia_history_reviewed,bleeding_risk_reviewed,pregnancy_relevance_reviewed,change_status,changes_summary,allergies_value,medicines_value,conditions_value,dental_history_value,bp_indication,blood_pressure_systolic,blood_pressure_diastolic,pulse_rate,measurement_notes,status,outcome_note,recorded_by,recorded_at,verified_by,verified_at,created_at,updated_at) '
            . 'VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),?,?,NOW(),NOW()) '
            . 'ON DUPLICATE KEY UPDATE intake_id=VALUES(intake_id),assessment_type=VALUES(assessment_type),identity_confirmed=VALUES(identity_confirmed),allergies_reviewed=VALUES(allergies_reviewed),medicines_reviewed=VALUES(medicines_reviewed),conditions_reviewed=VALUES(conditions_reviewed),anesthesia_history_reviewed=VALUES(anesthesia_history_reviewed),bleeding_risk_reviewed=VALUES(bleeding_risk_reviewed),pregnancy_relevance_reviewed=VALUES(pregnancy_relevance_reviewed),change_status=VALUES(change_status),changes_summary=VALUES(changes_summary),allergies_value=VALUES(allergies_value),medicines_value=VALUES(medicines_value),conditions_value=VALUES(conditions_value),dental_history_value=VALUES(dental_history_value),bp_indication=VALUES(bp_indication),blood_pressure_systolic=VALUES(blood_pressure_systolic),blood_pressure_diastolic=VALUES(blood_pressure_diastolic),pulse_rate=VALUES(pulse_rate),measurement_notes=VALUES(measurement_notes),status=VALUES(status),outcome_note=VALUES(outcome_note),recorded_by=VALUES(recorded_by),recorded_at=NOW(),verified_by=VALUES(verified_by),verified_at=VALUES(verified_at),updated_at=NOW()';
        $pdo->prepare($sql)->execute($values);
        $assessmentId = (int)$pdo->lastInsertId();
        if ($assessmentId < 1) {
            $assessmentId = (int)$pdo->query('SELECT id FROM `' . table('dental_safety_assessments') . '` WHERE queue_entry_id=' . $queueId . ' LIMIT 1')->fetchColumn();
        }

        $historyValues = ['allergies'=>$allergies,'medications'=>$medicines,'conditions'=>$conditions,'dental_history'=>$dentalHistory];
        if ($firstHistory || $changeStatus === 'reported') {
            if ($canVerify) {
                $historyId = integrity_insert_verified_medical_history($pdo, (int)$queue['patient_id'], $historyValues, $userId, 'Verified during first-seating dental treatment safety assessment for queue #' . $queueId . '.');
                clinical_safety_sync_verified_history($pdo, (int)$queue['patient_id'], $historyId, $historyValues, $userId);
                $pdo->prepare('UPDATE `' . table('patients') . '` SET medical_alerts=?,updated_at=NOW() WHERE id=?')->execute([integrity_medical_alert_summary($historyValues),(int)$queue['patient_id']]);
            } else {
                integrity_insert_reported_medical_history($pdo, (int)$queue['patient_id'], $historyValues, 'staff_recorded', $userId, 'Recorded at first seating for Dentist review. Queue #' . $queueId . '.');
            }
        }

        if ($bpSys !== null || $bpDia !== null || $pulse !== null) {
            $pdo->prepare('DELETE FROM `' . table('vital_signs') . '` WHERE dental_safety_assessment_id=?')->execute([$assessmentId]);
            $pdo->prepare('INSERT INTO `' . table('vital_signs') . '` (patient_id,branch_id,queue_entry_id,dental_safety_assessment_id,blood_pressure_systolic,blood_pressure_diastolic,pulse_rate,measurement_notes,recorded_by,recorded_at) VALUES (?,?,?,?,?,?,?,?,?,NOW())')
                ->execute([(int)$queue['patient_id'],(int)($queue['branch_id'] ?? 0) ?: null,$queueId,$assessmentId,$bpSys,$bpDia,$pulse,trim((string)($_POST['measurement_notes'] ?? '')) ?: null,$userId ?: null]);
        }

        if (!empty($intake['id'])) {
            $intakeStatus = in_array($status, ['ready','verified'], true) ? 'reviewed' : 'complete';
            $pdo->prepare('UPDATE `' . table('patient_intakes') . '` SET status=?,completed_by=?,completed_at=COALESCE(completed_at,NOW()),updated_at=NOW() WHERE id=?')
                ->execute([$intakeStatus,$userId ?: null,(int)$intake['id']]);
        }
        $pdo->prepare('UPDATE `' . table('queue_entries') . '` SET intake_completed_at=COALESCE(intake_completed_at,NOW()),updated_at=NOW() WHERE id=?')->execute([$queueId]);
        audit_required('dental_first_seating_assessment_saved','dental_safety_assessment',$assessmentId,[
            'queue_entry_id'=>$queueId,'patient_id'=>(int)$queue['patient_id'],'status'=>$status,'change_status'=>$changeStatus,'bp_indication'=>$bpIndication,
        ]);
        $pdo->commit();
        flash(in_array($status,['ready','verified'],true)?'success':'warning', dental_safety_assessment_status_label($status) . '.');
        header('Location: dental_safety_assessment.php?queue_id=' . $queueId);
        exit;
    } catch (Throwable $exception) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        $error = $exception->getMessage();
    }
}

$assessment = dental_safety_assessment_for_queue($queueId);
$history = dental_safety_latest_history($pdo, (int)$queue['patient_id']);
$status = (string)($assessment['status'] ?? 'missing');
$patientName = patient_full_name($queue);
$latestAllergies = (string)($assessment['allergies_value'] ?? $history['allergies'] ?? '');
$latestMedicines = (string)($assessment['medicines_value'] ?? $history['medications'] ?? '');
$latestConditions = (string)($assessment['conditions_value'] ?? $history['conditions'] ?? '');
$latestDentalHistory = (string)($assessment['dental_history_value'] ?? $history['dental_history'] ?? '');
$recommendedCarePath = dental_encounter_default_care_path($queue);
$measurementRequired = dental_safety_measurement_required($queue, $recommendedCarePath);
$defaultBpIndication = (string)($assessment['bp_indication'] ?? '');
if ($defaultBpIndication === '') {
    $defaultBpIndication = $measurementRequired
        ? (trim((string)($queue['medical_alerts'] ?? '')) !== '' ? 'existing_dental_alert' : ($recommendedCarePath === 'emergency' ? 'dentist_request' : 'invasive_procedure'))
        : 'not_required';
}

render_header('First-Seating Dental Safety');
?>
<section class="card">
  <div class="card-head"><div><span class="eyebrow">Before dental treatment</span><h2>First-seating dental treatment safety assessment</h2><p>Confirm only information that can affect dental treatment, dental prescribing, local anaesthesia or sedation, bleeding, radiography, healing, infection risk, or referral.</p></div><span class="badge <?=in_array($status,['ready','verified'],true)?'success':($status==='hold'?'danger':'warning')?>"><?=e(dental_safety_assessment_status_label($status))?></span></div>
  <div class="notice info"><strong><?=e($patientName)?></strong> · <?=e((string)$queue['patient_no'])?> · Queue <?=e((string)$queue['queue_no'])?> · <?=e((string)($queue['chair_name'] ?: 'Chair not assigned'))?></div>
  <?php if($error!==''):?><div class="flash error"><?=e($error)?></div><?php endif;?>
  <?php if($assessmentLocked):?><div class="notice info"><strong>First seating is closed.</strong> Treatment has started, so this assessment is read-only. Newly reported safety information belongs in a dated clinical addendum.</div><?php elseif(!$canAssess):?><div class="notice warning"><strong>Review-only access.</strong> Sign in or switch to the assigned Dentist or Dental Assistant role to record first seating.</div><?php endif;?>
</section>

<section class="card">
<form method="post" class="form-grid" data-preserve-scroll>
  <input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="queue_id" value="<?=$queueId?>">
  <div class="wide section-heading"><div><span class="step-number">1</span><div><h3>Identity and change review</h3><p>This review happens after seating and before treatment starts.</p></div></div></div>
  <label class="wide check-label"><input type="checkbox" name="identity_confirmed" value="1" <?=!empty($assessment['identity_confirmed'])?'checked':''?> <?=$canAssess?'':'disabled'?> required><span>Patient identity confirmed using name and patient number.</span></label>
  <label class="wide">Has anything changed since the latest dental-safety history?
    <select name="change_status" <?=$canAssess?'':'disabled'?> required>
      <option value="">Select</option><option value="none" <?=($assessment['change_status']??'')==='none'?'selected':''?>>No change reported</option><option value="reported" <?=($assessment['change_status']??'')==='reported'?'selected':''?>>Change reported</option><option value="unknown" <?=($assessment['change_status']??'')==='unknown'?'selected':''?>>Patient is unsure / clarification required</option>
    </select>
  </label>
  <label class="wide">Change summary<textarea name="changes_summary" <?=$canAssess?'':'readonly'?> placeholder="New allergy, medicine, pregnancy status relevant to care, bleeding risk, hospitalization, anaesthesia reaction, or other dental-treatment concern"><?=e((string)($assessment['changes_summary']??''))?></textarea></label>

  <div class="wide section-heading"><div><span class="step-number">2</span><div><h3>Dental-treatment safety history</h3><p>Enter “None known” when applicable. Do not use this page for general medical diagnosis or chronic-disease management.</p></div></div></div>
  <label class="wide check-label"><input type="checkbox" name="allergies_reviewed" value="1" <?=!empty($assessment['allergies_reviewed'])?'checked':''?> <?=$canAssess?'':'disabled'?> required><span>Medicine, latex, material, and anaesthetic allergies reviewed.</span></label>
  <label class="wide">Allergies relevant to dental care<textarea name="allergies_value" <?=$canAssess?'':'readonly'?>><?=e($latestAllergies)?></textarea></label>
  <label class="wide check-label"><input type="checkbox" name="medicines_reviewed" value="1" <?=!empty($assessment['medicines_reviewed'])?'checked':''?> <?=$canAssess?'':'disabled'?> required><span>Current medicines reviewed for bleeding, dental prescribing, anaesthesia, sedation, and healing risk.</span></label>
  <label class="wide">Current medicines relevant to dental care<textarea name="medicines_value" <?=$canAssess?'':'readonly'?>><?=e($latestMedicines)?></textarea></label>
  <label class="wide check-label"><input type="checkbox" name="conditions_reviewed" value="1" <?=!empty($assessment['conditions_reviewed'])?'checked':''?> <?=$canAssess?'':'disabled'?> required><span>Health conditions that can affect dental treatment reviewed.</span></label>
  <label class="wide">Conditions relevant to dental care<textarea name="conditions_value" <?=$canAssess?'':'readonly'?>><?=e($latestConditions)?></textarea></label>
  <label class="wide">Relevant dental and anaesthesia history<textarea name="dental_history_value" <?=$canAssess?'':'readonly'?>><?=e($latestDentalHistory)?></textarea></label>
  <label class="check-label"><input type="checkbox" name="anesthesia_history_reviewed" value="1" <?=!empty($assessment['anesthesia_history_reviewed'])?'checked':''?> <?=$canAssess?'':'disabled'?> required><span>Previous anaesthesia or sedation reaction reviewed.</span></label>
  <label class="check-label"><input type="checkbox" name="bleeding_risk_reviewed" value="1" <?=!empty($assessment['bleeding_risk_reviewed'])?'checked':''?> <?=$canAssess?'':'disabled'?> required><span>Bleeding risk and relevant medicines reviewed.</span></label>
  <label class="check-label"><input type="checkbox" name="pregnancy_relevance_reviewed" value="1" <?=!empty($assessment['pregnancy_relevance_reviewed'])?'checked':''?> <?=$canAssess?'':'disabled'?> required><span>Pregnancy relevance reviewed when applicable to radiography, prescribing, or procedure planning.</span></label>

  <div class="wide section-heading"><div><span class="step-number">3</span><div><h3>Indication-driven chairside measurement</h3><p>Blood pressure is not a universal service. Record it only when the dental visit or patient risk makes it relevant.</p></div></div></div>
  <?php if($measurementRequired):?><div class="notice warning wide"><strong>Measurement required before treatment.</strong> The planned dental visit or recorded safety alert requires a blood-pressure assessment at first seating.</div><?php else:?><div class="notice info wide">No chairside measurement is automatically required for this visit. The Dentist may still request one when clinically relevant.</div><?php endif;?>
  <label>Dental indication<select name="bp_indication" <?=$canAssess?'':'disabled'?>><?php foreach(['not_required'=>'Not required for this dental visit','dentist_request'=>'Requested by Dentist','local_anesthetic'=>'Local anaesthetic / vasoconstrictor review','invasive_procedure'=>'Invasive dental procedure','sedation'=>'Sedation or monitored care','existing_dental_alert'=>'Existing dental-safety alert'] as $code=>$label):?><option value="<?=e($code)?>" <?=$defaultBpIndication===$code?'selected':''?>><?=e($label)?></option><?php endforeach;?></select></label>
  <label>Systolic<input type="number" name="blood_pressure_systolic" min="40" max="300" value="<?=e((string)($assessment['blood_pressure_systolic']??''))?>" <?=$canAssess?'':'readonly'?>></label>
  <label>Diastolic<input type="number" name="blood_pressure_diastolic" min="20" max="200" value="<?=e((string)($assessment['blood_pressure_diastolic']??''))?>" <?=$canAssess?'':'readonly'?>></label>
  <label>Pulse<input type="number" name="pulse_rate" min="20" max="250" value="<?=e((string)($assessment['pulse_rate']??''))?>" <?=$canAssess?'':'readonly'?>></label>
  <label class="wide">Measurement note<textarea name="measurement_notes" <?=$canAssess?'':'readonly'?>><?=e((string)($assessment['measurement_notes']??''))?></textarea></label>

  <div class="wide section-heading"><div><span class="step-number">4</span><div><h3>Readiness decision</h3><p>Treatment cannot start until this assessment is ready or Dentist verified.</p></div></div></div>
  <label>Outcome<select name="outcome" <?=$canAssess?'':'disabled'?>>
    <option value="ready" <?=in_array($status,['ready','verified'],true)?'selected':''?>>Ready for Dentist</option>
    <option value="needs_dentist_review" <?=$status==='needs_dentist_review'?'selected':''?>>Dentist review required</option>
    <option value="hold" <?=$status==='hold'?'selected':''?>>Hold dental treatment</option>
  </select></label>
  <label class="wide">Outcome note<textarea name="outcome_note" <?=$canAssess?'':'readonly'?>><?=e((string)($assessment['outcome_note']??''))?></textarea></label>
  <?php if($canAssess):?><div class="button-row wide"><button class="btn primary" type="submit"><?= $canVerify ? 'Save and verify first seating' : 'Save first-seating assessment' ?></button><a class="btn ghost" href="queue.php">Back to queue</a><?php if(dental_safety_assessment_is_ready($assessment)&&active_role_is('dentist')):?><a class="btn primary" href="doctor_treatment.php#queue-entry-<?=$queueId?>">Continue to treatment start</a><?php endif;?></div><?php endif;?>
</form>
</section>
<?php render_footer(); ?>
