<?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 = [
    [
        "Tobacco" => ["Current every day smoker", "Current some day smoker", "Former smoker", "Heavy tobacco smoker", "Light tobacco smoker", "Never smoker", "Smoker, current status unknown", "Unknown if ever smoked "],
    ],
    [
        "Alcohol" => ["Do not drink", "Drink daily", "Frequently drink", "Hx of Alcoholism", "Occasional drink"],
        "Drug Abuse" => ["IVDU", "Illicit drug use", "No illicit drug use"],
    ],
    [
        "Cardiovascular" => ["Eat healthy meals", "Regular exercise", "Take daily aspirin"],
        "Safety" => ["Household Smoke detector", "Keep Firearms in home", "Wear seatbelts"],
    ],
    [
        "Sexual Activity" => ["Exposure to STI", "Homosexual encounters", "Not sexually active", "Safe sex practices", "Sexually active"],
        "Birth Gender" => ["Male", "Female", "Undifferentiated"],
    ]
];

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

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

$point = Point::getOrCreateOnlyTopLevelPointOfCategory($note, 'SOCIAL_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 = [
        "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_social-container">
                <div class="d-flex align-items-start flex-wrap custom-items-container row">
                    @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" 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>
                                                </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 = 'sochx';

            new Vue({
                el: '#edit-univ_history_social-container',
                delimiters: ["@{{","}}"],
                data: model,
                mounted: function() {
                    $('#edit-univ_history_social-container [moe][initialized]').removeAttr('initialized');
                    initMoes();
                },
                watch: {
                    $data: {
                        handler: function(val, oldVal) {
                            let parent = $('#edit-univ_history_social-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')
                }
            });

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

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

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