<?php

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

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

$fields = [
    [
        "Constitutional" => [
            "Fatigue",
            "Fever",
            "Weight gain",
            "Weight loss"],

        "Eyes" => [
            "Blurry vision",
            "Double vision",
            "Dry eyes",
            "Floaters",
            "Halos",
            "Headache",
            "Irritation",
            "Loss of peripheral vision",
            "Pain",
            "Pinpoint pupils",
            "Teary",
            "Visual changes"],

        "ENMT" => [
            "Altered sense of smell",
            "Dental caries",
            "Dentures",
            "Dizziness",
            "Dry mouth",
            "Ear pain/pressure",
            "Hearing loss",
            "Mouth pain",
            "Nasal congestion",
            "Neck pain/stiffness",
            "Post nasal drainage",
            "Sinus pain / pressure",
            "Sore throat",
            "Teeth missing",
            "Tinnitus",
            "Trouble swallowing"],
        "Allergy / Immune" => [
            "Congestion",
            "Difficulty healing",
            "Frequent infections",
            "Headache",
            "Hives",
            "Itching",
            "Running nose",
            "Sneezing",
            "Watery eyes"],

        "Cardiovascular" => [
            "Chest pain / pressure at rest",
            "Chest pain / pressure with excursion",
            "Cold hands / feet",
            "Dizziness",
            "Exercise intolerance",
            "Fainting",
            "Feeling faint",
            "Left arm pain",
            "Light headed",
            "Lower leg cramps",
            "Muscle weakness",
            "Palpitations",
            "Shortness of breath",
            "Sweating",
            "Swelling"],

    ],
    [
        "Respiratory" => [
            "Cough – dry",
            "Cough – wet",
            "Coughing up blood",
            "Pain with breathing",
            "Productive cough",
            "Shortness of breath at rest",
            "Shortness of breath on excursion",
            "Wheezing"],

        "Gastrointestinal" => [
            "Abdominal pain",
            "Constipation",
            "Coughing up blood",
            "Diarrhea",
            "Difficulty swallowing",
            "Fecal incontinence",
            "Heartburn",
            "Loose stool",
            "Nausea",
            "Painful swallowing",
            "Rectal pain",
            "Stool – black tarry",
            "Stool – bloody"],

        "Genitourinary" => [
            "Blood in urine",
            "Discharge",
            "Foley",
            "Incontinence",
            "Lesions",
            "Sexual dysfunction",
            "Tenderness",
            "Urinary retention",
            "Urination - frequent",
            "Urination - painful",
            "Urination wakes you up at night"],

        "Musculoskeletal" => [
            "Decreased range of motion",
            "Fracture",
            "Gait - unstable",
            "Joint instability",
            "Joint pain",
            "Joint stiffness",
            "Joint swelling",
            "Muscle pain",
            "Muscle weakness",
            "Sprain"],

        "Skin" => [
            "Bruises",
            "Color changes",
            "Dry skin",
            "Goosebumps",
            "Itchy",
            "IVDU marks",
            "Lesions",
            "Nodules",
            "Rash",
            "Scars",
            "Swelling",
            "Track marks",
            "Ulcer",
            "Wound"],
    ],
    [
        "Neurological" => [
            "Coordination problem",
            "Dizziness",
            "Double vision",
            "Fainting",
            "Head trauma",
            "Headache",
            "Imbalance",
            "Muscle twitching",
            "Numbness",
            "Problems walking",
            "Restlessness",
            "Seizures",
            "Speech disturbance",
            "TBI",
            "Tingling",
            "Tinnitus",
            "Tremor",
            "Vertigo",
            "Weakness"],

        "Endocrine" => [
            "Change in hair growth",
            "Cold intolerance",
            "Diabetes",
            "Excessive hunger",
            "Excessive thirst",
            "Excessive urination",
            "Exhausted",
            "Goiter",
            "Heat intolerance",
            "Hot and cold flashes",
            "Sleeplessness",
            "Weight gain",
            "Weight loss"],

        "Lymphatic" => [
            "Anemia",
            "Bleeding tendency",
            "Bruises",
            "Lymph node pain enlargement",
            "Pain",
            "Swelling",
            "Transfusions"],
    ]
];

// only for ros - since ros edit markup is loaded via AJAX GET from the UI
if(!@$sessionKey) {
    $sessionKey = request()->cookie('sessionKey');
}

$point = Point::getOrCreateOnlyTopLevelPointOfCategory($note, 'ROS', $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 = [
        "declaration" => false,
        "common" => [],
        "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 ?>">
            @endif
            <input type="hidden" name="uid" value="<?= $point->uid ?>">
            <input type="hidden" name="noteUid" value="<?= $note->uid ?>">
            <input type="hidden" name="data" value='{!! json_encode($contentData) !!}'>

            <div id="edit-ros-container">
                <label class="d-flex align-items-center mb-3">
                    <input type="checkbox" class="my-0 mr-2" v-model="declaration">
                    <span>Except for the systems documented in the HPI or detailed below, all other systems were reviewed and negative.</span>
                </label>
                <div class="d-flex align-items-start flex-wrap custom-items-container">
                    @for ($i = 0; $i < count($fields); $i++)
                        <div class="w-33">
                            @foreach($fields[$i] as $head => $values)
                                <div class="font-weight-bold mb-2">{{ $head }}</div>
                                <div class="d-flex flex-nowrap align-items-center mb-1">
                                    <span class="rspace"><i class="fa fa-plus-circle text-success on-hover-opaque"></i></span>
                                    <span class="rspace ros-minus-all c-pointer" data-category="{{$head}}"><i class="fa fa-minus-circle text-danger on-hover-opaque"></i></span>
                                </div>
                                <div class="mb-3 ros-category" data-category="{{$head}}">
                                    @for($k = 0; $k < count($values); $k++)
                                        <?php $fName = $head . '_' . sanitize_field_name($values[$k]); ?>
                                        <div class="d-flex align-items-stretch mb-1">
                                            <div class="d-inline-flex flex-nowrap align-items-center">
                                                <span class="rspace">
                                                    <input type="radio" name="{{ $fName }}" class="m-0 c-pointer"
                                                           v-model="common['{{$fName}}']" value="+">
                                                </span>
                                                <span class="rspace">
                                                    <input type="radio" name="{{ $fName }}" class="m-0 c-pointer"
                                                           v-model="common['{{$fName}}']" value="-">
                                                </span>
                                            </div>
                                            <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" right>
                                                            <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 href="#" v-show="common['{{$fName}}']" v-on:click.prevent="clearValue('{{$fName}}')">
                                                        <i class="text-danger on-hover-opaque fa fa-trash-alt ml-1"></i>
                                                    </a>
                                                </div>
                                                <span v-show="common['{{$fName}}'] && common['{{$fName}}__comments']"
                                                      v-html="common['{{$fName}}__comments']"
                                                      class="text-sm text-secondary">
                                                </span>
                                            </div>
                                        </div>
                                    @endfor
                                </div>
                            @endforeach
                        </div>
                    @endfor
                </div>
                <hr class="m-neg-4 mt-0">
                <div class="mb-2">
                    <textarea class="form-control form-control-sm" v-model="comments">{!! $parsed && @$parsed->content ? @$parsed->content : '' !!}</textarea>
                </div>
                <div class="mt-3">
                    <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>
            </div>

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

        const debounce = (func, wait) => {
            let timeout;
            return function executedFunction(...args) {
                const later = () => {
                    clearTimeout(timeout);
                    func(...args);
                };
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
            };
        };

        let debouncedROSSaver = debounce(function(_trigger) {
            $(_trigger).closest('.stag-popup').find('.autosave-indicator').removeClass('show');
            $(_trigger).closest('.stag-popup').find('.autosave-indicator.saving').addClass('show');
            saveVisitForm(_trigger, true, false, () => {
                $(_trigger).closest('.stag-popup').find('.autosave-indicator').removeClass('show');
                $(_trigger).closest('.stag-popup').find('.autosave-indicator.saved').addClass('show');
            });
        }, 500);

        function initROS() {

            let model = <?= $contentData ? json_encode($contentData) : '{}' ?>;

            model.itemKey = 'pmhx';

            new Vue({
                el: '#edit-ros-container',
                delimiters: ["@{{","}}"],
                data: model,
                mounted: function() {
                    $('#edit-ros-container [moe][initialized]').removeAttr('initialized');
                    initMoes();

                    // custom buttons on title bar
                    $('.button-container').remove();
                    let buttonContainer = $('<div/>').addClass('button-container ml-4 mr-auto');
                    let titleElem = $('#edit-ros-container').closest('.stag-popup').find('.stag-popup-title>span');
                    titleElem.next().removeClass('ml-auto');
                    titleElem.parent().addClass('align-items-center');

                    // add button for "Edit Mode"
                    $('<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>').appendTo(buttonContainer);

                    buttonContainer.insertAfter(titleElem);

                    $('#edit-ros-container')
                        .off('click.ros-minus-all')
                        .on('click.ros-minus-all', '.ros-minus-all[data-category]', function() {
                            let category = $(this).attr('data-category');
                            $('.ros-category[data-category="' + category + '"]').find('input[type="radio"][value="-"]').click();
                            return false;
                        });
                },
                watch: {
                    $data: {
                        handler: function(val, oldVal) {
                            let parent = $('#edit-ros-container').closest('form');
                            parent.find('[name="data"]').val(JSON.stringify(this.$data));
                            debouncedROSSaver($('#edit-ros-container')[0]);
                        },
                        deep: true
                    }
                },
                methods: {
                    clearValue: function(_key) {
                        this.common[_key] = null;
                        Vue.nextTick(function() {
                            $('#edit-ros-container').find('textarea').first().trigger('input');
                        });
                    },
                    saveROS: function() {
                        saveVisitForm($('#edit-ros-container')[0], false, true);
                    }
                }
            });

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

        }

        window.segmentInitializers.omega_ros = initROS;

        addMCInitializer('init-ros-{{$note->id}}', initROS, '#edit-ros-container');

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