<?php
if(!@$sessionKey) {
    $sessionKey = request()->cookie('sessionKey');
}
$point = App\Models\Point::getOrCreateOnlyTopLevelPointOfCategory($note, 'VITALS', $sessionKey, true);
$vitalLabels = [
    "heightInInches" => "Ht. (in.)",
    "weightPounds" => "Wt. (lbs.)",
    "bmi" => "BMI (kg/m²)",
    "temperatureF" => "Temp. (F)",
    "systolicBP" => "SBP",
    "diastolicBP" => "DBP",
    "pulseRatePerMinute" => "Pulse",
    "respirationRatePerMinute" => "Resp.",
    "pulseOx" => "Pulse Ox.",
    "smokingStatus" => "Smoking Status",
    "pain" => "Pain",
];
$contentData = null;
if ($point->lastChildReview && $point->lastChildReview->note->id === $note->id && $point->lastChildReview->data) {
    $point->lastChildReview->data = json_decode($point->lastChildReview->data, true);
    $contentData = $point->lastChildReview->data;
}

if(!$contentData) {
    $contentData = [
        "date" => $note->effective_dateest,
        "heightInInches" => '',
        "weightPounds" => '',
        "bmi" => '',
        "temperatureF" => '',
        "systolicBP" => '',
        "diastolicBP" => '',
        "pulseRatePerMinute" => '',
        "respirationRatePerMinute" => '',
        "pulseOx" => '',
        "smokingStatus" => '',
        "pain" => '',
    ];
}else {
    if(!isset($contentData['date'])) $contentData['date'] = $note->effective_dateest;
    foreach ($vitalLabels as $k => $v) {
        if (!isset($contentData[$k]) || is_array($contentData[$k])) {
            $contentData[$k] = '';
        }
    }
}

$previousVitals = [];

$previousVitals = \App\Models\Point::where('parent_point_id', $point->id)
    ->where('category', 'REVIEW')
    ->where('added_in_note_id', '<', $note->id)
    ->orderBy('id', 'DESC')
    ->limit(4)
    ->get();

// convert to new format
$previousData = [];
$previousDataAssoc = [];
foreach ($previousVitals as $p) {
    if (!!@$p->data) {
        $parsedP = json_decode($p->data, true);
        $newFormat = [];
        foreach ($vitalLabels as $k => $v) {
            if (isset($parsedP[$k]) && is_array($parsedP[$k]) && isset($parsedP[$k]['value'])) {
                $newFormat[$k] = $parsedP[$k]['value'];
            }
            else if(isset($parsedP[$k]) && !is_array($parsedP[$k])) {
                $newFormat[$k] = $parsedP[$k];
            }
            else {
                $newFormat[$k] = '';
            }
        }
        $newFormat['date'] = $p->note->effective_dateest; // unfriendly_date($p->created_at);
        $previousData[] = $newFormat;
        $previousDataAssoc[$newFormat['date']] = $newFormat; // for easy iter to cols
    }
}

$copyTriggerAdded = [];

if(!@$segment) {
    $segment = $note->coreSegment;
}

?>
<div visit-moe close-on-save close-on-cancel class="d-block">
    <form show url="/api/visitPoint/upsertChildReview" class="mcp-theme-1">
        <input type="hidden" name="uid" value="<?= $point->uid ?>">
        <input type="hidden" name="noteUid" value="<?= $note->uid ?>">
        <input type="hidden" name="segmentUid" value="<?= $segment->uid ?>">
        <input type="hidden" name="category" value="VITALS">
        <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-150px">Vital</th>
                <th class="px-2 text-secondary border-bottom-0 w-25">{{friendly_date($contentData['date'])}}</th>
                @if(!$previousData || !count($previousData))
                    <th class="px-2 text-secondary border-bottom-0">Previous</th>
                @else
                    @foreach($previousData as $pDay)
                        <th class="px-2 text-secondary border-bottom-0 on-hover-opaque position-relative">
                            {{friendly_date($pDay['date'])}}
                        </th>
                    @endforeach
                @endif
            </tr>
            </thead>
            <tbody>
                @foreach($vitalLabels as $k => $v)
                    @if($k !== 'diastolicBP')
                    <tr>
                        <td>
                            <input type="text" tabindex="-1"
                                   class="form-control form-control-sm events-none border-0"
                                   value="{{ $k === 'systolicBP' ? 'Blood Pressure' : ($k === 'heightInInches' ? 'Height' : $v) }}" readonly>
                        </td>
                        <td class="position-relative">
                            @if($k === "bmi")
                                <div class="d-flex align-items-stretch">
                                    <input type="text" readonly bmi
                                           class="form-control form-control-sm vitals-title border-bottom-0 border-top-0 border-left-0 border-right width-70px"
                                           data-name="bmi" value="{{$contentData['bmi']}}">
                                    <div class="flex-grow-1 py-1 m-0 px-2 font-weight-bold bg-light" bmi-category>
                                        @if(isset($contentData['bmi']) && $contentData['bmi'] != "" )
                                            <?php $bmi = $contentData['bmi']; ?>
                                            @if($bmi < 18.5)
                                                <span class="text-sm text-warning-mellow">Underweight</span>
                                            @endif
                                            @if($bmi >= 18.5 && $bmi < 25)
                                                <!--<span class="text-sm text-success">Healthy Weight</span>-->
                                            @endif
                                            @if($bmi >= 25 && $bmi < 30)
                                                <span class="text-sm text-warning-mellow">Overweight</span>
                                            @endif
                                            @if($bmi >= 30)
                                                <span class="text-sm text-warning-mellow">Obese</span>
                                            @endif
                                        @endif
                                    </div>
                                </div>
                            @elseif($k === "smokingStatus")
                                <input type="text"
                                       class="form-control form-control-sm border-0"
                                       data-name="smokingStatus"
                                       placeholder="{{$v}}"
                                       data-option-list="smokingStatus" value="{{$contentData['smokingStatus']}}">
                                <div id="smoking-status-options" class="data-option-list">
                                    <div>Current every day smoker</div>
                                    <div>Former some day smoker</div>
                                    <div>Former smoker</div>
                                    <div>Never smoker</div>
                                    <div>Smoker, current status unknown</div>
                                    <div>Unknown if ever smoked</div>
                                    <div>Heavy tobacco smoker</div>
                                    <div>Light tobacco smoker</div>
                                </div>
                            @elseif($k === 'systolicBP')
                                <div class="d-flex align-items-center bg-white">
                                    <input type="text" class="form-control form-control-sm min-width-unset w-auto-input width-70px border-0 edit"
                                           data-name="systolicBP" systolicBP
                                           value="{{$contentData['systolicBP']}}" placeholder="Systolic">
                                    <span class="px-2 text-secondary bg-white">/</span>
                                    <input type="text" class="form-control form-control-sm min-width-unset w-auto-input width-70px border-0 edit"
                                           data-name="diastolicBP" diastolicBP
                                           value="{{$contentData['diastolicBP']}}" placeholder="Diastolic">
                                </div>
                            @elseif($k === 'heightInInches')
                                <div class="d-flex align-items-center bg-white">
                                    <input type="text" class="form-control form-control-sm min-width-unset w-auto-input width-30px border-0 edit"
                                           heightFeetInput
                                           value="{{feetFromInches($contentData['heightInInches']) ?: ''}}">
                                    <span class="pl-1 pr-2 text-secondary bg-white">ft.</span>
                                    <input type="text" class="form-control form-control-sm min-width-unset w-auto-input width-30px border-0 edit pr-0"
                                           heightInchesInput
                                           value="{{inchesAfterFeetFromInches($contentData['heightInInches']) ?: ''}}">
                                    <span class="pl-1 text-secondary bg-white">in.</span>
                                    <input type="hidden" data-name="heightInInches" value="{{$contentData['heightInInches']}}">
                                </div>
                            @elseif($k === 'pain')
                                <input type="text"
                                       class="form-control form-control-sm border-0"
                                       data-name="pain"
                                       placeholder="{{$v}}"
                                       data-option-list="pain" multi-col-option-list tiny value="{{$contentData['pain']}}">
                                <div id="pain" class="data-option-list">
                                    <div>1</div>
                                    <div>6</div>
                                    <div>2</div>
                                    <div>7</div>
                                    <div>3</div>
                                    <div>8</div>
                                    <div>4</div>
                                    <div>9</div>
                                    <div>5</div>
                                    <div>10</div>
                                </div>
                            @else
                                <input type="text"
                                       class="form-control form-control-sm border-0" data-name="{{$k}}" {{$k}}
                                       value="{{$contentData[$k]}}"
                                       placeholder="{{$v}}"
                                       @if($k == 'heightInInches' || $k == 'weightPounds') refresh-bmi @endif>
                            @endif
                        </td>
                        @if(!$previousData || !count($previousData))
                            <td class="bg-light"></td>
                        @else
                            @foreach($previousData as $pDay)
                                <td class="bg-light {{!isset($copyTriggerAdded[$k]) ? 'px-2' : 'px-2'}} py-1 text-secondary position-relative">
                                    <span data-type="{{$k}}">
                                    @if($k === 'systolicBP')
                                        {{ @$previousDataAssoc[$pDay['date']]['systolicBP'] ?: '-' }}/{{ @$previousDataAssoc[$pDay['date']]['diastolicBP'] ?: '-' }}
                                    @elseif($k === 'heightInInches')
                                        {{$previousDataAssoc[$pDay['date']][$k] ? toFeetAndInches($previousDataAssoc[$pDay['date']][$k]) : '-' }}
                                    @elseif($k === 'bmi')
                                        {{$previousDataAssoc[$pDay['date']][$k] ?: '-' }}
                                        <?php
                                        $prevBMI = $previousDataAssoc[$pDay['date']][$k] ? +($previousDataAssoc[$pDay['date']][$k]) : false;
                                        ?>
                                        @if($prevBMI < 18.5)
                                            <span class="text-sm text-warning-mellow ml-1">Underweight</span>
                                        @endif
                                        @if($prevBMI >= 18.5 && $prevBMI < 25)
                                            <!--<span class="text-sm text-success ml-1">Healthy Weight</span>-->
                                        @endif
                                        @if($prevBMI >= 25 && $prevBMI < 30)
                                            <span class="text-sm text-warning-mellow ml-1">Overweight</span>
                                        @endif
                                        @if($prevBMI >= 30)
                                            <span class="text-sm text-warning-mellow ml-1">Obese</span>
                                        @endif
                                    @else
                                        {{$previousDataAssoc[$pDay['date']][$k] ?: '-' }}
                                    @endif
                                    </span>
                                    @if(!isset($copyTriggerAdded[$k]) && $k !== "bmi")
                                        <a href="#" title="Copy to this note" class="vitals-copy-trigger"><i class="fa fa-chevron-circle-left font-size-14"></i></a>
                                    @endif
                                </td>
                                <?php $copyTriggerAdded[$k] = true ?>
                            @endforeach
                        @endif
                    </tr>
                    @endif
                @endforeach
            </tbody>
        </table>
        <div>
            <button submit class="btn btn-sm btn-primary mr-2"><i class="fa fa-save"></i></button>
            <div class="d-inline-flex align-self-stretch align-items-center">
                <span class="autosave-indicator saving text-sm text-secondary">Saving changes &hellip;</span>
                <span class="autosave-indicator saved text-sm text-secondary">
                    <i class="fa fa-check"></i>
                    Saved
                </span>
            </div>
        </div>
    </form>
</div>
<script>
    window.segmentInitializers.psych_vitals = function () {
        let parentSegment = $('[data-segment-template-name="psych_vitals"] ');

        function __refreshBMI() {
            var height = parseInt(parentSegment.find('[data-name="heightInInches"]').val());
            var weight = parseInt(parentSegment.find('[data-name="weightPounds"]').val());
            var bmi = '', bmiCategory = '';
            if(!isNaN(height) && !isNaN(weight)) {
                bmi = Math.round((weight / (height * height)) * 703.06957964);
                if(bmi < 18.5) {
                    bmiCategory = '<span class="text-sm text-warning-mellow">Underweight</span>';
                }
                else if(bmi >= 18.5 && bmi < 25) {
                    bmiCategory = '<span class="text-sm text-success"></span>';
                }
                else if(bmi >= 25 && bmi < 30) {
                    bmiCategory = '<span class="text-sm text-warning-mellow">Overweight</span>';
                }
                else if(bmi >= 30) {
                    bmiCategory = '<span class="text-sm text-warning-mellow">Obese</span>';
                }
            }
            parentSegment.find('[bmi]').val(bmi);
            parentSegment.find('[bmi-category]').empty().append(bmiCategory);
        }

        parentSegment.find('[refresh-bmi]').off('change input');
        parentSegment.find('[refresh-bmi]').on('change input', __refreshBMI);

        parentSegment.find('[heightFeetInput], [heightInchesInput]').off('change input paste');
        parentSegment.find('[heightFeetInput], [heightInchesInput]').on('change input paste', function () {
            let inches = 0;
            let ft = +(parentSegment.find('[heightFeetInput]').val()),
                inc = +(parentSegment.find('[heightInchesInput]').val());
            inches = Math.round(ft * 12 + inc);
            parentSegment.find('[data-name="heightInInches"]').val(inches);
            __refreshBMI();
        });

        parentSegment.find('.vitals-copy-trigger').off('click.copy-vital');
        parentSegment.find('.vitals-copy-trigger').on('click.copy-vital', function () {
            let td = $(this).closest('td'), value = $.trim(td.text());
            let type = td.find('>span').first().attr('data-type');
            if(!type) return false;
            switch (type) {
                case 'heightInInches':
                    if(value.indexOf('ft.') !== -1 && value.indexOf('in.') !== -1) {
                        value = value.replace('in.', '');
                        value = value.replace('ft.', '|');
                        value = value.replace('/\s/gi', '');
                        let parts = value.split('|');
                        if (parts.length >= 1 && parts[0] !== '-') {
                            td.prev().find('input:eq(0)').val(parts[0]).trigger('change');
                        }
                        if (parts.length >= 2 && parts[1] !== '-') {
                            td.prev().find('input:eq(1)').val(parts[1]).trigger('change');
                        }
                    }
                    break;
                case 'systolicBP':
                    if(value.indexOf('/') !== -1) {
                        let parts = value.split('/');
                        if (parts.length >= 1 && parts[0] !== '-') {
                            td.prev().find('input:eq(0)').val(parts[0]).trigger('change');
                        }
                        if (parts.length >= 2 && parts[1] !== '-') {
                            td.prev().find('input:eq(1)').val(parts[1]).trigger('change');
                        }
                    }
                    break;
                default:
                    if(value && value !== '-') {
                        td.prev().find('input').val(value).trigger('change');
                    }
                    break;
            }

            return false;
        });

    };
</script>
