<?php

use App\Models\Client;
use App\Models\Note;
use App\Models\Point;

/** @var Client $patient */
/** @var Note $note */
/** @var Point $point */

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

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

// replace content data
$contentData = [
	"Dozing" => "",
	"functional_status" => false,
	"cognitive_status" => false,
	"Score" => 0,
];

if ($point->lastChildReview && $point->lastChildReview->data) {
	$point->lastChildReview->data = json_decode($point->lastChildReview->data, true);
	$contentData = $point->lastChildReview->data;
}
?>
<div class="p-3 mcp-theme-1">
	<style>
		.select-esc-option {
			max-width: 100px;
			min-width: auto !important;
		}
    .textarea .select2-selection{
      height: 100px !important;
    }
    .select2-results__message {
      display: none !important;
    }
	</style>
	<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="<?= $note->coreSegment->uid ?>">
			<input type="hidden" name="data" value="{{json_encode($contentData)}}">

			<div id="edit-sleep_health_intake-container" class="customized-form">
				@include('app.patient.modules.sleep_health_intake.partials.cc')
				@include('app.patient.modules.sleep_health_intake.partials.epworth_sleepiness_study')

				@include('app.patient.modules.sleep_health_intake.partials.obstructive_sleep_apnea')

				@include('app.patient.modules.sleep_health_intake.partials.physical_exam')

				@include('app.patient.modules.sleep_health_intake.partials.a_p')

				<div class="mt-3 pt-3 border-top text-center">
					<button type="button" v-on:click.prevent="saveForm()" class="btn btn-sm btn-primary mr-2">Submit</button>
					<button type="button" onclick="closeStagPopup()" class="btn btn-sm btn-default border">Cancel</button>
				</div>

			</div>

			<div class="d-none">
				<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>
</div>
<script>
	(function() {
		runMCInitializer('hide-moes');
		function init() {

			// any JS can come here
			// will be run on page-load as well as whenever this segment is refreshed
			new Vue({
				el: '#edit-sleep_health_intake-container',
				delimiters: ["@{{", "}}"],
				data: {
					form: $('#edit-sleep_health_intake-container').closest('form'),
					data: <?= json_encode($contentData) ?>,
					defaultDropdownOptions: {}
				},
				methods: {
					autoSaveForm: function() {
						var self = this;
						var url = self.form.attr('url');
						self.form.find('input[name=data]').val(JSON.stringify(self.data));
						// autosave on change
						var dataArray = self.form.serializeArray();
						$.post(url, dataArray, function(response) {}, 'json');
						refreshSegment('omega_subjective_system');
						refreshSegment('omega_assessment_system');
						refreshSegment('omega_plan_system');
					},
					_autoSaveForm: function() {
						let parent = $('#edit-sleep_health_intake-container').closest('form');
						parent.find('[name="data"]').val(JSON.stringify(this.data));

						// autosave on change
						autoSaveSegment(parent.find('[submit]').first());
					},
					saveForm: function() {
						this.autoSaveForm();
						closeStagPopup();
						refreshSegment('omega_subjective_system');
						refreshSegment('omega_assessment_system');
						refreshSegment('omega_plan_system');
						refreshSegment('omega_cc');
					},
					onInputChange: function(evt) {
						var self = this;
						var input = evt.target;
						var name = input.name || $(input).data('name');
						value = input.value;
						if ($(input).is(':radio')) {
							if (!input.checked) {
								value = null;
							}
						}
						if ($(input).is(':checkbox')) {
							value = input.checked ? 'YES' : null
						}
						self.data[name] = value;
						self.autoSaveForm();
					},
					initSelect2: function() {
						var self = this;
						var arr = $('.select2');
						for (var i = 0; i < arr.length; i++) {
							var loadedData = self.data[arr[i].name] || [];

							$(arr[i]).select2({
								data: loadedData,
								tags: true,
								allowClear: true,
								placeholder: 'Press "Enter" to create a new entry',
							}).on('change', function(e) {
								var name = $(e.target)[0].name;
								var value = $(e.target).val();
								self.data[name] = value;
								self.autoSaveForm();
							}).val(loadedData);

							$(arr[i]).trigger('change'); //load preselected

						};
					},
					calculateScore: function() {
						var self = this;
						var fields = self.form.find('[score-input]');
						var score = 0;
						$.each(fields, function(i, field) {
							var value = parseInt($(field).val());
							value = isNaN(value) ? 0 : value;
							score = score + value;
						});
						self.data.Score = score;
						$('#scoreValue').text(self.data.Score);
						self.$forceUpdate();
						self.autoSaveForm();
					},
					clearScore: function() {
						var self = this;
						var fields = self.form.find('[score-input]');
						$.each(fields, function(i, field) {
							var name = $(field).data('name');
							self.data[name] = null;
							$(field).val(null);
						});
						self.data.score = 0;
						$('#scoreValue').text(self.data.score);
						self.$forceUpdate();
						self.autoSaveForm();
					},
					initOnSelectChange: function() {
						var self = this;
						self.form.find('.calc-select').on('change', function() {
							self.calculateScore();
						});
					},
					initOmegaCC: function(){
						var self = this;
						const options = { theme: "snow" };
						var quill = new Quill('#omegaCCEditor', options);
						quill.on('text-change', function(delta, oldDelta, source) {
							var html = quill.root.innerHTML;
							html = html.replace("<p><br></p>", "");
							// auto-save omega_cc
							var quillTarget = $('#omegaCCEditor');
							var segmentUid = quillTarget.data('segment-uid');
							var segmentCategory = quillTarget.data('segment-category');
							var noteUid = quillTarget.data('note-uid');
							var uid = quillTarget.data('uid');
							var data = {free_text:html};
							var formData = {
								// uid: uid,
								segmentUid: segmentUid,
								category: segmentCategory,
								data: JSON.stringify(data)
							};
							var url = '/api/visitPoint/upsertNoteSingleton';
							$.post(url, formData, function(response) {}, 'json');
							refreshSegment('omega_cc');
						});
					},
				},
				mounted: function() {
					this.initSelect2();
					this.initOnSelectChange();
					this.initOmegaCC();
					initRequestToAddAProblem();
				}
			});

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

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

	})();
</script>
