<?php

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

if(!$contentData) $contentData = [];
if( !isset($contentData) ||
    !isset($contentData['current_cch']) ||
    !isset($contentData['current_cch']['list']) ||
    !count($contentData['current_cch']['list'])) {
    $contentData = [
        "current_cch" => [
            "list" => [
                [
                    "category" => '',
                    "name" => '',
                    "icd" => '',
                    "memo" => '',
                    "hpi" => [
                        "free_text" => ''
                    ],
                ]
            ]
        ]
    ];
}

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

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

    <div class="mt-3 mb-2">
        <span class="font-weight-bold">CC</span>
        <a href="#" class="ml-3"
                v-on:click.prevent="addItem()"
        >+ Add</a>
    </div>

    <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">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['current_cch']['list'].length > 1" class="px-2 text-secondary border-bottom-0"></th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(item, index) in data['current_cch']['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" data-field="title"
                       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" required>
            </td>
            <td>
                <input type="text" :data-index="index"
                       class="form-control form-control-sm"
                       v-model="item.memo">
            </td>
            <td v-if="data['current_cch']['list'].length > 1" class="px-2 text-nowrap">
                <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>

    <p class="font-weight-bold mt-3 mb-2">HPI</p>

    <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">Issue</th>
            <th class="px-2 text-secondary border-bottom-0 w-75">HPI</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(item, index) in data['current_cch']['list']">
            <td class="align-middle px-2">
                @{{ item.category }}@{{ item.name ? ' / ' + item.name : '' }}@{{ item.icd ? ' / ' + item.icd : '' }}
            </td>
            <td>
                <input type="text" :data-index="index"
                       class="form-control form-control-sm"
                       v-model="item.hpi.free_text" required>
            </td>
        </tr>
        </tbody>
    </table>

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