<?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(!@$medications || !@$counts) {
    list($medications, $counts) = Point::getPointsOfCategoryExtended($patient, 'MEDICATION', $note, !!@$summaryView);
}
$numActiveItems = Point::getNumPointsOfCategory($patient, 'MEDICATION');
if(!@$summaryView) {
    $favorites = $pro->favoritesByCategoryDecoded('medication');
    function isFavoriteMedication($_medication, $_favorites) {
        foreach($_favorites as $favorite) {
            if($favorite->data->name === $_medication->data->name) return $favorite->uid;
        }
        return false;
    }
}
?>

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

        <?php $tracker = Point::getGlobalSingletonOfCategory($patient, 'NO_KNOWN_TRACKER'); ?>
        @if(!@$summaryView)
        <textarea class="no_known_tracker d-none">{!! $tracker && @($tracker->data) ? json_encode($tracker->data) : '{}' !!}</textarea>
        <div class="d-flex align-items-center mb-3">
            <label class="border border-info d-inline-flex align-items-center my-0 mr-3 p-2 rounded">
                <input type="checkbox" class="tracker-input mr-2"
                       {{$tracker && @($tracker->data->no_known_medications) ? 'checked' : ''}}
                       data-field-name="no_known_medications"
                       data-num-active-items="{{$numActiveItems}}">
                <span>No Known Medications</span>
            </label>
        </div>
        @else
            @if($tracker && @($tracker->data->no_known_medications))
                <div>• No Known Medications</div>
            @endif
        @endif

        <table class="table table-sm table-bordered bg-white mb-2 point-table read">
            <thead>
            <tr class="">
                @if($patient->core_note_id !== $note->id)
                    <th class="border-bottom-0 text-secondary text-center width-35px text-nowrap pr-1">Rel.</th>
                @endif
                <th class="border-bottom-0 text-secondary">Name</th>
                <th class="border-bottom-0 text-secondary w-30">Subj. Frequency / Experience</th>
                <th class="border-bottom-0 text-secondary w-30">Plan Frequency</th>
                @if(!@$summaryView) <th class="border-bottom-0 text-secondary width-30px"></th> @endif
            </tr>
            </thead>
            <?php $prevRowState = -1; ?>
            <?php
            $segment = $note->coreSegment; // getSegmentByInternalName('intake_allergies');
            // if(!$segment) $segment = $note->getSegmentByInternalName('allergies');
            // if(!$segment) $segment = $note->coreSegment;
            ?>
            <?php foreach($medications as $medication): ?>
                <?php $point = $medication; ?>
                @if(!@$summaryView)
                    <?php $favoriteUid = isFavoriteMedication($medication, $favorites); ?>
                @endif
                @if($prevRowState !== $medication->state)
                    @include('app.patient.wizard-partials.state-row', ['point' => $medication])
                @endif
                <?php $prevRowState = $medication->state; ?>
                <?php $rel = $medication->note_point_uid; ?>
                <tr class="{{$rel ? 'relevant-to-visit' : ''}} point-row"
                    data-uid="{{$medication->uid}}"
                    data-name-base64="{{!!@($medication->data->name) ? base64_encode($medication->data->name) : ''}}"
                    data-is-removed="{{$medication->is_removed ? 1 : 0}}"
                    data-is-removed-due-to-entry-error="{{$medication->is_removed_due_to_entry_error ? 1 : 0}}">
                    @if($patient->core_note_id !== $note->id)
                        @include('app.patient.wizard-partials.relevance-column-optimized', ['point' => $point])
                    @endif
                    <td>
                        <div class="d-flex align-items-start">
                            @include('app.patient.wizard-partials.state-icon', ['point' => $medication])
                            <div>
                                @if(!@$summaryView)
                                    <div moe huge relative>
                                        <a start show href="#" title="Edit">
                                            <b><?= !!@($medication->data->name) ? @($medication->data->name) : '-' ?></b>
                                            <?php
                                            if($medication->last_child_review_data) {
                                                $review = json_decode($medication->last_child_review_data);
                                                if(isset($review->value) && isset($review->experience)) {
                                                    ?>
                                                    <span class="text-dark text-sm ml-1">({{$review->value}})</span>
                                                    <?php
                                                }
                                            }
                                            ?>
                                        </a>
                                        <form url="/api/visitPoint/updateTopLevel" no-auto-focus class="mcp-theme-1 frm-edit-medication">
                                            <input type="hidden" name="uid" value="<?= $medication->uid ?>">
                                            <input type="hidden" name="noteUid" value="<?= $note->uid ?>">
                                            <p class="mb-2"><b>Update Medication</b></p>

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

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

                                                <div class="mb-2 bg-light p-2 border">
                                                    <p class="mb-1 font-weight-bold">
                                                        {{ @$medication->data->name }}
                                                    </p>
                                                    @if($patient->core_note_id !== $note->id)
                                                        <div class="text-secondary">This medication 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 {{$medication->added_in_note_id === $note->id ? '' : 'd-none'}}" if-core-data-edit-confirmed>
                                                <input type="hidden" data-name="medId" value="{{@$medication->data->medId}}">
                                                <input type="hidden" data-name="routedMedId" value="{{@$medication->data->routedMedId}}">
                                                <input type="hidden" data-name="routedDosageFormMedId" value="{{@$medication->data->routedDosageFormMedId}}">
                                                <input type="hidden" data-name="gcnSeqno" value="{{@$medication->data->gcnSeqno}}">

                                                <div class="mb-2">
                                                    <label class="text-sm mb-1 font-weight-bold">Drug</label>
                                                    <input type="text" class="form-control form-control-sm min-width-unset prescription-medication"
                                                           data-name="name"
                                                           value="{{@$medication->data->name}}"
                                                           stag-suggest
                                                           stag-suggest-ep="/fdb-med-suggest-v2/json">
                                                </div>
                                            </div>

                                            @include('app.patient.wizard-partials.common-fields-optimized', ['label' => 'medication', 'point' => $medication, 'addVerbPT' => 'Prescribed'])

                                            <div class="mt-3 pt-2 d-flex align-items-center border-top">
                                                <button type="submit" class="btn-save-medication 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
                                    <?= !!@($medication->data->name) ? @($medication->data->name) : '-' ?>
                                @endif
                                @include('app.patient.wizard-partials.state-badge', ['point' => $medication, 'addedVerb' => 'Prescribed', 'removedVerb' => 'Discontinued'])
                            </div>
                            @if(!@$summaryView)
                            <div class="ml-auto pl-1 mr-1">
                                <div moe>
                                    @if(!$favoriteUid)
                                        <form show url="/api/proFavorite/create">
                                            <input type="hidden" name="proUid" value="{{$pro->uid}}">
                                            <input type="hidden" name="category" value="medication">
                                            <textarea class="d-none"
                                                      name="data">{!! json_encode(["name" => @($medication->data->name), "medId" => @($medication->data->medId), "routedMedId" => @($medication->data->routedMedId), "routedDosageFormMedId" => @($medication->data->routedDosageFormMedId), "gcnSeqno" => @($medication->data->gcnSeqno)]) !!}</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"></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"></i>
                                            </button>
                                        </form>
                                    @endif
                                </div>
                            </div>
                            @endif
                        </div>
                    </td>
                    <td>
                        <?php
                        list($currentChildReview, $previousChildReview) = @$point ? \App\Models\Point::getCurrentAndPreviousChildReviews($medication, $note) : [null, null];
                        ?>
                        <div if-read-mode>
                            <div class="d-flex align-items-start position-relative">
                                <div class="flex-grow-1">
                                    <?php
                                    $point = $medication;
                                    include resource_path('views/app/patient/segment-templates/_child_review/medication/last-review-optimized.php');
                                    ?>
                                </div>
                                @if(!@$summaryView)
                                <div class="d-inline-flex ml-1">
                                    <a class="px-1 view-review-log text-secondary on-hover-opaque"
                                       native target="_blank"
                                       open-in-stag-popup
                                       popup-style="stag-popup-md"
                                       title="Subjective log<?= !!@($medication->data->name) ? ' for ' . @($medication->data->name) : '' ?>"
                                       href="/point/review-log/<?= $medication->uid ?>?popupmode=1">
                                        <i class="fa fa-history"></i>
                                    </a>
                                    <?php
                                    if($segment) {
                                        include resource_path('views/app/patient/segment-templates/_child_review/medication/edit-review-optimized.php');
                                    }
                                    ?>
                                </div>
                                @endif
                            </div>
                        </div>
                        <div if-edit-mode>
                            <?php
                            if($segment) {
                                include resource_path('views/app/patient/segment-templates/_child_review/medication/edit-review-in-place-optimized.php');
                            }
                            ?>
                        </div>
                    </td>
                    <td>
                        <?php
                        list($currentChildPlan, $previousChildPlan) = @$point ? \App\Models\Point::getCurrentAndPreviousChildPlans($medication, $note) : [null, null];
                        ?>
                        <div if-read-mode>
                            <div class="d-flex align-items-start position-relative">
                                <div class="flex-grow-1">
                                    <?php
                                    include resource_path('views/app/patient/segment-templates/_child_plan/medication/last-plan-optimized.php');
                                    ?>
                                </div>
                                @if(!@$summaryView)
                                <div class="d-inline-flex ml-1">
                                    <a class="px-1 view-review-log text-secondary on-hover-opaque"
                                       native target="_blank"
                                       open-in-stag-popup
                                       popup-style="stag-popup-md"
                                       title="Plan log<?= !!@($medication->data->name) ? ' for ' . @($medication->data->name) : '' ?>"
                                       href="/point/plan-log/<?= $medication->uid ?>?popupmode=1">
                                        <i class="fa fa-history"></i>
                                    </a>
                                    <?php
                                    if($segment) {
                                        include resource_path('views/app/patient/segment-templates/_child_plan/medication/edit-plan-optimized.php');
                                    }
                                    ?>
                                </div>
                                @endif
                            </div>
                        </div>
                        <div if-edit-mode>
                            <?php
                            if($segment) {
                                include resource_path('views/app/patient/segment-templates/_child_plan/medication/edit-plan-in-place-optimized.php');
                            }
                            ?>
                        </div>
                    </td>
                    @if(!@$summaryView)
                    <td>
                        <div class="position-relative c-pointer stag-tooltip">
                            <i class="fa fa-info-circle"></i>
                            <div class="position-absolute bg-white border rounded p-2 stag-tooltip-content">
                                <div class="text-nowrap small text-left">Started <b><?= !!@($medication->data->start_date) ? friendly_date($medication->data->start_date) : '-' ?></b></div>
                                @if(!!@($medication->data->prescriber))
                                    <div class="text-sm text-left text-secondary">By: <?= !!@($medication->data->prescriber) ? @($medication->data->prescriber) : '-' ?></div>
                                @endif
                                <hr class="my-1">
                                <div class="text-nowrap small text-left text-left">Ended <b><?= !!@($medication->removal_effective_date) ? friendly_date($medication->removal_effective_date) : '-' ?></b></div>
                                @if(!!@($medication->data->prescriber))
                                    <div class="text-sm text-secondary">By/Memo: <?= !!@($medication->removal_reason_memo) ? @($medication->removal_reason_memo) : '-' ?></div>
                                @endif
                            </div>
                        </div>
                    </td>
                    @endif
                </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-medication" novalidate>
                                <input type="hidden" name="noteUid" value="<?= $note->uid ?>">
                                <input type="hidden" name="category" value="MEDICATION">
                                <input type="hidden" name="data">

                                <input type="hidden" data-name="medId">
                                <input type="hidden" data-name="routedMedId">
                                <input type="hidden" data-name="routedDosageFormMedId">
                                <input type="hidden" data-name="gcnSeqno">

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

                                <div class="d-flex align-items-baseline mb-2">
                                    <b>Add Medication</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 Medications <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-medId="{{@($favorite->data->medId)}}"
                                                       data-routedMedId="{{@($favorite->data->routedMedId)}}"
                                                       data-routedDosageFormMedId="{{@($favorite->data->routedDosageFormMedId)}}"
                                                       data-gcnSeqno="{{@($favorite->data->gcnSeqno)}}"
                                                       class="px-2 py-1 d-block text-nowrap text-sm favorite-item">
                                                        {{$favorite->data->name}}
                                                    </a>
                                                @endforeach
                                            </div>
                                        </div>
                                    @endif
                                </div>
                                <div class="mb-2">
                                    <label class="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-med-suggest-v2/json"
                                           required>
                                </div>

                                <?php $point = null; ?>
                                @include('app.patient.wizard-partials.common-fields-optimized', ['label' => 'medication', 'addVerbPT' => 'Prescribed'])

                                <div class="d-flex align-items-center">
                                    <button type="submit" class="btn btn-sm btn-primary mr-2">Save Medication</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
                            $problems = \App\Models\Point::getPointsOfCategory($patient, "PROBLEM");
                            ?>
                            @if(count($problems))
                                <h6 class="my-0 font-weight-bold text-secondary mb-2">Active Problems</h6>
                                <div class="bg-light border px-2 pt-2 pb-1 mb-0">
                                    @foreach($problems as $problem)
                                        <div class="mb-1">
                                            <b><?= !!@($problem->data->name) ? @($problem->data->name) : '-' ?></b>
                                        </div>
                                    @endforeach
                                </div>
                                <hr class="my-3 m-neg-3">
                            @endif

                            <div class="fdb-rx-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' => 'medication', 'adder' => 'Prescriber'])
                </div>
            </div>
        </div>
        @endif

    </div>
</div>

@if(!@$summaryView)
<script>
(function() {
    function init() {
        let parentSegment = $('#medications-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="routedMedId"]').val(_data.routed_med_id);
                $(_input).closest('form').find('input[data-name="routedDosageFormMedId"]').val(_data.routed_dosage_form_med_id);
                $(_input).closest('form').find('input[data-name="gcnSeqno"]').val(_data.gcn_seqno);
                $(_input).closest('form').find('input[data-name="medId"]').val(_data.medid);

                $('.fdb-rx-vigilance').html('<span class="text-secondary font-italic">Please wait ...</span>');
                $.post('/fdb-rx-vigilance/{{$patient->uid}}', {
                    _token: '{{csrf_token()}}',
                    medId: _data.medid,
                    routedMedId: _data.routed_med_id,
                    routedDosageFormMedId: _data.routed_dosage_form_med_id,
                    gcnSeqno: _data.gcn_seqno,
                    name: _input.val(),
                }, _data => {
                    $('.fdb-rx-vigilance').html(_data);
                });

                return false;
            });

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

        // custom buttons on title bar
        $('.button-container').remove();
        let buttonContainer = $('<div/>').addClass('button-container ml-4 mr-2 d-inline-flex align-items-center flex-grow-1');
        let titleElem = $('#medications-center-{{$note->id}}').closest('.stag-popup').find('.stag-popup-title>span');
        titleElem.next().removeClass('ml-4');
        titleElem.parent().addClass('align-items-baseline');

        // 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 btn-info text-white font-weight-bold shadow-none">Switch to Edit Mode</a>')
            .appendTo(buttonContainer);

        $('<div class="d-inline-flex align-self-stretch align-items-center ml-3 mr-auto">' +
            '<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);

        // add button for "reconcile active medications"
        if($('.active-record').length) {
            $('.btn-reconcile-active').remove();
            $('<a ' +
                'href="/medications-reconcile/{{$patient->uid}}/{{$note->uid}}" ' +
                'title="Reconcile Active Medications" ' +
                'update-parent ' +
                'open-in-stag-popup ' +
                'mc-initer="medications-reconcile-{{$note->id}}" ' +
                'popup-style="medium" ' +
                'class="btn-reconcile-active btn btn-sm mr-2 btn-primary text-white font-weight-bold">Reconcile Active Medications</a>')
                .appendTo(buttonContainer);
        }

        // add button for "eRx"
        $('.btn-manage-erx').remove();
        $('<a ' +
            'href="#" ' +
            'data-non-segment-target="Prescriptions" ' +
            'class="btn-manage-erx btn btn-sm mr-2 btn-primary text-white font-weight-bold">Manage eRx</a>')
            .appendTo(buttonContainer);

        buttonContainer.insertAfter(titleElem);

        initSegmentMoes(parentSegment);

        // if there are active items, and it is marked NKAM, auto-unmark it
        @if($numActiveItems && $tracker && @($tracker->data->no_known_medications))
            parentSegment.find('[data-field-name="no_known_medications"]').prop('checked', false).trigger('change');
        @endif

        parentSegment.find('.favorite-item')
            .off('click.add-from-favorite')
            .on('click.add-from-favorite', function () {
                let form = $('#frm-add-medication');
                form.find('input[data-name="name"]').val($(this).attr('data-name'));
                form.find('input[data-name="medId"]').val($(this).attr('data-medId'));
                form.find('input[data-name="routedMedId"]').val($(this).attr('data-routedMedId'));
                form.find('input[data-name="routedDosageFormMedId"]').val($(this).attr('data-routedDosageFormMedId'));
                form.find('input[data-name="gcnSeqno"]').val($(this).attr('data-gcnSeqno'));
                $(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="medId"]').val($(this).attr('data-medId'));
                row.find('input[key="routedMedId"]').val($(this).attr('data-routedMedId'));
                row.find('input[key="routedDosageFormMedId"]').val($(this).attr('data-routedDosageFormMedId'));
                row.find('input[key="gcnSeqno"]').val($(this).attr('data-gcnSeqno'));
                $(this).closest('.on-click-menu').find('[menu]').hide();
                return false;
            });

        let mode = 'read';

        button
            .off('click.toggle-edit')
            .on('click.toggle-edit', function () {
                if (mode === 'read') {
                    mode = 'edit';
                    $(this).text('Back to Read Mode');
                    $('#medications-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(() => {
        __initRTEs(parentSegment.find('[note-rte]:not(.ql-container)'));
        }, 0);
    }
    addMCInitializer('medications-center-{{$note->id}}', init, '#medications-center-{{$note->id}}');
}).call(window);
</script>
@endif
