<?php

// $contentData is already pro-scoped by this point!

if(!$contentData) {
    $contentData = [
        "next_fu" => [
            "active" => true,
            "date" => null
        ],
        "next_cc" => [
            "list" => [
                [
                    "category" => 'follow-up',
                    "name" => 'Follow Up on Plan & Progress, Safety Monitoring',
                ]
            ]
        ]
    ];
}

$formID = rand(0, 100000);
?>

<div id="next_fuSection_{{$formID}}">
    <h3 class="stag-popup-title mb-2 border-bottom pb-1 hide-if-note pt-1 pb-2">
        <span>Follow-up Appointment</span>
        <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)}}">

    <p class="font-weight-bold">
        <label class="m-0 d-flex align-items-center">
            <span class="mr-2">Follow-up Appointment</span>
            <input type="checkbox" v-model="data['next_fu']['active']">
        </label>
    </p>

    <label v-if="data['next_fu']['active']" class="d-flex align-items-center">
        <span class="mr-2">Follow Up Date</span>
        <input type="date" v-model="data['next_fu']['date']">
        <a v-if="data['next_fu']['active'] && !!data['next_fu']['date']" native target="_blank" href="{{route('patients.view.calendar', ['patient' => $patient])}}" class="ml-3">
            <i class="fa fa-calendar-alt"></i>
            Patient Calendar
        </a>
    </label>

    <div v-if="data['next_fu']['active']" class="">
        <div class="mb-2">
            <span class="font-weight-bold">Next CC</span>
            <a href="#" class="ml-3"
               v-on:click.prevent="addNextCCItem()"
            >+ Add</a>
        </div>
        <table class="table table-sm table-bordered 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">Category</th>
                <th class="px-2 text-secondary border-bottom-0">Title</th>
                <th class="px-2 text-secondary border-bottom-0">ICD</th>
                <th class="px-2 text-secondary border-bottom-0 w-35">Memo</th>
                <th v-if="data['next_cc']['list'].length > 1" class="px-2 text-secondary border-bottom-0"></th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(item, index) in data['next_cc']['list']">
                <td class="px-2 pt-2 text-center text-sm font-weight-bold">@{{ index + 1 }}</td>
                <td>
                    <select class="form-control form-control-sm" v-model="item.category" required>
                        <option value="dx">Dx</option>
                        <option value="symptom">Symptom</option>
                        <option value="goal">Goal</option>
                        <option value="follow-up">Follow-Up</option>
                    </select>
                </td>
                <td>
                    <input type="text" :data-index="index"
                           class="form-control form-control-sm"
                           v-model="item.name" required>
                </td>
                <td>
                    <input type="text" :data-index="index" data-field="icd"
                           class="form-control form-control-sm"
                           v-model="item.icd">
                </td>
                <td>
                    <input type="text" :data-index="index"
                           class="form-control form-control-sm"
                           v-model="item.memo">
                </td>
                <td v-if="data['next_cc']['list'].length > 1" class="px-2 text-nowrap">
                    <a href="#" v-on:click.prevent="removeNextCCItem(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>

</div>
<script>
    (function() {
        function init() {
            window.clientNextFUApp_{{$formID}} = new Vue({
                el: '#next_fuSection_{{$formID}}',
                data: {
                    data: <?= json_encode($contentData) ?>,
                },
                mounted: function() {
                    $('#next_fuSection_{{$formID}} [moe][initialized]').removeAttr('initialized');
                    initMoes();
                    this.initICDAutoSuggest();
                },
                watch: {
                    $data: {
                        handler: function(val, oldVal) {
                            $(this.$el).closest('#next_fuSection_{{$formID}}').find('[name="data"]').val(JSON.stringify(this.data));
                        },
                        deep: true
                    }
                },
                methods: {
                    addNextCCItem: function() {
                        this.data['next_cc']['list'].push({
                            "category": '',
                            "name": '',
                            "icd": '',
                            "memo": '',
                        });
                        Vue.nextTick(() => {
                            this.initICDAutoSuggest();
                        });
                    },
                    removeNextCCItem: function(_index) {
                        this.data['next_cc']['list'].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];
                                }
                            }
                            plItems.push(plObject);
                        }
                        return plItems;
                    },
                    initICDAutoSuggest: function() {
                        let self = this;
                        $('#next_fuSection_{{$formID}} 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.data['next_cc']['list'][vueIndex].icd = acData[0].code;
                                self.data['next_cc']['list'][vueIndex].memo = acData[0].data['name'];
                                return false;
                            });
                            $(elem).attr('ac-initialized', 1);
                        });
                    },
                }
            });
        }
        addMCInitializer('client-next_fu{{$formID}}', init, '#next_fuSection_{{$formID}}');
    })();
</script>
