<?php
$category = 'CHIEF_COMPLAINT';
$endPoint = 'upsertNoteSingleton';

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) {
    $problemPoints = Point::getPointsOfCategory($patient, 'PROBLEM');
    $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 {{!!$segment ? 'visit-moe' : 'moe'}} close-on-save close-on-cancel class="d-block">
    <form show url="/api/visitPoint/<?= $endPoint ?>" class="mcp-theme-1"
      {{!$segment ? 'hook=onHxPopupClosure' : ''}}>
        @if(!!@$segment)
            <input type="hidden" name="segmentUid" value="<?= $segment->uid ?>">
        @else
            <input type="hidden" name="segmentUid" value="<?= $note->coreSegment->uid ?>">
        @endif
        <input type="hidden" name="category" value="<?= $category ?>">
        <input type="hidden" name="data">
        <div note-rte
             class="form-group mb-2 border-left border-right rte-holder"
             data-field-name="free_text"
        ><?= $parsed && @$parsed->free_text ? $parsed->free_text : '' ?></div>
        <div class="my-2">
            <button submit class="btn btn-sm btn-primary mr-2"><i class="fa fa-save"></i></button>
            <div class="d-inline-flex align-self-stretch align-items-center">
                <span class="autosave-indicator saving text-sm text-secondary">Saving changes &hellip;</span>
                <span class="autosave-indicator saved text-sm text-secondary">
                    <i class="fa fa-check"></i>
                    Saved
                </span>
            </div>
        </div>
    </form>
</div>
