<?php

use App\Models\Client;
use App\Models\Point;
use App\Models\Note;
/** @var Client $patient */
/** @var Note $note */
/** @var Segment $segment */

if(!@$segment) $segment = null;

if(!@$sessionKey) {
    $sessionKey = request()->cookie('sessionKey');
}

$fields = [
    [
        "Head" => ["Trauma"],
        "Eyes" => ["Blindness", "Cataracts", "Glaucoma", "Wears glasses/contacts"],
        "Ears" => ["Hearing aids"],
        "Nose/Sinuses" => ["Allergic Rhinitis", "Sinus infections"],
        "Mouth/Throat/Teeth" => ["Dentures"],
        "Cardiovascular" => ["Aneurysm", "Angina", "DVT", "Dysrhythmia", "HTN", "Murmur", "Myocardial infarction", "Other heart disease"],
    ],
    [
        "Respiratory" => ["Asthma", "Bronchitis", "COPD - Bronchitis/Emphysema", "Pleuritis", "Pneumonia"],
        "Gastrointestinal" => ["Cirrhosis", "GERD", "Gallbladder disease", "Heartburn", "Hemorrhoids", "Hepatitis", "Hiatal hernia", "Jaundice", "Ulcer"],
        "Genitourinary" => ["Hernia", "Incontinence", "Nephrolithiasis", "Other kidney disease", "STDs", "UTI(s)"],
    ],
    [
        "Musculoskeletal" => ["Arthritis", "Gout", "M/S injury"],
        "Skin" => ["Dermatitis", "Mole(s)", "Other skin condition(s)", "Psoriasis"],
        "Neurological" => ["Epilepsy", "Seizures", "Severe headaches, migraines", "Stroke", "TIA"],
        "Psychiatric" => ["Bipolar disorder", "Depression", "Hallucinations, delusions", "Suicidal ideation", "Suicide attempts"],
    ],
    [
        "Endocrine" => ["Goiter", "Hyperlipidemia", "Hypothyroidism", "Thyroid disease", "Thyroiditis", "Type I DM", "Type II DM"],
        "Heme/Onc" => ["Anemia", "Cancer"],
        "Infectious" => ["HIV", "STDs", "Tuberculosis (dz)", "Tuberculosis (exposure)"],
    ]
];

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

if(!$customFields) $customFields = [];

$point = Point::getOrCreateOnlyTopLevelPointOfCategory($note, 'PAST_MEDICAL_HISTORY', $sessionKey, true);

$contentData = $parsed = false;

if ($point->lastChildReview && $point->lastChildReview->data) {
    $point->lastChildReview->data = json_decode($point->lastChildReview->data, true);
    $contentData = $parsed = $point->lastChildReview->data;
}

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

for ($i = 0; $i < count($fields); $i++) {
    foreach($fields[$i] as $head => $values) {
        for($k = 0; $k < count($values); $k++) {
            $fName = $head . '_' . sanitize_field_name($values[$k]);
            if(!isset($contentData["common"][$fName])) $contentData["common"][$fName] = null;
        }
    }
}
?>
<hr class="hide-outside-popup mt-3 mb-0">
<div class="p-3 mcp-theme-1">
    <div {{!!$segment ? 'visit-moe' : 'moe'}} close-on-save close-on-cancel class="d-block">
        <form show url="/api/visitPoint/upsertChildReview" class="mcp-theme-1"
                {{!$segment ? 'hook=onHxPopupClosure' : ''}}>
            @if(!!@$segment)
                <input type="hidden" name="segmentUid" value="<?= $segment->uid ?>">
            @else
                <input type="hidden" name="segmentUid" value="<?= $note->coreSegment->uid ?>">
            @endif
            <input type="hidden" name="uid" value="<?= $point->uid ?>">
            <input type="hidden" name="noteUid" value="<?= $note->uid ?>">
            <input type="hidden" name="data">

            <div id="edit-univ_history_past_medical-container">
                <div class="d-flex align-items-center mb-2">
                    <div class="width-100px mr-3">
                        <label class="text-secondary mb-1">Blood Type</label>
                        <select class="form-control form-control-sm width-100px" v-model="bloodType">
                            <option value=""> -- select -- </option>
                            <option value="A">A</option>
                            <option value="AB">AB</option>
                            <option value="B">B</option>
                            <option value="O">O</option>
                        </select>
                    </div>
                    <div class="width-100px mr-3">
                        <label class="text-secondary mb-1">RH</label>
                        <select class="form-control form-control-sm width-100px" v-model="bloodRH">
                            <option value=""> -- select -- </option>
                            <option value="+ve">+ve</option>
                            <option value="-ve">-ve</option>
                        </select>
                    </div>
                </div>
                <div class="row custom-items-container">
                    @for ($i = 0; $i < count($fields); $i++)
                        <div class="col-12 col-sm-6 col-md-4 col-lg-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]); ?>
                                        <label class="d-flex align-items-start mb-1">
                                            <input type="checkbox" name="{{ $fName }}" class="mx-0 mt-1"
                                                   v-model="common['{{$fName}}']">
                                            <div class="ml-2">
                                                <div class="d-flex">
                                                    <span class="mr-2 common-item">{{ $values[$k] }}</span>
                                                    <div moe relative no-mask v-show="common['{{$fName}}']" >
                                                        <a href="#" start show>
                                                            <i 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 min-width-200px"
                                                                          v-model="common['{{$fName}}__comments']"></textarea>
                                                            </div>
                                                            <div class="">
                                                                <button type="button" class="btn btn-sm btn-primary" cancel>Close
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <a v-show="common['{{$fName}}']"
                                                       class="ml-1"
                                                       open-in-stag-popup
                                                       mc-initer="problems-center-{{$note->id}}"
                                                       title="Problems Center"
                                                       popup-style="overflow-visible"
                                                       href="/problems-center/{{$patient->uid}}/{{$note->uid}}?dx={{urlencode($values[$k])}}">
                                                        <i class="fa fa-plus-circle on-hover-opaque"></i>
                                                    </a>
                                                </div>
                                                <span v-show="common['{{$fName}}'] && common['{{$fName}}__comments']"
                                                      v-html="common['{{$fName}}__comments']"
                                                      class="text-sm text-secondary">
                                                </span>
                                            </div>
                                        </label>
                                    @endfor
                                </div>
                            @endforeach
                        </div>
                    @endfor
                </div>
                <div class="row border-top pt-3">
                    <div class="col-12">
                        @include('app.patient.segment-templates._custom_items.edit')
                    </div>
                </div>
                <hr class="m-neg-4">
                <div class="mb-2">
                    <textarea class="form-control form-control-sm" v-model="comments">{!! $parsed && @$parsed->content ? @$parsed->content : '' !!}</textarea>
                </div>
            </div>

            @if(!!$segment)
                <div>
                    <button onclick="return saveVisitForm(this, false, false)" type="button" 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>
            @else
                <div>
                    <button submit class="btn btn-sm btn-primary mr-2">Submit</button>
                    <button cancel class="btn btn-sm btn-default border" {!! @$closeOnSave ? 'onmousedown="return closeStagPopup()"' : '' !!}>Close</button>
                </div>
            @endif

        </form>
    </div>
</div>
<script>
    (function() {

        function init() {

            let model = <?= $contentData ? json_encode($contentData) : '{}' ?>;
            model.newCustomItemLabel = '';
            let myCustomFields = <?= json_encode($customFields) ?>;
            if(!model.customFields) {
                model.customFields = [];
            }
            for (let i = 0; i < myCustomFields.length; i++) {
                let foundAt = -1;
                for (let j = 0; j < model.customFields.length; j++) {
                    if(model.customFields[j].label === myCustomFields[i].label) {
                        foundAt = j;
                        break;
                    }
                }
                if(foundAt === -1) {
                    model.customFields.push({
                        label: myCustomFields[i].label,
                        value: '',
                        comments: '',
                        uid: myCustomFields[i].uid
                    })
                }
                else {
                    model.customFields[foundAt].uid = myCustomFields[i].uid;
                }
            }

            // if not own AND not active - remove from model.customFields
            for (let i = model.customFields.length - 1; i >= 0 ; i--) {
                let foundAt = -1;
                for (let j = 0; j < myCustomFields.length; j++) {
                    if(model.customFields[i].label === myCustomFields[j].label) {
                        foundAt = j;
                        break;
                    }
                }
                if(foundAt === -1) {
                    if(!!model.customFields[i].value) {
                        model.customFields[i].other = true;
                    }
                    else {
                        model.customFields.splice(i, 1);
                    }
                }
            }

            // sort by label
            model.customFields.sort(function (a, b) {
                return a.label.localeCompare(b.label);
            });

            model.itemKey = 'pmhx';

            new Vue({
                el: '#edit-univ_history_past_medical-container',
                delimiters: ["@{{","}}"],
                data: model,
                mounted: function() {
                    $('#edit-univ_history_past_medical-container [moe][initialized]').removeAttr('initialized');
                    initMoes();
                },
                watch: {
                    $data: {
                        handler: function(val, oldVal) {
                            let parent = $('#edit-univ_history_past_medical-container').closest('form');
                            parent.find('[name="data"]').val(JSON.stringify(this.$data)).trigger('save-trigger');
                        },
                        deep: true
                    }
                },
                methods: {
                    @include('app.patient.segment-templates._custom_items.script')
                }
            });

            window.segmentInitializers.past_medical_history = function() {};

            // if in popup (omega template), add provision to toggle relevance
            @include('app.patient.segment-templates._common_actions.toggle-relevance', ['container' => '#edit-univ_history_past_medical-container', 'segmentName' => 'omega_history_past_medical'])

        }

        window.segmentInitializers.past_medical_history = init;
        addMCInitializer('edit-univ_history_past_medical-container-{{$note->id}}', init, '#edit-univ_history_past_medical-container');

    }).call(window);
</script>
