<?php
if(!isset($contentData['items'])){
    $contentData['items'] = [];
}
if(!is_array($contentData['items'])){
    $contentData['items'] = [];
}
if(!$contentData || !isset($contentData['items']) || !count($contentData['items'])) {
    $contentData = [
        "items" => [
            [
                "title" => "",
                "icd" => "",
                "coa" => "Chronic",
                "detail" => "",
                "plan" => "",
            ]
        ]
    ];
}

$formID = rand(0, 100000);
?>
<div id="dxSection">
    <h3 class="stag-popup-title mb-2 border-bottom-0 pb-1 hide-if-note">
        <span>Current Problems / Focus Areas</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-50px hide-if-dashboard">
                <label class="d-flex align-items-center c-pointer align-items-end m-0">
                    <input type="checkbox" class="mr-1" tabindex="-1"
                           v-model="includeAll" v-on:change="includeAllChanged()">
                    <span>All</span>
                </label>
            </th>
            <th class="px-2 text-secondary border-bottom-0 w-35">
                <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 min-width-140px">ICD</th>
            <th class="px-2 text-secondary border-bottom-0 w-25">Detail</th>--}}
            <th class="px-2 text-secondary border-bottom-0 w-75">Plan</th>
            <th class="px-2 text-secondary border-bottom-0"></th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(item, index) in items">
            <td class="px-2 pt-2 text-center text-sm font-weight-bold">@{{ index + 1 }}</td>
            <td class="px-2 hide-if-dashboard">
                <label class="d-block c-pointer m-0 pt-1">
                    <input type="checkbox" class="mt-1" tabindex="-1"
                           v-model="inclusion[index]"
                           v-on:change="includeChanged()">
                </label>
            </td>
            <td>
                <input type="text" :data-index="index"
                       class="form-control form-control-sm font-weight-bold font-size-14"
                       data-field="title" placeholder="Title" v-model="item.title" autofocus required>
                <div class="d-flex">
                    <input type="text" :data-index="index"
                           class="form-control form-control-sm canvas-dx-title"
                           data-field="icd" placeholder="ICD" v-model="item.icd">
                    <select v-model="item.coa" class="form-control form-control-sm pl-1 border-left" required>
                        <option value="">-- select --</option>
                        <option value="Chronic" selected>Chronic</option>
                        <option value="Acute">Acute</option>
                    </select>
                </div>
                <textarea type="text" class="form-control form-control-sm" v-model="item.detail" placeholder="Detail"></textarea>
            </td>
            {{--<td>
                <input type="text" :data-index="index"
                       class="form-control form-control-sm canvas-dx-title"
                       data-field="icd" placeholder="ICD" v-model="item.icd">
                <select v-model="item.coa" class="form-control form-control-sm pl-1" required>
                    <option value="">-- select --</option>
                    <option value="Chronic" selected>Chronic</option>
                    <option value="Acute">Acute</option>
                </select>
            </td>
            <td><textarea type="text" class="form-control form-control-sm"
                          dx-rte :data-index="index" data-field="detail"
                          v-model="item.detail"></textarea>
            </td>--}}
            <td><textarea type="text" class="form-control form-control-sm"
                          dx-rte :data-index="index" data-field="plan"
                          v-model="item.plan"></textarea>
            </td>
            <td class="px-2 text-nowrap">
                <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>
            </td>
        </tr>
        </tbody>
    </table>

    <div class="form-group my-2">
    <button type="button" class="btn btn-sm btn-default text-primary border border-primary mr-2"
            v-on:click.prevent="addItem()"
    >+ New Entry</button>
    </div>

    <div class="assessment-detail-template">
        <?php $sectionInternalName = 'plan'; ?>
        @include('app/patient/note/_templates-index')
    </div>

</div>
<script>
    (function() {
        let favorites = <?= json_encode($pro->favoritesByCategory('dx')) ?>;
        for (let i = 0; i < favorites.length; i++) {
            favorites[i].data = JSON.parse(favorites[i].data);
        }
        function init() {
            window.clientDXApp = new Vue({
                el: '#dxSection',
                data: {
                    includeAll: false,
                    items: <?= json_encode($contentData['items']) ?>,
                    inclusion: [],
                    favorites: favorites,
                },
                mounted: function() {
                    this.inclusion = [];
                    for (let i = 0; i < this.items.length; i++) {
                        this.inclusion[i] = this.items[i].included;
                    }
                    this.initRTE();
                    this.initTitleAutoSuggest();
                    $('#dxSection [moe][initialized]').removeAttr('initialized');
                    initMoes();
                    this.includeChanged();
                },
                watch: {
                    items: {
                        handler: function(val, oldVal) {
                            $(this.$el).closest('#dxSection').find('[name="data"]').val(JSON.stringify({
                                items: this.cleanArray(this.items)
                            }));
                        },
                        deep: true
                    },
                    inclusion: {
                        handler: function(val, oldVal) {
                            $(this.$el).closest('#dxSection').find('[name="data"]').val(JSON.stringify({
                                items: this.cleanArray(this.items)
                            }));
                        },
                        deep: true
                    }
                },
                methods: {
                    includeAllChanged: function() {
                        for (let i = 0; i < this.items.length; i++) {
                            this.inclusion[i] = this.includeAll; // NOTE: this does not trigger a watch event
                        }
                        $('#dxSection').find('[name="data"]').val(JSON.stringify({ // trigger mutation on select-all
                            items: this.cleanArray(this.items)
                        }));
                    },
                    includeChanged: function() {
                        let all = true;
                        for (let i = 0; i < this.items.length; i++) {
                            if(!this.inclusion[i]) {
                                all = false;
                                break;
                            }
                        }
                        this.includeAll = all;
                    },
                    addItem: function() {
                        let self = this;
                        this.items.push({
                            title: '',
                            icd: '',
                            coa: 'Chronic',
                            detail: '',
                            plan: '',
                        });
                        this.inclusion.push(true);
                        Vue.nextTick(function() {
                            self.initRTE();
                            self.initTitleAutoSuggest();
                            $('.canvas-dx-title').last().focus();
                        });
                    },
                    removeItem: function(_index) {
                        this.items.splice(_index, 1);
                        this.inclusion.splice(_index, 1);
                    },
                    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];
                                }
                            }
                            plObject.included = this.inclusion[x];
                            plItems.push(plObject);
                        }
                        return plItems;
                    },
                    initRTE: function() {
                        let self = this;
                        $('#dxSection textarea[dx-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');

                            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);

                            // add button for templates
                            var templatesButton = $('<button type="button" tabindex="-1" ' +
                                'class="position-relative note-templates-trigger-assessment btn bg-white btn-sm btn-default text-primary w-auto px-2 border py-0 ml-1 ' +
                                'text-sm show-templates">Templates</button>');
                            templatesButton.attr('data-editor-id', editorID);
                            toolbar.append(templatesButton);
                            // $(this).closest('tr').find('.assessment-detail-template').appendTo(templatesButton);

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

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

                            $(this).remove();

                        });
                    },
                    initICDAutoSuggest: function() {
                        let self = this;
                        $('#dxSection 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();
                                self.items[vueIndex].icd = acData[0].code;
                                self.items[vueIndex].title = acData[0].data['name'];
                                return false;
                            });
                            $(elem).attr('ac-initialized', 1);
                        });
                    },
                    initTitleAutoSuggest: function() {
                        let self = this;
                        $('#dxSection input[type="text"][data-field="title"]:not([ac-initialized])').each(function() {
                            var elem = this,
                                dynID = 'title-' + 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: [1],
                                    colHeaders: ['Code', 'Name'],
                                }
                            );
                            window.Def.Autocompleter.Event.observeListSelections(dynID, function() {
                                let autocomp = elem.autocomp, acData = autocomp.getSelectedItemData();
                                self.items[vueIndex].icd = acData[0].code;
                                self.items[vueIndex].title = acData[0].data['name'];
                                return false;
                            });
                            $(elem).attr('ac-initialized', 1);
                        });
                    },
                    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: 'dx',
                            data: JSON.stringify(_item)
                        }, function(_data) {
                            if(_data && _data.success) {
                                self.favorites.push({
                                    uid: _data.data,
                                    category: 'dx',
                                    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;
                        item.included = true; // default to included
                        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.initTitleAutoSuggest();
                        });
                    },
                    isFavoriteAdded: function(_favorite) {
                        let matches = this.items.filter(function(_x) {
                            return _x.title === _favorite.data.title;
                        });
                        return matches.length > 0;
                    }
                }
            });
        }
        addMCInitializer('client-dx', init, '#dxSection');
    })();
</script>
