<?php
$category = 'CHIEF_COMPLAINT';

use App\Models\Point;

$point = Point::where('added_in_note_id', $segment->note->id)->where('category', $category)->orderBy('id', 'DESC')->first();
$parsed = null;
if ($point && !!@$point->data) {
    $parsed = json_decode($point->data);
}

if(!$parsed || !@$parsed->free_text) {
    
    list($problemPoints, $counts) = Point::getPointsOfCategoryExtended($patient, 'PROBLEM', $note);
    $problemNames = [];
    foreach ($problemPoints as $problemPoint) {
        if($problemPoint->relevanceToNote($note)) {
            $problemNames[] = $problemPoint->data->name;
        }
    }
    $problems = '';
    for($i = 0; $i < count($problemNames); $i++) {
        if($i > 0) {
            if($i === count($problemNames) - 1) {
                $problems .= " and ";
            }
            else {
                $problems .= ", ";
            }
        }
        $problems .= $problemNames[$i];
    }
    $defaultCC = "Patient {$patient->name_first} {$patient->name_last} " .
        "is a {$patient->age_in_years} year old" .
        ($patient->sex ? ($patient->sex === 'F' ? ' female' : ($patient->sex === 'M' ? ' male' : ' ' . $patient->sex)) : '') .
        ($problems ? " with a history of {$problems}" : "") .
        ($note->new_or_fu_or_na === 'NEW' ? ' presenting for establishing care' : ' presenting for follow-up') .
        ".";
    $parsed = json_decode(json_encode([
        "free_text" => $defaultCC
    ]));
    
}
?>
<div>
    <?php
    if (!!$parsed && @$parsed->free_text) {
        echo $parsed->free_text;
    }
    else {
        echo "-";
    }
    ?>
</div>

