<?= $this->extend($_SESSION['userrole'].'/layout/form.php') ?>

<?= $this->section('content') ?>
<?php
$usercityid = session()->get('usercityid');

if ($usercityid == 1) {
	date_default_timezone_set('Asia/Makassar');
	$valuevisitnumber = "value='BV'";
	$locationdropdown = "
		<option value='DPS'>Denpasar</option>
	";
} else if ($usercityid == 2) {
	date_default_timezone_set('Asia/Jakarta');
	$valuevisitnumber = "value='SV'";
	$locationdropdown = "
		<option value='SBY'>Surabaya</option>
	";
} else {
	date_default_timezone_set('Asia/Makassar');
	$valuevisitnumber = "";
	$locationdropdown = "	
		<option value='DPS'>Denpasar</option>
		<option value='SBY'>Surabaya</option>
	";
}
$now = date('Y-m-d H:i');
$visitdate = $now;

?>
<style>
.table > tbody > tr > td {
     vertical-align: middle;
}
.testtable {
    height: 330px;
    overflow-y: auto;
}
</style>
<div class="card border-0">
	<div class="card-body">
		<h3>Order Creation</h3>
		<input type='hidden' id='orderid' value='<?=$orderid;?>' />
		<div id='alert'>
		</div>
		<div class='row border gap-1 p-1'>
			<div class='col border'>
			
				<!-- Patient Data -->
				<p>Patient Information</p>
				<input type='hidden' id='patid' value='' />
				<div class='table-responsive border-1'>
					<table class='table table-sm table-borderless'>
						<tr>
							<td>MR#</td> 
							<td colspan='3'>
								<div class="input-group">
									<input type="text" id="patnumber" class="form-control form-control-sm" oninput="this.value = this.value.toUpperCase();patClear();">
									<div class="input-group-append">
										<button class='btn btn-sm btn-primary' onclick='patSearch()'><i class='bi bi-search'></i> Search</button>
									</div>
								</div>
							</td>
						</tr>
						<tr> <td>Patient Name</td> <td id='patname'></td></tr>
						<tr> <td>BirthDate</td> <td id='birthdate'></td> </tr>
						<tr> <td>Sex</td> <td id='sex'></td> </tr>
						<tr> <td>Address</td> <td id='address'></td></tr>
						<tr> <td>Phone#</td> <td id='phone'></td></tr>
					</table>
				</div>
				
				<!-- Order Data -->
				<p>Order Information</p>
				<div class='table-responsive border-1'>
					<table class='table table-sm table-borderless'>
						<tr> 
							<td>Visit#</td> 
							<td><input type="text" <?=$valuevisitnumber;?> id="visitnumber" class="form-control form-control-sm" oninput="this.value = this.value.toUpperCase();"></td> 
							<td>Visit Date</td> 
							<td><input type="datetime" id="visitdate" class="form-control form-control-sm" value='<?=$visitdate;?>'></td>
						</tr>
						<tr>
							<td>Location</td> 
							<td>
								<select id='loc' class='form-control'>
									<?=$locationdropdown;?>
								</select>
							</td>
							<td>Reff ID</td> 
							<td><input type="text" id="reffid" disabled class="form-control form-control-sm" value=''></td>
						</tr>
						<tr> 
							<td>Payer Name</td> 
							<td colspan='3'><input type="text" id="payername" class="form-control form-control-sm"></td> 
						</tr>
					</table>
				</div>
				
			</div>
			<div class='col border'>
			
				<!-- Tests Data -->
				<p>Tests</p>
				<div class='table-responsive testtable border'>
					<table class='table table-sm '>
						<tbody>
						<?php
						for($i=0;$i<50;$i++) {
						?>
						<tr> 
							<td class='px-2'> <?=$i+1;?></td>
							<td>
								<select class='form-control form-control-sm test<?=$i+1;?>'>
									<option value=''></option>
									<?php
									foreach($tests as $data) {
										$qhiscode = $data['HISCODE'];
										$qdesc = $data['DESCS'];
										echo "<option value='$qhiscode'>$qhiscode - $qdesc</option> \r\n";
									}
									?>
								</select>
							</td> 
							<td> <button class='btn btn-sm btn-warning' onclick="testdel(<?=$i+1;?>)">X</button> </td>
						</tr>
						<?php
						}
						?>
						</tbody>
					</table>
				</div>
				
			</div>
		</div>
		<p class='m-3'>
		<button class='btn btn-success' onclick='save()'>Save</button>
		<button class='btn btn-secondary' onclick='cancel()'>Cancel</button>
		</p>
	</div>
</div>

<div class="modal fade" id="modal_patEditor" aria-hidden="true" tabindex="-1">
	<div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
		<div class="modal-content">
			<div class="modal-header">
				<h1 class="modal-title fs-5" id="exampleModalToggleLabel">Edit Patient</h1>
				<button type="button" class="btn-close" data-bs-dismiss="modal" ></button>
			</div>
			<div class="modal-body" style='background-color:#F4F6FF'>
				<table class="table table-sm table-borderless">
					<input type='hidden' id='qpatid' value='' />
					<tr class="align-middle"> <th>MR#</th> <th>:</th> 
						<td><input class='form-control' type='text' id='qpatnumber' oninput='this.value = this.value.toUpperCase();' /></td> 
					</tr>
					<tr class="align-middle"> <th>Patient Name</th> <th>:</th> <td><input class='form-control' type='text' id='qpatname'/></td> </tr>
					<tr class="align-middle"> <th>BirthDate</th> <th>:</th> <td><input class='form-control' type='date' id='qbirthdate'/></td> </tr>
					<tr class="align-middle"> 
						<th>Sex</th> <th>:</th> 
						<td>
							<select class='form-control' id='qsex'>
								<option value=''></option>
								<option value='F'>Female</option>
								<option value='M'>Male</option>
							</select>
						</td> 
					</tr>
					<tr class="align-middle"> <th>Address</th> <th>:</th> <td><textarea class='form-control' id='qaddress'></textarea></td> </tr>
					<tr class="align-middle"> <th>Phone</th> <th>:</th> <td><input class='form-control' type='text' id='qphone'/></td> </tr>
				</table>		
				<button class='btn btn-sm btn-success' onclick='patSave()'>Save</button>
				<button class='btn btn-sm btn-secondary' data-bs-dismiss="modal">Cancel</button>
			</div>
		</div>
	</div>
</div>

<div class="modal fade" id="modal_patList" aria-hidden="true" tabindex="-1">
	<div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
		<div class="modal-content">
			<div class="modal-header">
				<h1 class="modal-title fs-5" id="exampleModalToggleLabel">Patient List</h1>
				<button type="button" class="btn-close" data-bs-dismiss="modal" ></button>
			</div>
			<div class="modal-body" style='background-color:#F4F6FF'>
				<table class="table table-sm table-borderless">
					<tbody id='patList_tbody' >
					</tbody>
				</table>		
			</div>
		</div>
	</div>
</div>

<?= $this->endSection() ?>

<?= $this->section('script') ?>
<script>
function testdel(testid) { 
	if(confirm('are you sure') == true)  {
		$('.test'+testid).val('').change(); 
	}
}

function orderDetail(orderid) {
	console.log(orderid);
	let url = '<?=base_url('');?>api/orders/detail/'+orderid;
	$.ajax({
		url: url,
		method: 'GET',
		success: function(response) {
			var data = response['orders'];
			$('#payername').val(data[0].PAYERNAME);
			$('#loc').val(data[0].LOC);
			$('#visitdate').val(data[0].VISITDATE);
			$('#visitnumber').val(data[0].VISITNUMBER);
			patSelect(data[0].PATID);
			
			var tests = response['tests'];
			var j = 1;
			for (const test of tests) {
				console.log(test);
				console.log(test.HISCODE);
				$('.test'+j).val(test.HISCODE).trigger('change');
				j++;
			}
		},
		error: function(response) { console.log(response.responseJSON); }
	});
}

function save() {
	confirm('Are you sure?');
	if(confirm) {
		var orderid = $("#orderid").val();
		var patid = $("#patid").val();
		var loc = $("#loc").val();
		var visitnumber = $("#visitnumber").val();
		var visitdate = $("#visitdate").val();
		var treatdoc = $("#treatdoc").val();
		var payername = $("#payername").val();
		let data = { orderid:orderid, loc:loc, patid:patid, visitnumber:visitnumber, visitdate:visitdate, treatdoc:treatdoc, payername:payername ,tests:new Array() };
		for (let i = 1; i <= 50; i++) {
			let className = `.test${i}`; 
			let value = $(className).val(); 
			if (value !== undefined && value != '') {
				data['tests'].push(value);
			}
		}
		alert = '';
		errorTxt = '';
		if(patid == '') { errorTxt += '<br/>patient is empty. '; }
		if(visitnumber == '') { errorTxt += '<br/>visitnumber is empty. '; }
		if(visitdate == '') { errorTxt += '<br/>visitdate is empty. '; }
		if(data['tests'].length == 0) { errorTxt += '<br/>tests is empty. '; }
		if(errorTxt != '') {
			alert = '<div class="alert alert-danger alert-dismissible fade show" role="alert">' +
				'<strong>Error!</strong>' + errorTxt +
				'<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>'+
				'</div>';
			$('#alert').html(alert);
		} else {
			console.log(data);
			let url = '<?=base_url('');?>api/orders/save';
			$.ajax({
				url: url,
				method: "POST",
				data: data,
				success: function(response) {
					console.log(response);
					window.close();
					if (window.opener) { window.opener.location.reload(); }
				},
				error: function(response) {
					console.log(response);
				}
			});
		}
	}
}

function cancel() {
	confirm('Your data will be discarded. Are you sure?');
	if(confirm) {
		window.close();
	}
}

function patClear() {
	$('#patid').val('');
	$('#patname').html('');
	$('#sex').html('');
	$('#birthdate').html('');
	$('#address').html('');
	$('#phone').html('');
}

function patSelect(patid) {
	$('#modal_patList').modal('hide');
	$('#modal_patEditor').modal('hide');
	let url = '<?=base_url('');?>api/patients/detail/'+patid;
	$.ajax({
		url: url,
		method: "GET",
		success: function(response) {
			let data = response['patient'];
			$("#patid").val(patid);
			$("#patnumber").val(data.PATNUMBER);
			$('#patname').html(data.PATNAME);
			$('#sex').html(data.SEX);
			$('#birthdate').html(data.BIRTHDATE);
			$('#address').html(data.ADDRESS);
			$('#phone').html(data.PHONE);
		},
		error: function(response) {
			alert(response.responseJSON.messages.errors);
		}
	});
}

function patCreate() {
	$('#modal_patList').modal('hide');
	$("#qpatid").val('0');
	$("#qpatnumber").val(patnumber);
	$("#qpatname").val("");
	$("#qsex").val("");
	$("#qbirthdate").val("");
	$("#qaddress").val(''); 
	$('#modal_patEditor').modal('show');
}

function patEdit(patid) {
	$('#modal_patList').modal('hide');
	let url = '<?=base_url('');?>api/patients/detail/'+patid;
	$.ajax({
		url: url,
		method: "GET",
		success: function(response) {
			let data = response['patient'];
			$("#qpatnumber").val(data.PATNUMBER);
			$("#qpatid").val(patid);
			$("#qpatname").val(data.PATNAME);
			$("#qsex").val(data.SEX);
			$("#qbirthdate").val(data.BIRTHDATE);
			$("#qaddress").val(data.ADDRESS); 
			$("#qphone").val(data.PHONE); 
			$("#modal_patEditor").modal('show'); 
		},
		error: function(response) {
			alert(response.responseJSON.messages.errors);
		}
	});
}

function patSearch() {
	patnumber = $("#patnumber").val();
	let url = '<?=base_url('');?>api/patients/search';
	$.ajax({
		url: url,
		method: "POST",
		data: {patnumber:patnumber},
		success: function(response) {
			$("#patList_tbody").html("");
			var data = response['patients'];
			datarow = '<tr> <td><button class="btn btn-sm btn-primary" onclick="patCreate(\''+patnumber+'\')"><i class="bi bi-plus-circle"></i> Create</button></td> </tr>';
			$("#patList_tbody").append(datarow);
			if(data.length != 0) {
				for (var i = 0; i < data.length; i++) {
					patid = data[i].PATID;
					qpatnumber = data[i].PATNUMBER;
					patname = data[i].PATNAME;
					sex = data[i].SEX;
					birthdate = data[i].BIRTHDATE;
					editBtn = '<button class="btn btn-sm btn-warning" ' + ' onclick="patEdit(\'' + patid + '\')">Edit' + '</button> ';
					selectBtn = '<button class="btn btn-sm btn-success" ' + ' onclick="patSelect(\'' + patid + '\')">Select' + '</button> ';
					if(data[i].LISCODE == null) { liscode = '-'; }
					let datarow = '<tr class="align-middle">' + 
						'<td>' + qpatnumber + '</td>' + '<td>' + patname+ '</td> <td>' + sex + '</td>' + '<td>' + birthdate+ '</td>' + '<td>' + selectBtn + editBtn + '</td>' +
					'</tr>';
					$("#patList_tbody").append(datarow);
				}
			}
			$('#modal_patList').modal('show');
		},
		error: function(response) {
			alert(response.responseJSON.messages.errors);
		}
	});	
}

function patSave() {
	patid = $("#qpatid").val();
	patnumber = $("#qpatnumber").val();
	patname = $("#qpatname").val();
	birthdate = $('#qbirthdate').val();
	sex = $('#qsex').val();
	address = $('#qaddress').val();
	phone = $('#qphone').val();	
	let data = { patid: patid, patnumber: patnumber, patname:patname, birthdate:birthdate, sex:sex, address:address, phone:phone };
	let url = '<?=base_url('');?>api/patients/save';
	$.ajax({
		url: url,
		method: "POST",
		data:data,
		success: function(response) {
			console.log(response);
			patSelect(patnumber);
		},
		error: function(response) {
			alert(response.responseJSON.messages.errors);
		}
	});
}

$(document).ready(function() {
	<?php
	for($i=1;$i<=50;$i++) {
		echo "$('.test$i').select2();";
	}
	?>
	
	flatpickr("#visitdate", { allowInput: true, enableTime: true, dateFormat: "Y-m-d H:i", time_24hr: true });
	
	$("#patnumber").keydown(function(event) {
		if (event.keyCode === 13) {
			patSearch();
		}
	});
	
	if( $('#orderid').val()!=0 ) {
		orderDetail($('#orderid').val());
	}
});
</script>
<?= $this->endSection() ?>