<?php

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

/** @var Client $patient */
/** @var Note $note */

list($supplements, $counts) = Point::getPointsOfCategoryExtended($patient, 'SUPPLEMENT', $note);

?>

<div class="mt-3 p-3 border-top min-height-500px" id="supplements-center-{{$note->id}}">
    <div class="point-table-container">

        <table class="table table-sm table-bordered mb-0 bg-white mb-2 point-table">
            <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 width-50px">Edit</th>
                <th class="border-bottom-0 text-secondary w-30">Subjective</th>
                <th class="border-bottom-0 text-secondary w-30">Plan</th>
                <th class="border-bottom-0 text-secondary width-30px"></th>
            </tr>
            </thead>
            <?php $prevRowState = -1; ?>
            <?php foreach($supplements as $supplement): ?>
                <?php $point = $supplement; ?>
                @if($prevRowState !== $supplement->state)
                    @include('app.patient.wizard-partials.state-row', ['point' => $supplement])
                @endif
                <?php $prevRowState = $supplement->state; ?>
                <?php $rel = $supplement->relevanceToNote($note); ?>
                <tr class="{{$rel ? 'relevant-to-visit' : ''}} point-row"
                    data-uid="{{$supplement->uid}}"
                    data-name-base64="{{!!@($supplement->data->name) ? base64_encode($supplement->data->name) : ''}}"
                    data-is-removed="{{$supplement->is_removed ? 1 : 0}}"
                    data-is-removed-due-to-entry-error="{{$supplement->is_removed_due_to_entry_error ? 1 : 0}}">
                    @if($patient->core_note_id !== $note->id)
                        @include('app.patient.wizard-partials.relevance-column', ['point' => $supplement])
                    @endif
                    <td>
                        <div class="d-flex align-items-baseline">
                            @include('app.patient.wizard-partials.state-icon', ['point' => $supplement])
                            <div>
                                <b><?= !!@($supplement->data->name) ? @($supplement->data->name) : '-' ?></b>
                                @include('app.patient.wizard-partials.state-badge', ['point' => $supplement, 'addedVerb' => 'Prescribed', 'removedVerb' => 'Discontinued'])
                            </div>
                        </div>
                    </td>
                    <td>
                        <div moe huge relative>
                            <a start show href="#" title="Edit">Edit</a>
                            <form url="/api/visitPoint/updateTopLevel" no-auto-focus class="mcp-theme-1 frm-edit-supplement">
                                <input type="hidden" name="uid" value="<?= $supplement->uid ?>">
                                <input type="hidden" name="noteUid" value="<?= $note->uid ?>">
                                <p class="mb-2"><b>Update Supplement</b></p>

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

                                @if($supplement->added_in_note_id === $note->id)

                                    <input type="hidden" data-name="medId" value="{{@$supplement->data->medId}}">
                                    <input type="hidden" data-name="routedMedId" value="{{@$supplement->data->routedMedId}}">
                                    <input type="hidden" data-name="routedDosageFormMedId" value="{{@$supplement->data->routedDosageFormMedId}}">
                                    <input type="hidden" data-name="gcnSeqno" value="{{@$supplement->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"
                                               data-name="name"
                                               value="{{@$supplement->data->name}}"
                                               stag-suggest
                                               stag-suggest-ep="/fdb-med-suggest-v2/json">
                                    </div>

                                @else

                                    <div class="mb-2 bg-light p-2 border">
                                        <p class="mb-1 font-weight-bold">
                                            {{ @$supplement->data->name }}
                                        </p>
                                        @if($patient->core_note_id !== $note->id)
                                            <div class="text-secondary text-sm">Clinical details cannot be modified since the supplement was added prior to this visit.</div>
                                        @else
                                            <div class="text-secondary text-sm">Clinical details cannot be modified since the supplement was added on a previous visit.</div>
                                        @endif
                                    </div>

                                @endif

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

                                <div class="mt-3 pt-2 d-flex align-items-center border-top">
                                    <button type="submit" class="btn-save-supplement 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>
                    </td>
                    <td>
                        <div class="d-flex align-items-start">
                            <div class="flex-grow-1">
                                <?php
                                $point = $supplement;
                                include resource_path('views/app/patient/segment-templates/_child_review/last-review.php');
                                ?>
                            </div>
                            <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<?= !!@($supplement->data->name) ? ' for ' . @($supplement->data->name) : '' ?>"
                                   href="/point/review-log/<?= $supplement->uid ?>?popupmode=1">
                                    <i class="fa fa-history"></i>
                                </a>
                            </div>
                        </div>
                    </td>
                    <td>
                        <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.php');
                                ?>
                            </div>
                            <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<?= !!@($supplement->data->name) ? ' for ' . @($supplement->data->name) : '' ?>"
                                   href="/point/plan-log/<?= $supplement->uid ?>?popupmode=1">
                                    <i class="fa fa-history"></i>
                                </a>
                                <?php
                                /*$segment = $note->getSegmentByInternalName('plan_supplements');
                                if($segment) {
                                    include resource_path('views/app/patient/segment-templates/_child_plan/edit-plan.php');
                                }*/
                                ?>
                            </div>
                        </div>
                    </td>
                    <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><?= !!@($supplement->data->start_date) ? friendly_date($supplement->data->start_date) : '-' ?></b></div>
                                @if(!!@($supplement->data->prescriber))
                                    <div class="text-sm text-left text-secondary">By: <?= !!@($supplement->data->prescriber) ? @($supplement->data->prescriber) : '-' ?></div>
                                @endif
                                <hr class="my-1">
                                <div class="text-nowrap small text-left text-left">Ended <b><?= !!@($supplement->removal_effective_date) ? friendly_date($supplement->removal_effective_date) : '-' ?></b></div>
                                @if(!!@($supplement->data->prescriber))
                                    <div class="text-sm text-secondary">By/Memo: <?= !!@($supplement->removal_reason_memo) ? @($supplement->removal_reason_memo) : '-' ?></div>
                                @endif
                            </div>
                        </div>
                    </td>
                </tr>
            <?php endforeach; ?>
    </table>

    <div class="d-flex align-items-center">
        <div class="mt-1 w-100 border p-3 bg-aliceblue border-info rounded">
            <!--<a href="#" start show class="btn btn-sm btn btn-outline-primary">+ Add new supplement, prescribed during this visit</a>-->
            <form action="/api/visitPoint/addTopLevel" class="mcp-theme-1 w-100" id="frm-add-supplement" novalidate>
                <input type="hidden" name="noteUid" value="<?= $note->uid ?>">
                <input type="hidden" name="category" value="SUPPLEMENT">
                <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="row">
                    <div class="col-8">
                        <p class="mb-2"><b>Add Supplement</b></p>
                        <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', ['label' => 'supplement', 'addVerbPT' => 'Prescribed'])

                    </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 class="d-flex align-items-center">
                    <button type="submit" class="btn btn-sm btn-primary mr-2">Save Supplement</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>
</div>
</div>

<script>
(function() {
    function init() {
        let parentSegment = $('#supplements-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' => 'supplement', 'segment_part' => 'supplements'])

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

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

        // add button for "eRx"
        $('.btn-manage-erx-supplements').remove();
        $('<a ' +
            'href="/patients/view/{{$patient->uid}}/prescriptions-popup?noteUid={{$note->uid}}&erx_category=DRUG" ' +
            'title="Manage eRx" ' +
            'update-parent ' +
            'open-in-stag-popup ' +
            'mc-initer="prescriptions-popup-{{$patient->id}}" ' +
            'popup-style="medium" ' +
            'class="btn-manage-erx-supplements btn btn-sm mr-2 btn-info text-white font-weight-bold">Manage eRx</a>')
            .appendTo(buttonContainer);

        buttonContainer.insertAfter(titleElem);

        initSegmentMoes(parentSegment);
        __initRTEs(parentSegment.find('[note-rte]:not(.ql-container)'));
    }
    addMCInitializer('supplements-center-{{$note->id}}', init, '#supplements-center-{{$note->id}}');
}).call(window);
</script>