<?php
if(!$contentData || !isset($contentData['items']) || !count($contentData['items'])) {
    $contentData = [
        "items" => [
            [
                "title" => "",
                "strength" => "",
                "frequency" => "",
                "detail" => "",
                "notes" => ["", ""],

                "type" => "",
                "updated_note_uid" => "",
                "created_note_uid" => "",
                "removed_note_uid" => "",

            ]
        ]
    ];
}

$formID = rand(0, 100000);
?>
<div id="rxSection_{{$formID}}">
    <h3 class="stag-popup-title mb-2 border-bottom-0 pb-1 hide-if-note">
        <span>Current Medications</span>
        <div v-if="favorites && favorites.length" class="d-inline-flex ml-2">
            <span class="mr-2 text-secondary">|</span>
            <div moe relative>
                <a start show href="#">
                    <i class="fa fa-star"></i>
                    Favorites
                </a>
                <div url="#" class="mt-1">
                    <a href="#"
                       v-for="(favorite, favIndex) in favorites"
                       class="d-flex align-items-center text-nowrap text-decoration-none"
                       :class="favIndex < favorites.length - 1 ? 'mb-2' : ''"
                       v-on:click.prevent="addFromFavorite(favorite)">
                        <i class="fa fa-check font-weight-bold mr-2" :class="isFavoriteAdded(favorite) ? '' : 'text-secondary-light'"></i>
                        <span :class="isFavoriteAdded(favorite) ? 'font-weight-bold' : ''">@{{ favorite.data.title }}</span>
                        <span v-if="favorite.data.strength" class="text-secondary d-inline-flex">
                            <span class="mx-1">/</span>
                            <span>@{{ favorite.data.strength }}</span>
                        </span>
                    </a>
                </div>
            </div>
        </div>
        <a href="#" onclick="return closeStagPopup()"
           class="ml-auto text-secondary">
            <i class="fa fa-times-circle"></i>
        </a>
    </h3>

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

    <table class="table table-sm table-bordered mb-2 table-edit-sheet">
        <thead>
        <tr class="bg-light">
            <th class="px-2 text-secondary border-bottom-0 width-30px text-center">#</th>
            <th class="px-2 text-secondary border-bottom-0 width-30px text-left">Type</th>
            <th class="px-2 text-secondary border-bottom-0 w-25">
                <div class="d-flex align-items-center font-weight-normal">
                    <span>Title</span>
                    <div class="hide-if-dashboard ml-auto">
                        <div v-if="favorites && favorites.length" class="d-inline-flex2">
                            <div moe relative>
                                <a start show href="#">
                                    <i class="fa fa-star"></i>
                                    Favorites
                                </a>
                                <div url="#" class="mt-1">
                                    <a href="#"
                                       v-for="(favorite, favIndex) in favorites"
                                       class="d-flex align-items-center text-nowrap text-decoration-none"
                                       :class="favIndex < favorites.length - 1 ? 'mb-2' : ''"
                                       v-on:click.prevent="addFromFavorite(favorite)">
                                        <i class="fa fa-check font-weight-bold mr-2"
                                           :class="isFavoriteAdded(favorite) ? '' : 'text-secondary-light'"></i>
                                        <span :class="isFavoriteAdded(favorite) ? 'font-weight-bold' : ''">@{{ favorite.data.title }}</span>
                                        <span v-if="favorite.data.strength" class="text-secondary d-inline-flex">
                                            <span class="mx-1">/</span>
                                            <span>@{{ favorite.data.strength }}</span>
                                        </span>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </th>
            <th class="px-2 text-secondary border-bottom-0 width-150px">Strength/Form/Freq.</th>
            <th class="px-2 text-secondary border-bottom-0 w-25">Detail</th>
            <th class="px-2 text-secondary border-bottom-0">Notes</th>
            <th class="px-2 text-secondary border-bottom-0"></th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(item, index) in items" :class="item.type === 'removed' ? 'on-hover-opaque' : ''">
            <td class="px-2 pt-2 text-center font-weight-bold text-secondary">@{{ index + 1 }}</td>
            <td class="px-2 pt-2 text-left text-capitalize text-nowrap" :data-type="item.type"
                v-html="(item.type === 'prescribed today' || item.type === 'updated' ? '*' : '') + ' ' + item.type"></td>
            <td>
                <input type="text" :data-index="index"
                       class="form-control form-control-sm canvas-rx-title"
                       data-field="title" v-model="item.title" autofocus required>
            </td>
            <td class="position-relative">
                <input type="text" :data-index="index"
                       class="form-control form-control-sm"
                       data-field="strength" v-model="item.strength">
                <input type="text" :data-index="index"
                       class="form-control form-control-sm"
                       v-on:change="onItemChange(index)"
                       data-option-list="frequency-options"
                       data-field="frequency" v-model="item.frequency">
                <div id="frequency-options" class="data-option-list">
                    <div>Once a day</div>
                    <div>Twice a day</div>
                </div>
            </td>
            <td><textarea type="text" class="form-control form-control-sm"
                          rx-rte :data-index="index" data-field="detail"
                          v-model="item.detail"></textarea>
            </td>
            <td>
                <textarea class="form-control form-control-sm"
                          v-on:change="onItemChange(index)"
                          v-model="item.notes[item.notes.length-1].text"></textarea>
            </td>
            <td class="px-2 text-nowrap">
                <div v-if="item.type !== 'removed'">
                    <a href="#"
                       v-if="!isFavorite(item)" v-on:click.prevent="addToFavorites(item)"
                       class="mt-1 d-inline-block mr-1 text-secondary on-hover-opaque"
                       title="Add to favorites">
                        <i class="fa fa-star"></i>
                    </a>
                    <a href="#"
                       v-if="isFavorite(item)" v-on:click.prevent="removeFromFavorites(item)"
                       class="mt-1 d-inline-block mr-1 text-warning"
                       title="Remove from favorites">
                        <i class="fa fa-star"></i>
                    </a>
                    <a href="#" v-on:click.prevent="removeItem(index)"
                       class="on-hover-opaque text-danger mt-1 d-inline-block">
                        <i class="fa fa-trash-alt"></i>
                    </a>
                </div>
            </td>
        </tr>
        </tbody>
    </table>

    <div class="form-group my-2 d-flex">
        <button type="button" class="btn btn-sm btn-default text-success border border-success mr-2"
                v-on:click.prevent="addItem('prescribed today')"
        >+ Entry: <b>Prescribed Today</b></button>
        <button type="button" class="btn btn-sm btn-default text-primary border border-primary mr-2"
                v-on:click.prevent="addItem('existing')"
        >+ Entry: <b>Existing</b></button>
    </div>

</div>
<script>
    (function() {
        let favorites = <?= json_encode($pro->favoritesByCategory('rx')) ?>;
        for (let i = 0; i < favorites.length; i++) {
            favorites[i].data = JSON.parse(favorites[i].data);
        }
        let dbItems = <?= json_encode($contentData['items']) ?>,
            originalItems = JSON.parse(JSON.stringify(dbItems));
        for (let i = 0; i < dbItems.length; i++) {
            // if(typeof dbItems[i].is_currently_active === 'undefined') {
            //     dbItems[i].is_currently_active = true;
            // }
            if(typeof dbItems[i].notes === 'undefined') {
                dbItems[i].notes = [];
            }
            dbItems[i].notes.push({
                date: '{{@$note ? $note->effective_dateest : date('Y-m-d')}}',
                text: '',
            });
            if(dbItems[i].type !== 'removed' && dbItems[i].updated_note_uid !== '{{@$note->uid}}') {
                dbItems[i].type = 'existing';
            }
        }
        function init() {
            window.clientRXApp_{{$formID}} = new Vue({
                el: '#rxSection_{{$formID}}',
                data: {
                    items: dbItems,
                    favorites: favorites,
                    skipWatcher: false,
                },
                mounted: function() {
                    this.initRTE();
                    this.initRxAutoSuggest();
                    $('#rxSection_{{$formID}} [moe][initialized]').removeAttr('initialized');
                    initMoes();
                },
                watch: {
                    $data: {
                        handler: function(val, oldVal) {
                            if(this.skipWatcher) {
                                console.log('ALIX skipWatcher');
                                return;
                            }
                            /*// if any "existing" item has changes, change it to "updated"
                            this.skipWatcher = true;
                            for (let i = 0; i < this.items.length; i++) {
                                let item = this.items[i];
                                if(item.type === 'existing') {
                                    if(item.title !== originalItems[i].title ||
                                        item.strength !== originalItems[i].strength ||
                                        item.frequency !== originalItems[i].frequency ||
                                        item.detail !== originalItems[i].detail) {
                                        item.type = 'updated';
                                        item.updated_note_uid = '{{@$note->uid}}';
                                    }
                                }
                            }
                            this.skipWatcher = false;*/
                            let payload = JSON.parse(JSON.stringify(this.cleanArray(this.items)));
                            for (let i = 0; i < payload.length; i++) {
                                payload[i].notes = payload[i].notes.filter(_x => {
                                    return !!_x.text;
                                });
                            }
                            $(this.$el).closest('#rxSection_{{$formID}}').find('[name="data"]').val(JSON.stringify({
                                items: payload
                            }));
                        },
                        deep: true
                    }
                },
                methods: {
                    onItemChange: function(_index) {
                        let item = this.items[_index], originalItem = originalItems[_index];
                        if(item.type === 'existing' && !!originalItem) {
                            if(item.title !== originalItem.title ||
                                item.strength !== originalItem.strength ||
                                item.frequency !== originalItem.frequency ||
                                item.detail !== originalItem.detail) {
                                item.type = 'updated';
                                item.updated_note_uid = '{{@$note->uid}}';
                            }
                        }
                    },
                    addItem: function(_type) {
                        let self = this;
                        this.items.push({
                            type: _type,
                            title: '',
                            strength: '',
                            frequency: '',
                            detail: '',
                            is_currently_active: true,
                            notes: [
                                {
                                    date: '{{@$note ? $note->effective_dateest : date('Y-m-d')}}',
                                    text: '',
                                }
                            ],
                            created_note_uid: '{{@$note->uid}}',
                            updated_note_uid: '{{@$note->uid}}',
                        });
                        Vue.nextTick(function() {
                            self.initRTE();
                            self.initRxAutoSuggest();
                            $('.canvas-rx-title').last().focus();
                        });
                    },
                    removeItem: function(_index) {
                        this.items.splice(_index, 1);
                        {{--let item = this.items[_index];--}}
                        {{--if(item.type === 'prescribed today') {--}}
                        {{--    this.items.splice(_index, 1);--}}
                        {{--}--}}
                        {{--else if(item.type === 'existing') {--}}
                        {{--    if(!(item.notes[item.notes.length - 1].text)) {--}}
                        {{--        alert('Please provide reason for removal/discontinuing.');--}}
                        {{--        return false;--}}
                        {{--    }--}}
                        {{--    item.type = 'removed';--}}
                        {{--    item.removed_note_uid = '{{@$note->uid}}';--}}
                        {{--}--}}
                    },
                    cleanArray: function(_source) {
                        let plItems = [], plObject = {};
                        for (let x=0; x<_source.length; x++) {
                            plObject = {};
                            for (let y in _source[x]) {
                                if(_source[x].hasOwnProperty(y)) {
                                    plObject[y] = _source[x][y];
                                }
                            }
                            plItems.push(plObject);
                        }
                        return plItems;
                    },
                    initRTE: function() {
                        let self = this;
                        $('#rxSection_{{$formID}} textarea[rx-rte]').each(function() {

                            $(this).wrap(
                                $('<div class="rte-holder"/>')
                                    .attr('data-shortcuts', '')
                            );

                            // give a unique id to this editor instance
                            var editorID = Math.ceil(Math.random() * 99999);

                            $('<div data-editor-id="' + editorID + '" data-field="' + this.name + '"/>')
                                .html(this.value)
                                .insertBefore(this);

                            let vueField = $(this).attr('data-field'), vueIndex = +$(this).attr('data-index');

                            $(this).remove();

                            var qe = new Quill('[data-editor-id="' + editorID + '"]', {
                                theme: 'snow',
                                modules: stagQuillConfig
                            });

                            var toolbar = $(qe.container).prev('.ql-toolbar');

                            // add button for new shortcut
                            var newSCButton = $('<button type="button" tabindex="-1" ' +
                                'class="btn bg-white btn-sm btn-default text-primary w-auto px-2 border py-0 ' +
                                'text-sm add-shortcut" data-editor-id="' + editorID + '">+ Shortcut</button>');
                            toolbar.append(newSCButton);

                            qe.on('text-change', function() {
                                self.items[vueIndex][vueField] = qe.root.innerHTML;
                                self.onItemChange(vueIndex);
                            });

                            $(qe.container)
                                .find('.ql-editor[contenteditable]')
                                .attr('data-editor-id', editorID)
                                .attr('with-shortcuts', 1);

                        });
                    },
                    initRxAutoSuggest: function() {
                        let self = this;
                        $('#rxSection_{{$formID}} input[type="text"][data-field="title"]:not([ac-initialized])').each(function() {
                            let elem = this,
                                randPart = Math.ceil(Math.random() * 1000000),
                                dynID = 'rx-' + randPart,
                                vueIndex = $(this).attr('data-index');
                            $(elem).attr('id', dynID);
                            var strengthElem = $(elem).closest('tr').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();
                                if(acData[0].code) {
                                    self.items[vueIndex].title = acData[0].code;
                                    self.onItemChange(vueIndex);
                                }
                                var strengths = acData[0].data['STRENGTHS_AND_FORMS'];
                                if (strengths) {
                                    strengthElem.autocomp.setListAndField(strengths, '');
                                }
                            });
                            window.Def.Autocompleter.Event.observeListSelections(dynStrengthsID, function() {
                                var autocomp = elem.autocomp, acData = autocomp.getSelectedItemData();
                                self.items[vueIndex].strength = $(strengthElem).val();
                                self.onItemChange(vueIndex);
                            });
                            $(elem).attr('ac-initialized', 1);
                            $(strengthElem).attr('ac-initialized', 1);

                            // if medication already filled, fetch and set strenths autocomplete
                            if($.trim($(this).val()) !== '') {
                                $.get('https://clinicaltables.nlm.nih.gov/api/rxterms/v3/search?' +
                                    'terms=' + encodeURIComponent($.trim($(this).val())) +
                                    '&maxList=1' +
                                    '&ef=STRENGTHS_AND_FORMS', _data => {
                                    if(_data && _data.length >= 1 && _data[2].STRENGTHS_AND_FORMS && _data[2].STRENGTHS_AND_FORMS[0]) {
                                        strengthElem.autocomp.setListAndField(_data[2].STRENGTHS_AND_FORMS[0], '', true);
                                    }
                                }, 'json');
                            }
                        });
                    },
                    isFavorite: function(_item) {
                        let matches = this.favorites.filter(function(_x) {
                            return _x.data.title === _item.title;
                        });
                        return matches.length ? matches[0].uid : false;
                    },
                    addToFavorites: function(_item) {
                        if(!_item.title || !$.trim(_item.title)) return;
                        if(this.isFavorite(_item)) return;
                        let self = this;
                        $.post('/api/proFavorite/create', {
                            proUid: '{{$pro->uid}}',
                            category: 'rx',
                            data: JSON.stringify(_item)
                        }, function(_data) {
                            if(_data && _data.success) {
                                self.favorites.push({
                                    uid: _data.data,
                                    category: 'rx',
                                    data: _item
                                });
                                toastr.success('Added to favorites');
                            }
                            else {
                                if(_data && _data.message) {
                                    toastr.error(_data.message);
                                }
                                else {
                                    toastr.error('Unable to add item to favorites');
                                }
                            }
                        }, 'json');
                    },
                    removeFromFavorites: function(_item) {
                        let uid = this.isFavorite(_item);
                        if(!uid) return;
                        let self = this;
                        $.post('/api/proFavorite/remove', {
                            uid: uid
                        }, function(_data) {
                            if(_data && _data.success) {
                                self.favorites = self.favorites.filter(function (_x) {
                                    return _x.uid !== uid;
                                });
                                toastr.success('Removed from favorites');
                            }
                            else {
                                if(_data && _data.message) {
                                    toastr.error(_data.message);
                                }
                                else {
                                    toastr.error('Unable to remove item from favorites');
                                }
                            }
                        }, 'json');
                    },
                    addFromFavorite: function(_favorite) {
                        if(this.isFavoriteAdded(_favorite)) {
                            for (let i = 0; i < this.items.length; i++) {
                                if(this.items[i].title === _favorite.data.title) {
                                    this.items.splice(i, 1);
                                    return;
                                }
                            }
                            return;
                        }
                        let item = _favorite.data;
                        if(!this.items.length) {
                            this.items.push(item);
                        }
                        else {
                            let lastItem = this.items[this.items.length - 1];
                            if(!lastItem.title) {
                                this.items.splice(this.items.length - 1, 1, item);
                            }
                            else {
                                this.items.push(item);
                            }
                        }
                        let self = this;
                        Vue.nextTick(function() {
                            self.initRTE();
                            self.initRxAutoSuggest();
                        });
                    },
                    isFavoriteAdded: function(_favorite) {
                        let matches = this.items.filter(function(_x) {
                            return _x.title === _favorite.data.title;
                        });
                        return matches.length > 0;
                    }
                }
            });
        }
        addMCInitializer('client-rx{{$formID}}', init, '#rxSection_{{$formID}}');
    })();
</script>
