<?php

use App\Models\Client;
use App\Models\Note;

/** @var Client $patient */
/** @var Note $note */

$canvasData = [
    "text" => '',
    "was_confirmed" => false,
    "note_uid" => '',
];

$patientDx = null;

if ($patient->canvas_data) {
    $canvasData = json_decode($patient->canvas_data, true);
    if (isset($canvasData["dx"])) {
        $patientDx = $canvasData["dx"];
    }
    if (isset($canvasData["cc_may21"])) {
        $canvasData = $canvasData["cc_may21"];
    }
}
$contentData = $canvasData;

if (!isset($contentData['note_uid']) || $contentData['note_uid'] !== @$note->uid) {
    $prefix = $patient->name_prefix ?: '';
    if (!$prefix) {
        $prefix = $patient->sex === 'M' ? 'Mr. ' : 'Ms. ';
    }

    $lines = [];
    $output = '';
    if ($patientDx && isset($patientDx['items'])) {
        $lines = $patientDx['items'];
        foreach ($lines as $i => $line) {
            if ($i > 0) {
                $output .= ($i < count($lines) - 2 ? ', ' : ($i === count($lines) - 2 ? ' and ' : ''));
            }
            $output .= $line['title'];
        }
    }

    $contentData['text'] =
        $prefix . $patient->name_first . ' ' . $patient->name_last . ' ' .
        'is a ' . $patient->age_in_years . ' y.o. ' . $patient->sex . ' ' .
        (!empty($output) ? (' with ' . $output) : '') . ' ' .
        'presenting today ' .
        (@$note ? (@$note->new_or_fu_or_na === 'NEW' ? 'to establish care' : 'for follow-up') : '') . '.';
    $contentData['was_confirmed'] = false;
    $contentData['note_uid'] = @$note->uid;
}
