<?php
$vitalLabels = [
    "heightInInches" => "Ht. (in.)",
    "weightPounds" => "Wt. (lbs.)",
    "temperatureF" => "Temp. (F)",
    "systolicBP" => "SBP",
    "diastolicBP" => "DBP",
    "pulseRatePerMinute" => "Pulse",
    "respirationRatePerMinute" => "Resp.",
    "pulseOx" => "Pulse Ox.",
    "smokingStatus" => "Smoking Status",
    "bmi" => "BMI (kg/m²)",
];
if(!$contentData) {
    $contentData = [
        "heightInInches" => [
            "label" => "Ht. (in.)",
            "value" => "",
            "date" => "",
        ],
        "weightPounds" => [
            "label" => "Wt. (lbs.)",
            "value" => "",
            "date" => "",
        ],
        "temperatureF" => [
            "label" => "Temp. (F)",
            "value" => "",
            "date" => "",
        ],
        "systolicBP" => [
            "label" => "SBP",
            "value" => "",
            "date" => "",
        ],
        "diastolicBP" => [
            "label" => "DBP",
            "value" => "",
            "date" => "",
        ],
        "pulseRatePerMinute" => [
            "label" => "Pulse",
            "value" => "",
            "date" => "",
        ],
        "respirationRatePerMinute" => [
            "label" => "Resp.",
            "value" => "",
            "date" => "",
        ],
        "pulseOx" => [
            "label" => "Pulse Ox.",
            "value" => "",
            "date" => "",
        ],
        "smokingStatus" => [
            "label" => "Smoking Status",
            "value" => "",
            "date" => "",
        ],
        "bmi" => [
            "label" => "BMI (kg/m²)",
            "value" => "",
            "date" => "",
        ],
    ];
}
else {
    // ensure $contentData has all the expected vitals and correct labels!
    foreach ($vitalLabels as $k => $v) {
        if(!isset($contentData[$k])) {
            $contentData[$k] = [
                "label" => $v,
                "value" => "",
                "date" => "",
            ];
        }
    }
}

$formID = rand(0, 100000);
?>
<div id="vitalsSection">
    <h3 class="stag-popup-title mb-2 border-bottom-0 pb-1 hide-if-note">
        <span>Vitals</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)}}">

    <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 w-25">Vital</th>
            <th class="px-2 text-secondary border-bottom-0 w-35">Value</th>
            <th class="px-2 text-secondary border-bottom-0">Date</th>
        </tr>
        </thead>
        <tbody>
        @foreach($vitalLabels as $k => $v)
            <tr>
                <td>
                    <input type="text" tabindex="-1"
                           class="form-control form-control-sm events-none"
                           data-field="title" value="{{ $v }}" readonly>
                </td>
                <td class="position-relative">
                    @if($k === "bmi")
                        <input type="text" readonly
                               class="form-control form-control-sm vitals-title"
                               data-field="value" v-model="bmi">
                        <p class="py-1 m-0 px-2 font-weight-bold bg-white" v-if="!!bmi">
                            <span class="text-sm text-warning-mellow" v-if="+bmi < 18.5">Underweight</span>
                            <span class="text-sm text-success" v-if="+bmi >= 18.5 && +bmi < 25">Healthy Weight</span>
                            <span class="text-sm text-warning-mellow" v-if="+bmi >= 25 && +bmi < 30">Overweight</span>
                            <span class="text-sm text-warning-mellow" v-if="+bmi >= 30">Obese</span>
                        </p>
                    @elseif($k === "smokingStatus")
                        <input type="text"
                               class="form-control form-control-sm"
                               data-field="value" v-model="items['smokingStatus'].value"
                               data-option-list="smokingStatus"
                               v-on:change="autoDate(items['smokingStatus'], 'smokingStatus')" v-on:keyup="autoDate(items['smokingStatus'], 'smokingStatus')">
                        <div id="smoking-status-options" class="data-option-list">
                            <div>Current</div>
                            <div>Former</div>
                            <div>Never</div>
                        </div>
                    @else
                        <input type="text"
                               class="form-control form-control-sm"
                               data-field="value" v-model="items['{{ $k }}'].value"
                               v-on:change="autoDate(items['{{ $k }}'], '{{ $k }}')" v-on:keyup="autoDate(items['{{ $k }}'], '{{ $k }}')">
                    @endif
                </td>
                <td>
                    <input type="date" {{ $k === 'bmi' ? 'readonly' : '' }}
                           class="form-control form-control-sm vitals-title"
                           data-field="date" v-model="items['{{ $k }}'].date">
                </td>
            </tr>
        @endforeach

        {{--<tr v-for="(item, index) in items">
            <td>
                <input type="text" :data-index="index" tabindex="-1"
                       class="form-control form-control-sm events-none"
                       data-field="title" v-model="item.label" readonly>
            </td>
            <td class="position-relative">
                <input type="text" :data-index="index" v-if="index !== 'bmi'"
                       class="form-control form-control-sm"
                       data-field="value" v-model="item.value"
                       :data-option-list="index === 'smokingStatus'"
                       v-on:change="autoDate(item, index)" v-on:keyup="autoDate(item, index)">
                <div id="smoking-status-options" class="data-option-list">
                    <div>Current</div>
                    <div>Former</div>
                    <div>Never</div>
                </div>
                <input type="text" :data-index="index" v-if="index === 'bmi'" readonly
                       class="form-control form-control-sm vitals-title"
                       data-field="value" v-model="bmi">
                <p class="py-1 m-0 px-2 font-weight-bold bg-white" v-if="index === 'bmi' && !!bmi">
                    <span class="text-sm text-warning-mellow" v-if="+bmi < 18.5">Underweight</span>
                    <span class="text-sm text-success" v-if="+bmi >= 18.5 && +bmi < 25">Healthy Weight</span>
                    <span class="text-sm text-warning-mellow" v-if="+bmi >= 25 && +bmi < 30">Overweight</span>
                    <span class="text-sm text-warning-mellow" v-if="+bmi >= 30">Obese</span>
                </p>
            </td>
            <td>
                <input type="date" :data-index="index" :readonly="index === 'bmi'"
                       class="form-control form-control-sm vitals-title"
                       data-field="date" v-model="item.date">
            </td>
        </tr>--}}
        </tbody>
    </table>
</div>
<script>
    (function() {
        function init() {
            window.clientVitalsApp = new Vue({
                el: '#vitalsSection',
                data: {
                    today: '{{ date("Y-m-d") }}',
                    items: <?= json_encode($contentData) ?>,
                    itemsOriginal: <?= json_encode($contentData) ?>
                },
                mounted: function() {
                    $(this.$el).closest('#vitalsSection').find('[name="data"]').val(
                        JSON.stringify(this.cleanObject(this.items))
                    );
                },
                watch: {
                    items: {
                        handler: function(val, oldVal) {
                            $(this.$el).closest('#vitalsSection').find('[name="data"]').val(
                                JSON.stringify(this.cleanObject(this.items))
                            );
                        },
                        deep: true
                    },
                },
                computed: {
                    bmi: function () {
                        let result = '';
                        let h = this.items.heightInInches, w = this.items.weightPounds;
                        if(!h || !w) {
                            return result;
                        }
                        h = h.value;
                        w = w.value;
                        try {
                            h = parseFloat(h);
                            w = parseFloat(w);
                            if(!h || !w) {
                                this.items.bmi.value = '';
                                return result;
                            }
                            let result = (w / [ h * h]) * 703;
                            return result.toFixed(1);
                        }
                        catch (e) {
                            return result;
                        }
                    }
                },
                methods: {
                    autoDate: function(_item, _index) {
                        console.log('ALIX autoDate for', _index)
                        if((_item.value !== this.itemsOriginal[_index].value) && !_item.date) {
                            _item.date = this.today;
                        }
                    },
                    cleanObject: function(_source) {
                        let plObject = {};
                        for (let y in _source) {
                            if(_source.hasOwnProperty(y)) {
                                plObject[y] = _source[y];
                            }
                        }
                        plObject.bmi = {
                            label: "BMI (kg/m²)",
                            value: this.bmi,
                            date: this.bmi ? this.today : '',
                        };
                        return plObject;
                    }
                }
            });
        }
        addMCInitializer('client-vitals', init, '#vitalsSection');
    })();
</script>
