<?php
$fields = [
    [
        "" => ["Aneurysm repair", "Appendectomy", "Back surgery", "Bariatric surgery/gastric bypass", "Bilateral tubal ligation", "Breast resection/mastectomy", "CABG", "Carotid endarterectomy/stent", "Carpal tunnel release surgery",]
    ],
    [
        "" => ["Cataract/lens surgery", "Cesarean section", "Cholecystectomy/bile duct surgery", "Dilation and curettage", "Hemorrhoid surgery", "Hip arthroplasty", "Hip replacement", "Hysterectomy", "Inguinal hernia repair",]
    ],
    [
        "" => ["Knee arthroplasty", "LASIK", "Laminectomy", "Nasal surgery", "PTCA/PCI", "Pacemaker/defibrillator", "Prostate surgery", "Prostatectomy", "Rotator cuff surgery",]
    ],
    [
        "" => ["Sinus surgery", "Skin cancer excision", "Spinal fusion", "TAH-BSO", "TURP", "Tonsillectomy/Adenoidectomy", "Vasectomy",]
    ]
];

$customFields = $pro->canvasCustomItems('pshx');
$customFields = array_map(function($_item) {
    return $_item['label'];
}, $customFields->toArray());

if(!$contentData) {
    $contentData = [
        "common" => [],
        "custom" => [],
        "comments" => "",
    ];
}

$formID = rand(0, 100000);
?>
<div id="pshxSection">
    <input type="hidden" name="data" value="{{json_encode($contentData)}}">
    <div class="row">
        <div class="col-12">
            <div class="font-weight-bold my-1">Common Surgeries</div>
        </div>
    </div>

    <div class="row">
        @for ($i = 0; $i < count($fields); $i++)
            <div class="col-md-3">
                @foreach($fields[$i] as $head => $values)
                    <div class="font-weight-bold mb-2">{{ $head }}</div>
                    <div class="mb-3">
                        @for($k = 0; $k < count($values); $k++)
                            <?php $fName = $head . '_' . sanitize_field_name($values[$k]); ?>
                            <?php
                            if(!isset($contentData[$fName])) {
                                $contentData[$fName] = false;
                                $contentData[$fName . '__comments'] = '';
                            }
                            ?>
                            <label class="d-flex align-items-center mb-1">
                                <input type="checkbox" name="{{ $fName }}" class="m-0"
                                       v-model="common['{{$fName}}']">
                                <span class="mx-2">{{ $values[$k] }}</span>
                                <div moe>
                                    <a href="#" start show>
                                        <i v-show="common['{{$fName}}']" class="fa-comment" :class="common['{{$fName}}__comments'] ? 'fas' : 'far'"></i>
                                    </a>
                                    <div url="/nop">
                                        <div class="mb-2">
                                            <textarea class="form-control form-control-sm ns-custom-comment"
                                                      v-model="common['{{$fName}}__comments']"></textarea>
                                        </div>
                                        <div class="">
                                            <button type="button" class="btn btn-sm btn-primary" cancel>Close
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </label>
                        @endfor
                    </div>
                @endforeach
            </div>
        @endfor
    </div>

    <div class="row border-top pt-3">
        <div class="col-12">
            <div class="d-flex align-items-center mb-2">
                <span class="font-weight-bold">Custom Items</span>
                <span class="mx-2 text-secondary">|</span>
                <div moe>
                    <a href="#" start show>Add</a>
                    <div custom-item-form url="/api/sectionTemplateCustomItem/create">
                        <div class="mb-2">
                            <input type="text" placeholder="Label"
                                   v-model="newCustomItemLabel"
                                   class="form-control form-control-sm label_new_custom_item">
                        </div>
                        <div>
                            <button type="button" class="btn btn-sm btn-primary mr-1"
                                    v-on:click.prevent="saveCustomItem(newCustomItemLabel)">Submit</button>
                            <button type="button" class="btn btn-sm btn-default border"
                                    v-on:click.prevent="cancelCustomItem()">Cancel</button>
                        </div>
                    </div>
                </div>
            </div>

            {{-- custom items --}}
            <div class="d-flex align-items-start flex-wrap custom-items-container">
                <div class="w-25" v-for="item in customFields">
                    <label class="d-flex align-items-center mb-1">
                        <input type="checkbox" class="m-0"
                               v-model="item.value">
                        <span class="mx-2">@{{ item.label }}</span>
                        <div moe>
                            <a href="#" start show>
                                <i v-show="item.value" class="fa-comment" :class="item.comments ? 'fas' : 'far'"></i>
                            </a>
                            <div url="/nop">
                                <div class="mb-2">
                                    <textarea class="form-control form-control-sm ns-custom-comment" v-model="item.comments"></textarea>
                                </div>
                                <div class="">
                                    <button type="button" class="btn btn-sm btn-primary" cancel>Close</button>
                                </div>
                            </div>
                        </div>
                    </label>
                </div>
            </div>

        </div>
    </div>

    <div class="row mb-3">
        <div class="col-12">
            <textarea type="text" class="form-control form-control-sm p-2 mt-2" v-model="comments" placeholder="Comments"></textarea>
        </div>
    </div>

</div>
<script>
    (function() {
        let model = <?= json_encode($contentData) ?>;
        model.newCustomItemLabel = '';
        let customFields = <?= json_encode($customFields) ?>;
        if(!model.customFields) {
            model.customFields = [];
        }
        for (let i = 0; i < customFields.length; i++) {
            let found = model.customFields.filter(function(_item) {
                return _item.label === customFields[i];
            }).length;
            if(!found) {
                model.customFields.push({
                    label: customFields[i],
                    value: '',
                    comments: '',
                })
            }
        }

        function init() {
            window.clientPSHXApp = new Vue({
                el: '#pshxSection',
                data: model,
                mounted: function () {
                    $('#pshxSection [moe][initialized]').removeAttr('initialized');
                    initMoes();
                },
                watch: {
                    $data: {
                        handler: function(val, oldVal) {
                            $(this.$el).closest('#pshxSection').find('[name="data"]').val(JSON.stringify({
                                common: this.cleanObject(this.common),
                                customFields: this.customFields,
                                comments: this.comments,
                            }));
                        },
                        deep: true
                    }
                },
                methods: {
                    cleanObject: function(_source) {
                        let plObject = {};
                        for (let y in _source) {
                            if(_source.hasOwnProperty(y)) {
                                plObject[y] = _source[y];
                            }
                        }
                        return plObject;
                    },
                    saveCustomItem: function(_label) {
                        if(!_label) return false;
                        showMask();
                        let self = this;
                        $.post('/api/clientCanvasCustomItem/create', {
                            proUid: '{{ $pro->uid }}',
                            key: 'pshx',
                            label: _label
                        }, function(_data) {
                            hideMask();
                            if(_data && _data.success) {
                                self.appendCustomItem(_label);
                                hideMoeFormMask();
                                $('[custom-item-form]').hide();
                            }
                            else {
                                toastr.error(_data.message);
                            }
                        }, 'json');
                        return false;
                    },
                    cancelCustomItem: function() {
                        hideMoeFormMask();
                        $('div[moe]').hide();
                        return false;
                    },
                    appendCustomItem: function(_name) {
                        this.customFields.push({
                            label: _name,
                            value: '',
                            comments: '',
                        });
                        Vue.nextTick(function() {
                            $('.custom-items-container [moe][initialized]').removeAttr('initialized');
                            initMoes();
                        });
                    }
                }
            });
        }
        addMCInitializer('client-pshx', init, '#pshxSection');
    })();
</script>
