@extends ('layouts.patient')
<?php
/** @var \App\Models\Client $patient */
?>
@section('inner-content')

    <div class="mb-3">

        <div id="erxSingleApp" v-cloak>
            <div class="d-flex align-items-center pb-2">
                <h4 class="font-weight-bold m-0 font-size-14"><i class="fa fa-prescription mr-2"></i>ERx Ticket
                    <span v-if="!item.is_open" class="text-secondary font-weight-bold opacity-60">(Closed)</span>
                </h4>
                <span class="mx-3 text-secondary">|</span>
                <a class="c-pointer" v-if="item.is_open" v-on:click.prevent="closeItem(item)">Close</a>
                <a class="c-pointer" v-if="!item.is_open" v-on:click.prevent="openItem(item)">Re-open</a>
                <span class="mx-3 text-secondary">|</span>
                <a class="py-0 font-weight-normal c-pointer" v-on:click.prevent="showPopup('erx-popup', item)">Edit</a>
            </div>

            <div class="row mt-2 mb-3">
                <div class="col-6 pr-0">
                    <div class="card bg-light mb-3">
                        <div class="card-body">
                            <div class="d-flex align-items-start flex-nowrap mb-2">
                                <span class="width-100px text-secondary text-sm">Created</span>
                                <span class="font-weight-bold">@{{ item.created_at }}</span>
                            </div>
                            <div class="d-flex align-items-start flex-nowrap mb-2">
                                <span class="width-100px text-secondary text-sm">Medication</span>
                                <span class="font-weight-bold">@{{ item.medication ? item.medication : '-' }}</span>
                            </div>
                            <div class="d-flex align-items-start flex-nowrap mb-2">
                                <span class="width-100px text-secondary text-sm">Strength</span>
                                <span class="font-weight-bold">@{{ item.strength ? item.strength : '-' }}</span>
                            </div>
                            <div class="d-flex align-items-start flex-nowrap mb-2">
                                <span class="width-100px text-secondary text-sm">Route</span>
                                <span class="font-weight-bold">@{{ item.route ? item.route : '-' }}</span>
                            </div>
                            <div class="d-flex align-items-start flex-nowrap mb-2">
                                <span class="width-100px text-secondary text-sm">Frequency</span>
                                <span class="font-weight-bold">@{{ item.frequency ? item.frequency : '-' }}</span>
                            </div>
                            <div class="d-flex align-items-start flex-nowrap mb-2">
                                <span class="width-100px text-secondary text-sm">Dispense Amount</span>
                                <span class="font-weight-bold">@{{ item.dispense ? item.dispense : '-' }}</span>
                            </div>
                            <div class="d-flex align-items-start flex-nowrap mb-2">
                                <span class="width-100px text-secondary text-sm">Refills</span>
                                <span class="font-weight-bold">@{{ item.refills ? item.refills : '-' }}</span>
                            </div>
                            <div class="d-flex align-items-start flex-nowrap">
                                <span class="width-100px text-secondary text-sm">Purpose</span>
                                <span class="font-weight-bold">@{{ item.purpose ? item.purpose : '-' }}</span>
                            </div>
                            <hr class="m-neg-4">
                            <div class="d-flex align-items-start flex-nowrap">
                                <span class="width-100px text-secondary text-sm">Pref. Pharmacy</span>
                                <span class="" v-html="pharmacy()"></span>
                            </div>
                        </div>
                    </div>
                    @include('app.patient.partials.ticket_action_links')
                </div>
                <div class="col-6">
                    @include('app.patient.partials.ticket_vue_collab_card')
                </div>
            </div>

            <div class="stag-popup stag-popup-sm mcp-theme-1" stag-popup-key="erx-popup">
                <form method="POST" action="">
                    <h3 class="stag-popup-title mb-2">
                        <span>@{{ popupMode === 'add' ? 'Add ERx Item' : 'Edit ERx Item' }}</span>
                        <a href="#" class="ml-auto text-secondary"
                           onclick="return closeStagPopup()"><i class="fa fa-times-circle"></i></a>
                    </h3>
                    <div class="row mb-2">
                        <div class="col-6">
                            <label class="text-sm text-secondary mb-1">Medication</label>
                            <input required type="text" data-field="medication"
                                   v-model="popupItem.medication" class="form-control form-control-sm">
                        </div>
                        <div class="col-6">
                            <label class="text-sm text-secondary mb-1">Strength</label>
                            <input type="text" data-field="strength"
                                   v-model="popupItem.strength" class="form-control form-control-sm">
                        </div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-6">
                            <label class="text-sm text-secondary mb-1">Frequency</label>
                            <input type="text" v-model="popupItem.frequency" class="form-control form-control-sm"
                                   data-option-list="frequency-options">
                            <div id="frequency-options" class="data-option-list">
                                <div>Once a day</div>
                                <div>Twice a day</div>
                            </div>
                        </div>
                        <div class="col-6">
                            <label class="text-sm text-secondary mb-1">Route</label>
                            <input required type="text" v-model="popupItem.route" class="form-control form-control-sm"
                                   data-option-list="route-options">
                            <div id="route-options" class="data-option-list">
                                <div>PO (by mouth)</div>
                                <div>PR (per rectum)</div>
                                <div>IM (intramuscular)</div>
                                <div>IV (intravenous)</div>
                                <div>ID (intradermal)</div>
                                <div>IN (intranasal)</div>
                                <div>TP (topical)</div>
                                <div>SL (sublingual)</div>
                                <div>BUCC (buccal)</div>
                                <div>IP (intraperitoneal)</div>
                            </div>
                        </div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-6">
                            <label class="text-sm text-secondary mb-1">Dispense Amount</label>
                            <input required type="number" v-model="popupItem.dispense" class="form-control form-control-sm">
                        </div>
                        <div class="col-6">
                            <label class="text-sm text-secondary mb-1">Refills</label>
                            <input type="number" v-model="popupItem.refills" class="form-control form-control-sm">
                        </div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-12">
                            <label class="text-sm text-secondary mb-1">Purpose</label>
                            <input required type="text" data-field="icd" v-model="popupItem.purpose" class="form-control form-control-sm">
                        </div>
                    </div>
                    <hr class="mt-3 mb-2">

                    <div class="row mb-2">
                        <div class="col-12">
                            <label class="text-sm text-secondary mb-1 font-weight-bold">Preferred Pharmacy</label>
                        </div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-12">
                            <label class="text-sm text-secondary mb-1">Business Name</label>
                            <input type="text" autocomplete="donotdoit" id="pharmacy-search" v-model="popupItem.pharmacyName" class="form-control form-control-sm">
                            <div class="suggestions-outer pharmacy-suggestions position-absolute d-none"></div>
                        </div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-6">
                            <label class="text-sm text-secondary mb-1">City</label>
                            <input type="text" v-model="popupItem.pharmacyCity" class="form-control form-control-sm">
                        </div>
                        <div class="col-6">
                            <label class="text-sm text-secondary mb-1">State</label>
                            <input type="text" v-model="popupItem.pharmacyState" class="form-control form-control-sm">
                        </div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-12">
                            <label class="text-sm text-secondary mb-1">Address Memo</label>
                            <input type="text" v-model="popupItem.pharmacyAddressMemo" class="form-control form-control-sm">
                        </div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-6">
                            <label class="text-sm text-secondary mb-1">Phone</label>
                            <input type="text" v-model="popupItem.pharmacyPhone" class="form-control form-control-sm">
                        </div>
                        <div class="col-6">
                            <label class="text-sm text-secondary mb-1">Fax</label>
                            <input type="text" v-model="popupItem.pharmacyFax" class="form-control form-control-sm">
                        </div>
                    </div>

                    <div class="d-flex align-items-center justify-content-center mt-3">
                        <button type="button" class="btn btn-sm btn-primary mr-2" v-on:click.prevent="savePopupItem()">Submit</button>
                        <button type="button" class="btn btn-sm btn-default border" onclick="return closeStagPopup()">Cancel</button>
                    </div>
                </form>
            </div>
            @include('app.patient.partials.ticket_update_pro_form',['ticketType'=>'erx'])
        </div>
        <script>
            (function() {
                <?php
                $item = json_decode($ticket->data);
                $item->uid = $ticket->uid;
                $item->is_open = $ticket->is_open;
                $item->assigned_pro_id = $ticket->assigned_pro_id;
                $item->manager_pro_id = $ticket->manager_pro_id;
                $item->ordering_pro_id = $ticket->ordering_pro_id;
                $item->initiating_pro_id = $ticket->initiating_pro_id;
                $item->has_assigned_pro_signed = $ticket->has_assigned_pro_signed;
                $item->has_manager_pro_signed = $ticket->has_manager_pro_signed;
                $item->has_ordering_pro_signed = $ticket->has_ordering_pro_signed;
                $item->has_initiating_pro_signed = $ticket->has_initiating_pro_signed;
                $item->is_entry_error = $ticket->is_entry_error;
                $item->created_at = friendly_date_time($ticket->created_at);
                $items[] = $item;
                ?>
                function init() {
                    let items = [];
                    let erxSingleApp = new Vue({
                        el: '#erxSingleApp',
                        delimiters: ['@{{', '}}'],
                        data: {
                            popupMode: 'add',
                            item: {!! json_encode($item) !!},
                            popupItem: {
                                uid: '',
                                is_open: true,
                                medication: '',
                                strength: '',
                                amount: '',
                                route: '',
                                frequency: '',
                                dispense: '',
                                refills: '',
                                purpose: '',
                                pharmacyName: '',
                                pharmacyCity: '',
                                pharmacyState: '',
                                pharmacyAddressMemo: '',
                                pharmacyPhone: '',
                                pharmacyFax: '',
                            },
                            @include('app.patient.partials.ticket_vue_data')
                        },
                        methods: {
                            showPopup: function(_name, _item) {
                                closeStagPopup();
                                this.popupMode = _item ? 'edit' : 'add';
                                this.popupItem = _item ? JSON.parse(JSON.stringify(_item)) : {
                                    uid: '',
                                    is_open: true,
                                    medication: '',
                                    strength: '',
                                    amount: '',
                                    route: '',
                                    frequency: '',
                                    dispense: '',
                                    refills: '',
                                    purpose: '',
                                    pharmacy: '',
                                    pharmacyName: '',
                                    pharmacyCity: '',
                                    pharmacyState: '',
                                    pharmacyAddressMemo: '',
                                    pharmacyPhone: '',
                                    pharmacyFax: '',
                                };
                                showStagPopup('erx-popup');
                            },
                            savePopupItem: function() {
                                let form = $('#erxSingleApp form').first();
                                if(!form[0].checkValidity()) {
                                    form[0].reportValidity();
                                    return false;
                                }

                                showMask();
                                let payload = {};
                                if(this.popupMode === 'add') {
                                    payload.clientUid = '{{ $patient->uid }}';
                                    payload.category = 'erx';
                                    payload.assignedProUid = '{{ $pro->uid  }}';
                                    payload.managerProUid = '{{ $pro->uid  }}';
                                    payload.orderingProUid = '{{ $pro->uid  }}';
                                    payload.initiatingProUid = '{{ $pro->uid  }}';
                                    payload.data = JSON.stringify(this.popupItem);
                                }
                                else {
                                    payload.uid = this.popupItem.uid;
                                    payload.newData = JSON.stringify(this.popupItem);
                                }

                                $.post(
                                    '/api/ticket/' + (this.popupMode === 'add' ? 'create' : 'updateData'),
                                    payload,
                                    function(_data) {
                                        console.log(_data);
                                        fastReload();
                                    },
                                    'json');

                                return false;
                            },
                            closeItem: function(_item) {
                                showMask();
                                $.post('/api/ticket/close', {
                                    uid: _item.uid
                                }, function(_data) {
                                    fastReload();
                                });
                            },
                            openItem: function(_item) {
                                showMask();
                                $.post('/api/ticket/open', {
                                    uid: _item.uid
                                }, function(_data) {
                                    fastReload();
                                });
                            },
                            initRxAutoSuggest: function() {
                                let self = this;
                                $('#erxSingleApp input[type="text"][data-field="medication"]:not([ac-initialized])').each(function() {
                                    let elem = this,
                                        randPart = Math.ceil(Math.random() * 1000000),
                                        dynID = 'rx-' + randPart;
                                    $(elem).attr('id', dynID);
                                    var strengthElem = $(elem).closest('.stag-popup').find('[data-field="strength"]')[0],
                                        dynStrengthsID = 'rx-' + randPart + '-strengths';
                                    $(strengthElem).attr('id', dynStrengthsID);
                                    $(strengthElem).attr('rx-id', dynID);
                                    new window.Def.Autocompleter.Prefetch(dynStrengthsID, []);
                                    new window.Def.Autocompleter.Search(dynID,
                                        'https://clinicaltables.nlm.nih.gov/api/rxterms/v3/search?ef=STRENGTHS_AND_FORMS');
                                    window.Def.Autocompleter.Event.observeListSelections(dynID, function() {
                                        var autocomp = elem.autocomp, acData = autocomp.getSelectedItemData();
                                        var strengths = acData[0].data['STRENGTHS_AND_FORMS'];
                                        if (strengths) {
                                            strengthElem.autocomp.setListAndField(strengths, '');
                                        }
                                        self.popupItem.medication = $(elem).val();
                                    });
                                    window.Def.Autocompleter.Event.observeListSelections(dynStrengthsID, function() {
                                        var autocomp = elem.autocomp, acData = autocomp.getSelectedItemData();
                                        self.popupItem.strength = $(strengthElem).val();
                                    });
                                    $(elem).attr('ac-initialized', 1);
                                    $(strengthElem).attr('ac-initialized', 1);
                                });
                            },
                            initICDAutoSuggest: function() {
                                let self = this;
                                $('#erxSingleApp input[type="text"][data-field="icd"]:not([ac-initialized])').each(function() {
                                    var elem = this,
                                        dynID = 'icd-' + Math.ceil(Math.random() * 1000000),
                                        vueIndex = $(this).attr('data-index');
                                    $(elem).attr('id', dynID);
                                    new window.Def.Autocompleter.Search(dynID,
                                        'https://clinicaltables.nlm.nih.gov/api/icd10cm/v3/search?sf=code,name&ef=name', {
                                            tableFormat: true,
                                            valueCols: [0],
                                            colHeaders: ['Code', 'Name'],
                                        }
                                    );
                                    window.Def.Autocompleter.Event.observeListSelections(dynID, function() {
                                        let autocomp = elem.autocomp, acData = autocomp.getSelectedItemData();
                                        debugger
                                        self.popupItem.purpose = acData[0].code + ' - ' + acData[0].data.name;
                                        return false;
                                    });
                                    $(elem).attr('ac-initialized', 1);
                                });
                            },
                            inWords: function (num) {
                                try {
                                    num = +num;
                                    var a = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];
                                    var b = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
                                    if ((num = num.toString()).length > 3) return 'overflow';
                                    let n = ('000000000' + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/);
                                    if (!n) return; var str = '';
                                    str += (n[1] != 0) ? (a[Number(n[1])] || b[n[1][0]] + ' ' + a[n[1][1]]) + 'crore ' : '';
                                    str += (n[2] != 0) ? (a[Number(n[2])] || b[n[2][0]] + ' ' + a[n[2][1]]) + 'lakh ' : '';
                                    str += (n[3] != 0) ? (a[Number(n[3])] || b[n[3][0]] + ' ' + a[n[3][1]]) + 'thousand ' : '';
                                    str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';
                                    str += (n[5] != 0) ? ((str != '') ? 'and ' : '') + (a[Number(n[5])] || b[n[5][0]] + ' ' + a[n[5][1]]) : '';
                                    return str ? '(' + $.trim(str) + ')' : '';
                                }
                                catch (e) {
                                    return '';
                                }
                            },
                            pharmacy: function() {
                                return [
                                    this.item.pharmacyName,
                                    this.item.pharmacyCity,
                                    this.item.pharmacyState,
                                    this.item.pharmacyAddressMemo,
                                    this.item.pharmacyPhone,
                                    this.item.pharmacyFax,
                                ].filter(Boolean).join('<br>');
                            },
                            @include('app.patient.partials.pharmacy-suggest')
                            @include('app.patient.partials.ticket_vue_methods',['ticketType'=>'erx'])
                        },
                        mounted: function () {
                            this.initRxAutoSuggest();
                            this.initICDAutoSuggest();
                            initFastLoad($('#erxSingleApp'));
                            this.initPharmacySearch();
                        }
                    })
                }
                addMCInitializer('erx-single', init, '#erxSingleApp');
            })();
        </script>

    </div>

@endsection
