<?php

use App\Models\Point;
use App\Models\Client;
use App\Models\Note;
use App\Models\Pro;

/** @var Client $patient */
/** @var Note $note */
/** @var Pro $pro */
/** @var $summaryView */

if(!@$problems || !@$counts) {
    list($problems, $counts) = Point::getPointsOfCategoryExtended($patient, 'PROBLEM', $note, !!@$summaryView);
}
if(!@$summaryView) {
    $ccSegment = $note->getSegmentByInternalName('chief_complaint');
    $ccSegment = $ccSegment ?? $note->getSegmentByInternalName('mc_cc');
    $ccSegment = $ccSegment ?? $note->getSegmentByInternalName('omega_cc');
    $favorites = $pro->favoritesByCategoryDecoded('problem');
    function isFavoriteProblem($_problem, $_favorites) {
        foreach($_favorites as $favorite) {
            if($favorite->data->name === $_problem->data->name) return $favorite->uid;
        }
        return false;
    }
}
?>

<div @if(!@$summaryView) class="mt-3 p-3 border-top" id="problems-center-{{$note->id}}" @else class="mt-2 pr-2" @endif>
    <div class="point-table-container">

        @if(!@$summaryView && $patient->core_note_id !== $note->id && $ccSegment)
        <div class="d-flex align-items-baseline mb-3">
            <div class="font-weight-bold font-size-14 text-secondary">Chief Complaint</div>
            <span class="mx-2 text-secondary">|</span>
            <a href="#" class="regenerate-cc mr-2">Regenerate</a>
            <?php
            $ccPoint = Point::where('added_in_note_id', $note->id)->where('category', 'CHIEF_COMPLAINT')->orderBy('id', 'DESC')->first();
            $parsed = null;
            if ($ccPoint && !!@$ccPoint->data) {
                $parsed = json_decode($ccPoint->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;
                    }
                }
                $ccProblems = '';
                for($i = 0; $i < count($problemNames); $i++) {
                    if($i > 0) {
                        if($i === count($problemNames) - 1) {
                            $ccProblems .= " and ";
                        }
                        else {
                            $ccProblems .= ", ";
                        }
                    }
                    $ccProblems .= $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)) : '') .
                    ($ccProblems ? " with a history of {$ccProblems}" : "") .
                    ($note->new_or_fu_or_na === 'NEW' ? ' presenting for establishing care' : ' presenting for follow-up') .
                    ".";
                $parsed = json_decode(json_encode([
                    "free_text" => $defaultCC
                ]));
            }
            ?>
            <div visit-moe class="d-inline-block flex-grow-1">
                <form show="" url="/api/visitPoint/upsertNoteSingleton" class="mcp-theme-1" id="frm-cc-regenerate">
                    <input type="hidden" name="segmentUid" value="{{$ccSegment->uid}}">
                    <input type="hidden" name="category" value="CHIEF_COMPLAINT">
                    <input type="hidden" name="data" value="">
                    <div note-rte slim-rte
                         class="form-group mb-0 border-left border-right rte-holder cc-generated"
                         data-field-name="free_text"
                    ><?= $parsed && @$parsed->free_text ? $parsed->free_text : '' ?></div>
                </form>
            </div>
        </div>
        @endif

        <table class="table table-sm table-bordered bg-white mb-2 point-table read">
            <?php $prevRowState = -1; ?>
            <?php
            $segment = $note->coreSegment; // getSegmentByInternalName('intake_allergies');
            // if(!$segment) $segment = $note->getSegmentByInternalName('allergies');
            // if(!$segment) $segment = $note->coreSegment;
            ?>
            <?php foreach($problems as $problem): ?>
            <?php $point = $problem; ?>
            @if(!@$summaryView)
                <?php $favoriteUid = isFavoriteProblem($problem, $favorites); ?>
            @endif
            @if($prevRowState !== $problem->state)
                @include('app.patient.wizard-partials.state-row-flat', ['point' => $problem])
            @endif
            <?php $prevRowState = $problem->state; ?>
            <?php $rel = $problem->note_point_uid; ?>
            <tr class="{{$rel ? 'relevant-to-visit' : ''}} point-row"
                data-uid="{{$problem->uid}}"
                data-name-base64="{{!!@($problem->data->name) ? base64_encode($problem->data->name) : ''}}"
                data-is-removed="{{$problem->is_removed ? 1 : 0}}"
                data-is-removed-due-to-entry-error="{{$problem->is_removed_due_to_entry_error ? 1 : 0}}">

                <td class="border-0 pl-0">
                    <div class="d-flex align-items-start">
                        @if($patient->core_note_id !== $note->id)
                            @include('app.patient.wizard-partials.relevance-column-optimized-flat', ['point' => $point])
                        @endif
                        <div class="{{$patient->core_note_id !== $note->id ? '' : 'pl-2'}}">
                            <div class="d-flex align-items-baseline">
                                <div> <!-- name + edit moe -->
                                    @if(!@$summaryView)
                                        <div moe huge relative>
                                            <a start show href="#" title="Edit" class="text-dark font-weight-bold">
                                                <?= !!@($problem->data->name) ? @($problem->data->name) : '-' ?>
                                                <?= !!@($problem->data->icd) ? '/&nbsp;' . @($problem->data->icd) : '' ?>
                                            </a>
                                            <form url="/api/visitPoint/updateTopLevel" no-auto-focus class="mcp-theme-1 frm-edit-problem">
                                                <input type="hidden" name="uid" value="<?= $problem->uid ?>">
                                                <input type="hidden" name="noteUid" value="<?= $note->uid ?>">
                                                <p class="mb-2"><b>Update Problem</b></p>

                                                <input type="hidden" name="data" value='{{json_encode($problem->data)}}'>

                                                @if($problem->added_in_note_id !== $note->id)

                                                    <div class="mb-2 bg-light p-2 border">
                                                        <p class="mb-1 font-weight-bold">
                                                            {{ @$problem->data->name }}
                                                            {{!!@($problem->data->icd) ? ' / ' . @($problem->data->icd) : ''}}
                                                        </p>
                                                        @if($patient->core_note_id !== $note->id)
                                                            <div class="text-secondary">This problem was added outside of this visit.
                                                                <a href="#" class="update-core-data ml-2">
                                                                    <i class="fa fa-edit on-hover-opaque"></i>
                                                                    Update
                                                                </a>
                                                            </div>
                                                        @endif
                                                    </div>

                                                @endif

                                                <div class="mb-2 {{$problem->added_in_note_id === $note->id ? '' : 'd-none'}}" if-core-data-edit-confirmed>

                                                    <input type="hidden" data-name="dxid" value="{{@$problem->data->dxid}}">
                                                    <input type="hidden" data-name="icd-type" value="{{@$problem->data->{'icd-type'} }}">

                                                    <div class="row mb-2">
                                                        <div class="col-8 pr-0">
                                                            <label class="text-sm mb-0 font-weight-bold">Problem</label>
                                                            <input type="text" class="form-control form-control-sm min-width-unset"
                                                                   data-name="name"
                                                                   value="{{@$problem->data->name}}"
                                                                   stag-suggest
                                                                   stag-suggest-ep="/fdb-dx-suggest-v2/json"
                                                                   stag-suggest-text-only>
                                                        </div>
                                                        <div class="col-4">
                                                            <label class="text-sm mb-0 font-weight-bold">ICD</label>
                                                            <input type="text"
                                                                   data-name="icd"
                                                                   class="form-control form-control-sm"
                                                                   value="{{@$problem->data->icd}}">
                                                        </div>
                                                    </div>

                                                </div>

                                                @include('app.patient.wizard-partials.common-fields-optimized', ['label' => 'problem', 'point' => $problem, 'addVerbPT' => 'Added', 'reviewLabel' => 'Subjective/HPI', 'apTerm' => 'assessment/plan'])

                                                <div class="mt-3 pt-2 d-flex align-items-center border-top">
                                                    <button type="submit" class="btn-save-problem btn btn-sm btn-primary mr-2">Save</button>
                                                    <button cancel class="btn btn-sm bg-light btn-default border">Cancel</button>
                                                </div>
                                            </form>
                                        </div>
                                    @else
                                        <?= !!@($problem->data->name) ? @($problem->data->name) : '-' ?>
                                        <?= !!@($problem->data->icd) ? '/&nbsp;' . @($problem->data->icd) : '' ?>
                                    @endif
                                </div>
                                @if(!@$summaryView)
                                    <div class="ml-3">
                                        <div moe>
                                            @if(!$favoriteUid)
                                                <form show url="/api/proFavorite/create">
                                                    <input type="hidden" name="proUid" value="{{$pro->uid}}">
                                                    <input type="hidden" name="category" value="problem">
                                                    <input type="hidden" data-name="dxid" value="{{@$problem->data->dxid}}">
                                                    <input type="hidden" data-name="icd" value="{{@$problem->data->icd}}">
                                                    <input type="hidden" data-name="icd-type" value="{{@$problem->data->{'icd-type'} }}">
                                                    <textarea class="d-none" name="data">{!! json_encode(["name" => @($problem->data->name), "dxid" => @($problem->data->dxid), "icd" => @($problem->data->icd), "icd-type" => @($problem->data->{'icd-type'})]) !!}</textarea>
                                                    <button submit class="outline-0 shadow-none border-0 bg-transparent p-0 text-secondary-light" title="Add to common">
                                                        <i class="fa fa-bookmark text-sm"></i>
                                                    </button>
                                                </form>
                                            @else
                                                <form show url="/api/proFavorite/remove">
                                                    <input type="hidden" name="uid" value="{{$favoriteUid}}">
                                                    <button submit class="outline-0 shadow-none border-0 bg-transparent p-0 text-info" title="Remove from common">
                                                        <i class="fa fa-bookmark text-sm"></i>
                                                    </button>
                                                </form>
                                            @endif
                                        </div>
                                    </div>
                                @endif
                                <div class="ml-3 d-inline-flex align-items-baseline text-dark"> <!-- meta info -->
                                    @if(!!@$problem->data->start_date)
                                        <div class="text-sm text-nowrap small text-left mr-2">Started <?= !!@($problem->data->start_date) ? friendly_date($problem->data->start_date) : '-' ?></div>
                                    @endif
                                    @if(!!@($problem->data->prescriber))
                                        <div class="text-sm text-left text-secondary mr-2">{{!!@$problem->data->start_date ? '' : 'Started'}} By: <?= !!@($problem->data->prescriber) ? @($problem->data->prescriber) : '-' ?></div>
                                    @endif
                                    @if(!!@$problem->removal_effective_date)
                                        <div class="text-sm text-nowrap small text-left text-left mr-2">Ended <?= !!@($problem->removal_effective_date) ? friendly_date($problem->removal_effective_date) : '-' ?></div>
                                    @endif
                                    @if(!!@($problem->removal_reason_memo))
                                        <div class="text-sm text-secondary">{{ !!@$problem->removal_effective_date ? '' : 'Ended' }} By: <?= !!@($problem->removal_reason_memo) ? @($problem->removal_reason_memo) : '-' ?></div>
                                    @endif
                                </div>
                            </div>
                            <div class="ml-3 text-dark">
                                <div class="mt-1">
                                    <div if-read-mode>
                                        <div class="">
                                            <div class="flex-grow-1">
                                                <span class="on-hover-opaque font-weight-bold mr-2 c-pointer upsert-rp-trigger font-underline">Subj</span>
                                                @if(!@$summaryView)
                                                    <div class="d-inline-flex align-items-baseline">
                                                        <?php
                                                        if($segment) {
                                                            include resource_path('views/app/patient/segment-templates/_child_review/edit-review-optimized-flat.php');
                                                        }
                                                        ?>
                                                        <a class="mr-2 view-review-log text-sm on-hover-opaque text-dark"
                                                           native target="_blank"
                                                           open-in-stag-popup
                                                           popup-style="stag-popup-md"
                                                           title="Subjective log<?= !!@($problem->data->name) ? ' for ' . @($problem->data->name) : '' ?>"
                                                           href="/point/review-log/<?= $problem->uid ?>?popupmode=1">
                                                            <i class="fa fa-history"></i>
                                                        </a>
                                                    </div>
                                                @endif
                                                <?php
                                                $point = $problem;
                                                include resource_path('views/app/patient/segment-templates/_child_review/last-review-optimized-flat.php');
                                                ?>
                                            </div>
                                        </div>
                                    </div>
                                    <div if-edit-mode>
                                        <?php
                                        if($segment) {
                                            include resource_path('views/app/patient/segment-templates/_child_review/edit-review-in-place-optimized.php');
                                        }
                                        ?>
                                    </div>
                                </div>
                                <div class="mt-1">
                                    <div if-read-mode>
                                        <div class="">
                                            <div class="flex-grow-1">
                                                <span class="on-hover-opaque font-weight-bold mr-2 c-pointer upsert-rp-trigger font-underline">Plan</span>
                                                @if(!@$summaryView)
                                                    <div class="d-inline-flex align-items-baseline">
                                                        <?php
                                                        if($segment) {
                                                            include resource_path('views/app/patient/segment-templates/_child_plan/edit-plan-optimized-flat.php');
                                                        }
                                                        ?>
                                                        <a class="mr-2 view-review-log text-sm on-hover-opaque text-dark"
                                                           native target="_blank"
                                                           open-in-stag-popup
                                                           popup-style="stag-popup-md"
                                                           title="Plan log<?= !!@($problem->data->name) ? ' for ' . @($problem->data->name) : '' ?>"
                                                           href="/point/plan-log/<?= $problem->uid ?>?popupmode=1">
                                                            <i class="fa fa-history"></i>
                                                        </a>
                                                    </div>
                                                @endif
                                                <?php
                                                include resource_path('views/app/patient/segment-templates/_child_plan/last-plan-optimized-flat.php');
                                                ?>
                                            </div>
                                        </div>
                                    </div>
                                    <div if-edit-mode>
                                        <?php
                                        if($segment) {
                                            include resource_path('views/app/patient/segment-templates/_child_plan/edit-plan-in-place-optimized-flat.php');
                                        }
                                        ?>
                                    </div>
                                </div>
                            </div>

                        </div>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
        </table>

        @if(!@$summaryView)
        <div class="d-flex align-items-center">
            <div class="mt-1 w-100 border p-3 bg-aliceblue border-info rounded">

                <div class="d-flex align-items-baseline mb-3" tab-links="">
                    <a class="tab-link-active" href="#" tab-link="add-single">Add Single</a>
                    <a class="" href="#" tab-link="add-multiple-pre-existing">Add Multiple Pre-existing</a>
                </div>
                <div class="cm-tab" tab-key="add-single">
                    <div class="row">
                        <div class="col-8">
                            <form action="/api/visitPoint/addTopLevel" class="mcp-theme-1 w-100" id="frm-add-problem" novalidate>
                                <input type="hidden" name="noteUid" value="<?= $note->uid ?>">
                                <input type="hidden" name="category" value="PROBLEM">
                                <input type="hidden" name="data">

                                <input type="hidden" data-name="dxid">
                                <input type="hidden" data-name="icd-type">

                                <input type="hidden" name="isRemovedDueToEntryError" value="0">

                                <div class="d-flex align-items-baseline mb-2">
                                    <b>Add Problem</b>
                                    @if(count($favorites))
                                        <div class="d-inline position-relative on-click-menu ml-4">
                                                <span class="text-primary c-pointer">
                                                    <i class="fa fa-bookmark text-info mr-1"></i> Common Problems <i class="ml-1 fa fa-caret-down"></i>
                                                </span>
                                            <div menu right class="bg-white border">
                                                @foreach($favorites as $favorite)
                                                    <a native target="_blank" href="#"
                                                       data-name="{{@($favorite->data->name)}}"
                                                       data-dxid="{{@($favorite->data->dxid)}}"
                                                       data-icd="{{@($favorite->data->icd)}}"
                                                       data-icd-type="{{@($favorite->data->{'icd-type'})}}"
                                                       class="px-2 py-1 d-block text-nowrap text-sm favorite-item">
                                                        {{$favorite->data->name}}
                                                    </a>
                                                @endforeach
                                            </div>
                                        </div>
                                    @endif
                                </div>
                                <div class="row mb-2">
                                    <div class="col-8 pr-0">
                                        <label class="text-sm mb-0 font-weight-bold">Name</label>
                                        <input type="text"
                                               data-name="name"
                                               class="form-control form-control-sm"
                                               stag-suggest
                                               stag-suggest-bottom-left
                                               stag-suggest-ep="/fdb-dx-suggest-v2/json"
                                               stag-suggest-text-only
                                               value="{{trim(request()->input('dx')) ? trim(request()->input('dx')) : ''}}"
                                               required>
                                    </div>
                                    <div class="col-4">
                                        <label class="text-sm mb-0 font-weight-bold">ICD</label>
                                        <input type="text"
                                               data-name="icd"
                                               class="form-control form-control-sm min-width-unset">
                                    </div>
                                </div>

                                <?php $point = null; ?>
                                @include('app.patient.wizard-partials.common-fields-optimized', ['label' => 'problem', 'addVerbPT' => 'Added', 'reviewLabel' => 'Subjective/HPI', 'apTerm' => 'assessment/plan'])

                                <div class="d-flex align-items-center">
                                    <button type="submit" class="btn btn-sm btn-primary mr-2">Save Problem</button>
                                    <button type="button" class="btn btn-sm btn-default border-secondary bg-white border mr-2" onclick="return closeStagPopup()">Close</button>
                                </div>
                            </form>
                        </div>
                        <div class="col-4 border-left">

                            <?php
                            $medications = \App\Models\Point::getPointsOfCategory($patient, "MEDICATION");
                            ?>
                            @if(count($medications))
                                <h6 class="my-0 font-weight-bold text-secondary mb-2">Active Medications</h6>
                                <div class="bg-light border px-2 pt-2 pb-1 mb-0">
                                    @foreach($medications as $medication)
                                        <div class="mb-1">
                                            <b><?= !!@($medication->data->name) ? @($medication->data->name) : '-' ?></b>
                                        </div>
                                    @endforeach
                                </div>
                                <hr class="my-3 m-neg-3">
                            @endif

                            <div class="fdb-dx-vigilance max-height-400px overflow-auto">

                            </div>
                        </div>
                    </div>
                </div>
                <div class="cm-tab d-none" tab-key="add-multiple-pre-existing">
                    @include('app.patient.wizard-partials.add-multiple-pre-existing', ['label' => 'problem', 'adder' => 'Diagnosed By'])
                </div>
            </div>
        </div>
        @endif
    </div>
</div>

@if(!@$summaryView)
<script>
    (function() {
        function init() {
            let parentSegment = $('#problems-center-{{$note->id}}');
            parentSegment.find('input[stag-suggest][data-name="name"]')
                .off('stag-suggest-selected')
                .on('stag-suggest-selected', (_e, _input, _data) => {
                    $(_input).closest('form').find('input[data-name="dxid"]').val(_data.dxid);
                    $(_input).closest('form').find('input[data-name="icd"]').val(_data.sub_text);
                    $(_input).attr('stag-suggest-selection', _input.val());

                    $('.fdb-dx-vigilance').html('<span class="text-secondary font-italic">Please wait ...</span>');
                    $.post('/fdb-dx-vigilance/{{$patient->uid}}', {
                        _token: '{{csrf_token()}}',
                        dxid: _data.dxid,
                        name: _input.val(),
                    }, _data => {
                        $('.fdb-dx-vigilance').html(_data);
                    });
                })
                .off('input.override paste.override cut.override')
                .on('input.override paste.override cut.override', function() {
                    let input = $(this);
                    if($.trim(input.val()) !== input.attr('stag-suggest-selection')) {
                        $(input).closest('form').find('input[data-name="dxid"]').val('');
                        $(input).closest('form').find('input[data-name="icd"]').val('');
                    }
                });

            @include('app.patient.wizard-partials.common-script', ['label' => 'problem', 'segment_part' => 'problems'])

            @if($patient->core_note_id !== $note->id)
            parentSegment.find('.regenerate-cc')
                .off('click.regenerate-cc')
                .on('click.regenerate-cc', function () {

                    showMask();

                    // refresh the cc
                    $.get('/note/generate-cc/{{$note->uid}}', _data => {
                        if(!hasResponseError(_data)) {
                            let quillInstance = $('#frm-cc-regenerate').find('.cc-generated').first().data('quillInstance');
                            quillInstance.root.innerHTML = $.trim($('<div/>').html(_data.data).text());
                        }
                    }, 'json')
                    .then(function() {
                        hideMask();
                    });

                    return false;
                });
            @endif

            initSegmentMoes($('#problems-center-{{$note->id}}'));
            __initRTEs(parentSegment.find('[note-rte]:not(.ql-container)'));

            @if(trim(request()->input('dx')))
                parentSegment.find('input[stag-suggest][data-name="name"]').focus().trigger('keydown')[0].scrollIntoView();
            @endif


            parentSegment.find('.favorite-item')
                .off('click.add-from-favorite')
                .on('click.add-from-favorite', function () {
                    $('#frm-add-problem').find('input[data-name="name"]').val($(this).attr('data-name'));
                    $('#frm-add-problem').find('input[data-name="dxid"]').val($(this).attr('data-dxid'));
                    $('#frm-add-problem').find('input[data-name="icd"]').val($(this).attr('data-icd')).removeAttr('readonly');
                    $('#frm-add-problem').find('input[data-name="icd-type"]').val($(this).attr('data-icd-type'));
                    $(this).closest('.on-click-menu').find('[menu]').hide();
                    return false;
                });

            parentSegment.find('.multi-favorite-item')
                .off('click.add-from-multi-favorite')
                .on('click.add-from-multi-favorite', function () {
                    let row = $(this).closest('tr');
                    row.find('input[key="name"]').val($(this).attr('data-name')).focus();
                    row.find('input[key="dxid"]').val($(this).attr('data-dxid'));
                    row.find('input[key="icd"]').val($(this).attr('data-icd'));
                    row.find('input[key="icd-type"]').val($(this).attr('data-icd-type'));
                    $(this).closest('.on-click-menu').find('[menu]').hide();
                    return false;
                });

            let mode = 'read';

            $('.button-container').remove();
            let buttonContainer = $('<div/>').addClass('button-container ml-4 mr-auto');
            let titleElem = $('#problems-center-{{$note->id}}').closest('.stag-popup').find('.stag-popup-title>span');
            titleElem.next().removeClass('ml-auto');
            titleElem.parent().addClass('align-items-center');

            // add button for "Edit Mode"
            $('.btn-toggle-edit-mode').remove();
            let button = $('<a href="#" native target="_blank" data-mode="read" ' +
                'class="btn-toggle-edit-mode btn btn-sm mr-2 btn-info text-white font-weight-bold shadow-none">Switch to Edit Mode</a>')
                .appendTo(buttonContainer);

            button
                .off('click.toggle-edit')
                .on('click.toggle-edit', function () {
                    if (mode === 'read') {
                        mode = 'edit';
                        $(this).text('Back to Read Mode');
                        $('#problems-center-{{$note->id}} .point-table').removeClass('read').addClass('edit');
                    } else {
                        let url = $(this).closest('.stag-popup').attr('stag-popup-key');
                        if(url.indexOf('forceReadMode') === -1) url += '&forceReadMode=1';
                        refreshDynamicStagPopup(url);
                    }
                    return false;
                });

            buttonContainer.insertAfter(titleElem);

            setTimeout(() => {
                $('<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>').appendTo(buttonContainer);
            }, 1000);

        }
        addMCInitializer('problems-center-{{$note->id}}', init, '#problems-center-{{$note->id}}');
    }).call(window);
</script>
@endif
