<?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(!@$allergies || !@$counts) {
    list($allergies, $counts) = Point::getPointsOfCategoryExtended($patient, 'ALLERGY', $note, !!@$summaryView);
}

$numActiveItems = Point::getNumPointsOfCategory($patient, 'ALLERGY');
if(!@$summaryView) {
    $favorites = $pro->favoritesByCategoryDecoded('allergy');
    function isFavoriteAllergy($_allergy, $_favorites) {
        foreach($_favorites as $favorite) {
            if($favorite->data->name === $_allergy->data->name) return $favorite->uid;
        }
        return false;
    }
}
?>

<div @if(!@$summaryView) class="mt-3 p-3 border-top" id="allergies-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_drug_allergies) ? 'checked' : ''}}
                       data-field-name="no_known_drug_allergies">
                <span>No Known Drug Allergies</span>
            </label>
            <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_allergies_of_any_type) ? 'checked' : ''}}
                       data-field-name="no_known_allergies_of_any_type"
                       data-num-active-items="{{$numActiveItems}}">
                <span>No Known Allergies of Any Type</span>
            </label>
        </div>
        @else
            @if($tracker && @($tracker->data->no_known_drug_allergies))
                <div>• No Known Drug Allergies</div>
            @endif
            @if($tracker && @($tracker->datano_known_allergies_of_any_typeno_known_drug_allergies))
                <div>• No Known Allergies of Any Type</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">Subjective</th>
                <th class="border-bottom-0 text-secondary w-30">Plan</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($allergies as $allergy): ?>
            <?php $point = $allergy; ?>
            @if(!@$summaryView)
                <?php $favoriteUid = isFavoriteAllergy($allergy, $favorites); ?>
            @endif
            @if($prevRowState !== $allergy->state)
                @include('app.patient.wizard-partials.state-row', ['point' => $allergy])
            @endif
            <?php $prevRowState = $allergy->state; ?>
            <?php $rel = $allergy->note_point_uid; ?>

            <tr class="{{$rel ? 'relevant-to-visit' : ''}} point-row"
                data-uid="{{$allergy->uid}}"
                data-name-base64="{{ !!@($allergy->data->name) ? base64_encode($allergy->data->name) : '' }}"
                data-is-removed="{{$allergy->is_removed ? 1 : 0}}"
                data-is-removed-due-to-entry-error="{{$allergy->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' => $allergy])
                        <div>

                            @if(!@$summaryView)
                                <div>
                                    <div moe huge relative>
                                        <a start show href="#" title="Edit"><?= !!@($allergy->data->name) ? @($allergy->data->name) : '-' ?></a>
                                        <form url="/api/visitPoint/updateTopLevel" no-auto-focus class="mcp-theme-1 frm-edit-allergy">
                                            <input type="hidden" name="uid" value="<?= $allergy->uid ?>">
                                            <input type="hidden" name="noteUid" value="<?= $note->uid ?>">
                                            <p class="mb-2"><b>Update Allergy</b></p>

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

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

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

                                                <input type="hidden" data-name="damConceptId" value="{{@$allergy->data->damConceptId}}">
                                                <input type="hidden" data-name="damConceptIdType" value="{{@$allergy->data->damConceptIdType}}">

                                                <div class="mb-2">
                                                    <label class="text-sm mb-0 font-weight-bold">Name</label>
                                                    <input type="text" data-name="name" class="form-control form-control-sm"
                                                           value="{{@$allergy->data->name}}"
                                                           stag-suggest
                                                           stag-suggest-ep="/fdb-allergy-suggest/json">
                                                </div>

                                            </div>

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

                                            <div class="mt-3 pt-2 d-flex align-items-center border-top">
                                                <button type="submit" class="btn-save-allergy 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>
                                </div>
                            @else
                                <?= !!@($allergy->data->name) ? @($allergy->data->name) : '-' ?>
                            @endif

                            @include('app.patient.wizard-partials.state-badge', ['point' => $allergy, 'addedVerb' => 'Added'])
                        </div>
                        @if(!@$summaryView)
                        <div class="ml-auto 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="allergy">
                                        <textarea class="d-none" name="data">{!! json_encode(["name" => @($allergy->data->name), "damConceptId" => @($allergy->data->damConceptId), "damConceptIdType" => @($allergy->data->damConceptIdType),]) !!}</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>
                    <div if-read-mode>
                        <div class="d-flex align-items-start position-relative">
                            <div class="flex-grow-1">
                                <?php
                                $point = $allergy;
                                include resource_path('views/app/patient/segment-templates/_child_review/last-review-optimized.php');
                                ?>
                            </div>
                            @if(!@$summaryView)
                            <div class="d-inline-flex ml-1">
                                <a class="px-1 view-review-log"
                                   native target="_blank"
                                   open-in-stag-popup
                                   popup-style="stag-popup-md"
                                   title="Subjective log<?= !!@($allergy->data->name) ? ' for ' . @($allergy->data->name) : '' ?>"
                                   href="/point/review-log/<?= $allergy->uid ?>?popupmode=1">
                                    <i class="fa fa-history"></i>
                                </a>
                                <?php
                                if($segment) {
                                    include resource_path('views/app/patient/segment-templates/_child_review/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/edit-review-in-place-optimized.php');
                        }
                        ?>
                    </div>
                </td>
                <td>
                    <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/last-plan-optimized.php');
                                ?>
                            </div>
                            @if(!@$summaryView)
                            <div class="d-inline-flex ml-1">
                                <a class="px-1 view-review-log"
                                   native target="_blank"
                                   open-in-stag-popup
                                   popup-style="stag-popup-md"
                                   title="Plan log<?= !!@($allergy->data->name) ? ' for ' . @($allergy->data->name) : '' ?>"
                                   href="/point/plan-log/<?= $allergy->uid ?>?popupmode=1">
                                    <i class="fa fa-history"></i>
                                </a>
                                <?php
                                if($segment) {
                                    include resource_path('views/app/patient/segment-templates/_child_plan/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/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><?= !!@($allergy->data->start_date) ? friendly_date($allergy->data->start_date) : '-' ?></b></div>
                            @if(!!@($allergy->data->prescriber))
                                <div class="text-sm text-left text-secondary">By: <?= !!@($allergy->data->prescriber) ? @($allergy->data->prescriber) : '-' ?></div>
                            @endif
                            <hr class="my-1">
                            <div class="text-nowrap small text-left text-left">Ended <b><?= !!@($allergy->removal_effective_date) ? friendly_date($allergy->removal_effective_date) : '-' ?></b></div>
                            @if(!!@($allergy->data->prescriber))
                                <div class="text-sm text-secondary">By/Memo: <?= !!@($allergy->removal_reason_memo) ? @($allergy->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-allergy" novalidate>
                                <input type="hidden" name="noteUid" value="<?= $note->uid ?>">
                                <input type="hidden" name="category" value="ALLERGY">
                                <input type="hidden" name="data">

                                <input type="hidden" data-name="damConceptId">
                                <input type="hidden" data-name="damConceptIdType">

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

                                <div class="d-flex align-items-baseline mb-2">
                                    <b>Add Allergy</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 Allergies <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-damConceptId="{{@($favorite->data->damConceptId)}}"
                                                       data-damConceptIdType="{{@($favorite->data->damConceptIdType)}}"
                                                       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="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-ep="/fdb-allergy-suggest/json"
                                           required>
                                </div>

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

                                <div class="d-flex align-items-center">
                                    <button type="submit" class="btn btn-sm btn-primary mr-2 my-1">Save Allergy</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">
                            <div class="fdb-allergy-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' => 'allergy', 'adder' => 'Diagnosed By'])
                </div>
            </div>
        </div>
        @endif

    </div>
</div>

@if(!@$summaryView)
<script>
    (function() {
        function init() {
            let parentSegment = $('#allergies-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="damConceptId"]').val(_data.dam_concept_id);
                    _input.closest('form').find('input[data-name="damConceptIdType"]').val(_data.dam_concept_id_typ);

                    $('.fdb-allergy-vigilance').html('<span class="text-secondary font-italic">Please wait ...</span>');
                    $.post('/fdb-allergy-vigilance/{{$patient->uid}}', {
                        _token: '{{csrf_token()}}',
                        name: _input.val(),
                        damConceptId: _data.dam_concept_id,
                        damConceptIdType: _data.dam_concept_id_typ
                    }, _data => {
                        $('.fdb-allergy-vigilance').html(_data);
                    });

                });

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

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

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

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

            let mode = 'read';

            // custom buttons on title bar
            $('.button-container').remove();
            let buttonContainer = $('<div/>').addClass('button-container ml-4 mr-auto');
            let titleElem = $('#allergies-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);

            $('<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);

            button
                .off('click.toggle-edit')
                .on('click.toggle-edit', function () {
                    if (mode === 'read') {
                        mode = 'edit';
                        $(this).text('Back to Read Mode');
                        $('#allergies-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);

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