<?php

use App\Models\Point;

$category = 'VITALS';
$endPoint = 'upsertNoteSingleton';

$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",
];

$point = Point::where('added_in_note_id', $note->id)->where('category', $category)->orderBy('id', 'DESC')->first();
$contentData = null;
if (!!@$point->data) {
    $contentData = json_decode($point->data, true);
}

if(!$contentData) {
    $contentData = [
        "date" => $note->effective_dateest,
        "heightInInches" => '',
        "weightPounds" => '',
        "bmi" => '',
        "temperatureF" => '',
        "systolicBP" => '',
        "diastolicBP" => '',
        "pulseRatePerMinute" => '',
        "respirationRatePerMinute" => '',
        "pulseOx" => '',
        "smokingStatus" => '',
    ];
}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 = Point::where('client_id', $patient->id)
    ->where('added_in_note_id', '<>', $note->id)
    ->where('category', $category)
    ->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;
        $previousData[] = $newFormat;
        $previousDataAssoc[$newFormat['date']] = $newFormat; // for easy iter to cols
    }
}

$copyTriggerAdded = [];

?>
<div visit-moe close-on-save close-on-cancel class="d-block">
    <form show url="/api/visitPoint/<?= $endPoint ?>" class="mcp-theme-1">
        <input type="hidden" name="segmentUid" value="<?= $segment->uid ?>">
        <input type="hidden" name="category" value="<?= $category ?>">
        <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-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' : $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">
                                        @if(isset($contentData['bmi']) && $contentData['bmi'] != "" )
                                            <?php $bmi = $contentData['bmi']; ?>
                                            @if($bmi < 18.5)
                                                <span class="text-sm text-warning-mellow" v-if="+bmi < 18.5">Underweight</span>
                                            @endif
                                            @if($bmi >= 18.5 && $bmi < 25)
                                                <!--<span class="text-sm text-success" v-if="+bmi >= 18.5 && +bmi < 25">Healthy Weight</span>-->
                                            @endif
                                            @if($bmi >= 25 && $bmi > 30)
                                                <span class="text-sm text-warning-mellow" v-if="+bmi >= 25 && +bmi < 30">Overweight</span>
                                            @endif
                                            @if($bmi >= 30)
                                                <span class="text-sm text-warning-mellow" v-if="+bmi >= 30">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>
                            @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">
                                    @if($k === 'systolicBP')
                                        {{ @$previousDataAssoc[$pDay['date']]['systolicBP'] ?: '-' }}/{{ @$previousDataAssoc[$pDay['date']]['diastolicBP'] ?: '-' }}
                                    @else
                                        {{$previousDataAssoc[$pDay['date']][$k] ?: '-' }}
                                    @endif
                                    @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">Submit</button>
            <button cancel class="btn btn-sm btn-default border">Cancel</button>
        </div>
    </form>
</div>
<script>
    window.segmentInitializers.<?= $segment->segmentTemplate->internal_name ?> = function () {
        let parentSegment = $('[data-segment-template-name="<?= $segment->segmentTemplate->internal_name ?>"] ');

        parentSegment.find('[refresh-bmi]').off('change input');
        parentSegment.find('[refresh-bmi]').on('change input', function () {
            var height = parseInt(parentSegment.find('[heightInInches]').val());
            var weight = parseInt(parentSegment.find('[weightPounds]').val());
            var bmi = Math.round((weight / (height * height)) * 703.06957964)
            parentSegment.find('[bmi]').val(bmi);
            parentSegment.find('[bmi-date]').val(parentSegment.find('[weight-date]').val());
        });

        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());
            if(value.indexOf('/') === -1) {
                td.prev().find('input').val(value).trigger('change');
            }
            else {
                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');
                }
            }
            return false;
        });

    };
</script>
