<?php
$displayData = [
	'icd_1' => [
		'title' => 'ICD 1',
		'reason' => $record->rm_reason_icd1,
		'description' => $record->rm_reason_icd1description
	],
	'icd_2' => [
		'title' => 'ICD 2',
		'reason' => $record->rm_reason_icd2,
		'description' => $record->rm_reason_icd2description
	],
	'icd_3' => [
		'title' => 'ICD 3',
		'reason' => $record->rm_reason_icd3,
		'description' => $record->rm_reason_icd3description
	],
	'icd_4' => [
		'title' => 'ICD 4',
		'reason' => $record->rm_reason_icd4,
		'description' => $record->rm_reason_icd4description
	],
];
if($recordType === 'NOTE'){
	$displayData['icd_1']['reason'] = $record->note_reason_icd1;
	$displayData['icd_1']['description'] = $record->note_reason_icd1description;
	$displayData['icd_2']['reason'] = $record->note_reason_icd2;
	$displayData['icd_2']['description'] = $record->note_reason_icd2description;
	$displayData['icd_3']['reason'] = $record->note_reason_icd3;
	$displayData['icd_3']['description'] = $record->note_reason_icd3description;
	$displayData['icd_4']['reason'] = $record->note_reason_icd4;
	$displayData['icd_4']['description'] = $record->note_reason_icd4description;

	$points = \App\Models\Point
	    ::where('client_id', $patient->id)
	    ->where('is_removed_due_to_entry_error', false)
	    ->where(function ($query1) use ($note) {
	        $query1
	            ->where(function ($query2) use ($note) {
	                $query2->where('is_removed', false)
	                    ->where('addition_reason_category', 'DURING_VISIT')
	                    ->where('added_in_note_id', $note->id);
	            })
	            ->orWhereRaw("(SELECT count(id) from note_point WHERE is_active IS TRUE AND note_id = {$note->id} AND point_id = point.id) > 0");
	    })
	    ->orderBy('created_at')
	    ->get();

	$problems = [];

	foreach ($points as $point) {
	    if ($point->data) {
	        $point->data = json_decode($point->data);
	    }
	    if($point->category === 'PROBLEM' && @$point->data->name) $problems[] = $point->data->name . (@$point->data->icd ? ' (' . $point->data->icd . ')' : '');
	}

}

	$submitUrl = null;
	if(@$recordType === 'CLIENT') $submitUrl = '/api/client/putRmReasons';
	if(@$recordType === 'NOTE') $submitUrl = '/api/note/putReasons';
	if(@$recordType === 'CARE_MONTH') $submitUrl = '/api/careMonth/putRmReasons';
?>
<div>
	@if($recordType == 'NOTE')
	<div id="suggestedICDComponent">
		<em v-if="unclaimedICDs.length > 0">Suggestions relevant to this note:</em>
		<em v-else>Missing suggestions listed in Assessment? <a href="#" class="ml-1 text-primary small" onclick="return fastReload()"><i class="fa fa-sync on-hover-opaque"></i></a></em>
		<div class="mb-2">
			<a href="javascript:;" @click.prevent="addICD(icd, $event)" v-for="icd in unclaimedICDs" class="badge badge-success p-1 text-left text-sm text-white d-inline-flex justify-content-between mr-2">@{{icd.reason}} (@{{icd.description}}) <i class="ml-3 fas fa-plus-square"></i></a>
		</div>
	</div>
	@endif
	<div class="d-flex">
		<?php $emptyICDs = true; ?>
		<ul id="sortIcds{{@$recordType}}" class="pl-0 mb-0">
			@foreach($displayData as $rmKey=>$rmData)
				<?php
				$emptyICD = true;
				if (!empty($rmData['reason']) || !empty($rmData['description'])) {
					$emptyICDs = false;
					$emptyICD = false;
				}
				?>
				@if(!$emptyICD)
					<li title="Drag and drop to rearrange the order" class="d-block badge badge-info p-2 px-3 text-left mb-1 mr-2" id="{{$rmKey}}"><i class="fas fa-ellipsis-v"></i><i class="fas fa-ellipsis-v mr-2"></i> {{$rmData['reason']}} @if(!empty($rmData['description']))({{ $rmData['description'] }})@endif</li>
				@endif
			@endforeach
		</ul>
		@if($emptyICDs)
			@if($recordType == 'NOTE') <!-- Claim ICDs are empty -->
			<div class="d-flex">
				<div class="alert alert-danger p-1 mb-0">
					Please ensure you have specified ICD codes relevant to this note.
				</div>
			</div>
			@else
				@if($patient->is_eligible_for_rm == 'YES' || $patient->is_enrolled_in_rm == 'YES')
					<div class="d-flex">
						<div class="alert alert-danger p-1 mb-0">
							Please specify the relevant RM reason(s).
						</div>
					</div>
				@else
					<small class="text-dark">-</small>
				@endif
			@endif
		@endif
	</div>

	@if($record->rm_reason_memo)
	<div class="d-flex">
			<span class="text-secondary mr-2"><b>Memo:</b></span>
			<small class="">{{ $record->rm_reason_memo }}</small>
	</div>
	@endif
</div>
<script type="text/javascript">
	var currentOrder = []; // to update the edit moe form order.
	$( function() {
		$( "#sortIcds{{@$recordType}}" ).sortable({
			stop: function(event, ui) {
				var els = $('.badge-info.ui-sortable-handle');
				var record = <?= json_encode($displayData) ?>;
				var newOrder = {};
				for (var i = 0; i < els.length; i++) {
					var icd_num = els[i].id;
					newOrder["icd_"+ (1+i)] = record[icd_num]
				}
				var data = {
					uid: "{{$record->uid}}",
					reasonIcd1: newOrder['icd_1'] ? newOrder['icd_1'].reason : '',
					reasonIcd1Description: newOrder['icd_1'] ? newOrder['icd_1'].description : '',
					reasonIcd2: newOrder['icd_2'] ? newOrder['icd_2'].reason : '',
					reasonIcd2Description: newOrder['icd_2'] ? newOrder['icd_2'].description : '',
					reasonIcd3: newOrder['icd_3'] ? newOrder['icd_3'].reason : '',
					reasonIcd3Description: newOrder['icd_3'] ? newOrder['icd_3'].description : '',
					reasonIcd4: newOrder['icd_4'] ? newOrder['icd_4'].reason : '',
					reasonIcd4Description: newOrder['icd_4'] ? newOrder['icd_4'].description : ''
				};
				currentOrder = data; // to update the moe form order.
				$.post("{{$submitUrl}}", data, function(results){
					if (!results.success) {
						toastr.error(results.message || 'Failed to rearrange');
					}
			  });
			}
		});
	});
</script>

@if($recordType == 'NOTE')
<script type="text/javascript">
	var suggestedICDComponent = new Vue({
		el: '#suggestedICDComponent',
		delimiters: ["@{{","}}"],
		data: {
			params: <?= json_encode($displayData) ?>,
			problems: <?= json_encode($problems) ?>,
			unclaimedICDs: [],
			adding: false,
		},
		methods: {
			addICD: function(_icd, _elem) {
				_elem.target.innerHTML = 'Please wait... <i class="fas fa-circle-notch fa-spin ml-3"></i>';

				var self = this;
				var icdEmpty = null;
				var obj = {};
				self.adding = true;
				for (var x = 1; x <= 4; x++) { // loop through all reasons initiated at the top
					if (!self.params['icd_'+x].reason) { // check if already added
						obj['reasonIcd'+x] = _icd.reason;
						obj['reasonIcd'+x+'Description'] = _icd.description;
						break; // stop loop;
					}else {
						obj['reasonIcd'+x] = self.params['icd_'+x].reason;
						obj['reasonIcd'+x+'Description'] = self.params['icd_'+x].description;
					}
				}
				var data = {
					uid: "{{$record->uid}}",
					reasonIcd1: obj['reasonIcd1'] || '',
					reasonIcd1Description: obj['reasonIcd1Description'] || '',
					reasonIcd2: obj['reasonIcd2'] || '',
					reasonIcd2Description: obj['reasonIcd2Description'] || '',
					reasonIcd3: obj['reasonIcd3'] || '',
					reasonIcd3Description: obj['reasonIcd3Description'] || '',
					reasonIcd4: obj['reasonIcd4'] || '',
					reasonIcd4Description: obj['reasonIcd4Description'] || ''
				};

				$.post("{{$submitUrl}}", data, function(results){
					if (!results.success) {
						_elem.target.innerHTML = icd.code + ' ('+ icd.description + ') <i class="ml-3 fas fa-plus-square"></i>';
						self.adding = false;
						toastr.error(results.message || 'Failed to add ICD code.');
					}else {
						fastReload();
					}
			  });

			},
			init: function() {
				var probs = this.problems;
				for (var i = 0; i < probs.length; i++) {
					var split = probs[i].split(' ('); // splitting description from ICD
					var description = split[0];
					var reason = split[1].split(')')[0]; // removing the closing parenthesis
					var reasonExists = false;

					for (var x = 1; x <= 4; x++) { // loop through all reasons initiated at the top
						if (this.params['icd_'+x].reason == reason) { // check if already added
						 	reasonExists = true;
						}
					}

					if (!reasonExists) {
						this.unclaimedICDs.push({description,reason});
					}
				}
			}
		},
		mounted: function() {
			this.init();
		}
	})
</script>
@endif
