<link rel="stylesheet"
	  href="<?= base_url('bower_components/bootstrap-datepicker/dist/css/bootstrap-datepicker.min.css') ?>">
<link rel="stylesheet" href="<?= base_url('bower_components/bootstrap-daterangepicker/daterangepicker.css') ?>">
<link rel="stylesheet"
	  href="<?= base_url('<link rel="stylesheet" 
	href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap.min.css">') ?>">
<link rel="stylesheet" href="<?= base_url('bower_components/toastr/toastr.css') ?>">

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">


<link rel="stylesheet" href="<?= base_url('dist/css/custom/levels-table.css') ?>">
<?php

use Brick\Money\Context\CustomContext;
use Brick\Money\Money;

$context = new \Brick\Money\Context\AutoContext();
$fmt = new NumberFormatter('fr_FR', NumberFormatter::DECIMAL);
?>

<div class="content-wrapper">
	<!-- Content Header (Page header) -->
	<section class="content-header">

		<h1>
			<?= $this->lang->line('update_execution') ?>
		</h1>

	</section>

	<section class="content">
		<div class="row">
			<!-- left column -->
			<div class="col-md-12">
				<!-- general form elements -->
				<div class="box box-primary">
					<div class="box-header with-border">
						<h3 class="box-title">Formulaire</h3>
					</div>
					<!-- /.box-header -->
					<!-- form start -->
					<form id="sheet-form">
						<div class="box-body">
							<div class="row" style="margin-bottom: 30px">
								<div class="col-md-6">
									<div class="form-group">
										<label><?= $this->lang->line('one_insured')?></label>
										<select class="form-control" name="insured_id" required>
											<option value="" selected disabled> Choisissez l'assuré</option>
										</select>
									</div>
									<div class="form-group" id="execution">
										<label>Execution</label>
										<select class="form-control" name="health_care_sheet_id" required>
											<option value="" selected disabled> Choisissez l'execution</option>
										</select>
									</div>
									<div id="patient-details">
										<div class="form-group">
											<label><?= $this->lang->line('patient_lastname')?></label>
											<input class="form-control" name="patient_lastname" disabled>
										</div>
										<div class="form-group">
											<label><?= $this->lang->line('patient_firstname')?></label>
											<input class="form-control" name="patient_firstname" disabled>
										</div>
									</div>

								</div>

								<div class="col-md-6">
									<div class="form-group">
										<label><?= $this->lang->line('practitioner_lastname')?></label>
										<input class="form-control" name="practitioner_lastname" required>
									</div>
									<div class="form-group">
										<label><?= $this->lang->line('practitioner_firstname')?></label>
										<input class="form-control" name="practitioner_firstname">
									</div>
									<div class="form-group">
										<label>Classification</label>
										<select required class="form-control" name="practitioner_provider_class_id">
											<?php foreach ($provider_classes->result() as $row) { ?>
												<option value="<?=$row->id ?>"> <?= $row->name ?></option>
											<?php } ?>
										</select>
									</div>
								</div>

							</div>

							<div class="form-group mt-4" style="overflow-x:auto;" id="exams-div">
								<div class="table-title">
									<div class="row">
										<div class="col-sm-8">
											<label for="nom"
												   class="col-form-label"><?= $this->lang->line('exams'); ?></label>
										</div>
									</div>
								</div>
								<table id="exams" class="table table-bordered">
									<thead>
									<tr>
										<th><?= $this->lang->line('exam_class'); ?></th>
										<th><?= $this->lang->line('exam_description'); ?></th>
										<th><?= $this->lang->line('quantity'); ?></th>
										<th><?= $this->lang->line('UNIT_PRICE'); ?></th>
										<th>Actions</th>
									</tr>
									</thead>
									<tbody>
									</tbody>
								</table>
							</div>

							<div class="form-group mt-4" style="overflow-x:auto;" id="prescriptions-div">
								<div class="table-title">
									<div class="row">
										<div class="col-sm-8">
											<label for="nom"
												   class="col-form-label"><?= $this->lang->line('medical_prescriptions'); ?></label>
										</div>
									</div>
								</div>
								<table id="prescriptions" class="table table-bordered">
									<thead>
									<tr>
										<th><?= $this->lang->line('drugs_or_device'); ?></th>
										<th><?= $this->lang->line('dosage'); ?></th>
										<th><?= $this->lang->line('quantity'); ?></th>
										<th><?= $this->lang->line('UNIT_PRICE'); ?></th>
										<th>Actions</th>
									</tr>
									</thead>
									<tbody>
									</tbody>
								</table>
							</div>

							<div class="form-group">
								<label><?= $this->lang->line('mot de passe')?></label>
								<input type="password" class="form-control" name="password" required>
							</div>
						</div>
						<!-- /.box-body -->

						<div class="box-footer">
							<button type="submit" class="btn btn-primary"><?= $this->lang->line('save'); ?></button>
<!--							<button type="button" class="btn btn-default pull-left"-->
<!--									data-dismiss="modal">--><?php //echo $this->lang->line('Fermer'); ?><!--</button>-->
						</div>
					</form>
				</div>
				<!-- /.box -->
			</div>
		</div>
	</section>
</div>

<!-- jQuery 2.2.4 -->
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>

<!-- Bootstrap 3.3.7 -->
<script src="<?= base_url('bower_components/bootstrap/dist/js/bootstrap.min.js') ?>"></script>
<!-- DataTables -->
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap.min.js"></script>
<!-- Slimscroll -->
<script src="<?= base_url('bower_components/jquery-slimscroll/jquery.slimscroll.min.js') ?>"></script>
<!-- FastClick -->
<script src="<?= base_url('bower_components/fastclick/lib/fastclick.js') ?>"></script>
<!-- AdminLTE App -->
<script src="<?= base_url('dist/js/adminlte.min.js') ?>"></script>
<!-- AdminLTE for demo purposes -->
<script src="<?= base_url('dist/js/demo.js') ?>"></script>

<script src="<?= base_url('bower_components/moment/min/moment.min.js') ?>"></script>
<script src="<?= base_url('bower_components/bootstrap-daterangepicker/daterangepicker.js') ?>"></script>
<script src="<?= base_url('bower_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js') ?>"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
<!-- ChartJS -->
<script src="<?= base_url('bower_components/chart.js/Chart.js') ?>"></script>
<script src="<?= base_url('bower_components/toastr/toastr.js') ?>"></script>
<script src="<?= base_url('dist/js/sweetalert2.js') ?>"></script>

<script>
	toastr.options.closeButton = true;
	toastr.options.closeMethod = 'fadeOut';
	toastr.options.closeDuration = 5000;
	toastr.options.closeEasing = 'swing';

	$(document).ready(function (){
		$('#execution').hide();
		$('#patient-details').hide();
		$('#prescriptions-div').hide();
		$('#exams-div').hide();
		// Get The Data
		const insured = JSON.parse(sessionStorage.getItem('insured'));
		if(insured && Array.isArray(insured)){
			var currentInsurance = null;
			var consultations = [];

			$.each(insured, function (i, item) {
				$('#sheet-form').find('select[name="insured_id"]').append($('<optgroup>', {
					label: 'Assuré principal',
				}));
				$('#sheet-form').find('select[name="insured_id"]').append($('<option>', {
					insured_id : item.insured_id,
					value: 0,
					text : item.insured_id+' - '+item.user.lastname +' '+(item.user.firstname || '') + (item.state === 'SUSPENDED' ? " - <?= $this->lang->line('SUSPENDED') ?>" : ''),
					disabled : item.state === 'SUSPENDED'
				}));
				$('#sheet-form').find('select[name="insured_id"]').append($('<optgroup>', {
					label: 'Ayants droits',
				}));
				$.each(item.beneficiaries, function (j, it) {
					$('#sheet-form').find('select[name="insured_id"]').append($('<option>', {
						insured_id : item.insured_id,
						value: it.id,
						text : item.insured_id+' - '+it.lastname +' '+(it.firstname || '') + (item.state === 'SUSPENDED' ? " - <?= $this->lang->line('SUSPENDED') ?>" : ''),
						disabled : item.state === 'SUSPENDED'
					}));
				});
			});

			$('#sheet-form').find('select[name="insured_id"]').change(function () {
				 let insurance = insured.filter(i => i.insured_id === $(this).find(":selected").attr('insured_id'));
				 // Definir benficiary_id to null si c'est l'assuré principal
				 let beneficiary_id = parseInt($(this).val()) === 0 ? null : $(this).val();
				 $.each(insurance, function (i, item) {
					currentInsurance = item;
					 $.ajax({
						 url: '<?= base_url('NanoHealthController/getHealthCareSheets')?>',
						 type: 'POST',
						 dataType: 'json',
						 data: {
							 "user_id" : item.user.id, "beneficiary_id" : beneficiary_id, "state" : "UNTREATED" , "type" : "EXECUTION",
							 'network_agent_id' : "<?= $network_agent_id ?>"
						 },
						 success: function (data) {
							 if(data.status === 200){
								 consultations = data.response;
								 $('#sheet-form').find('select[name="health_care_sheet_id"]').children().remove().end()
									 .append('<option selected disabled value="">Choisissez l\'execution</option>');

								 $.each(consultations, function (j, it) {
								 	$('#sheet-form').find('select[name="health_care_sheet_id"]').append($('<option>', {
								 		value: it.id,
								 		text : it.health_care_sheet_id +' - '+it.patient_lastname+' '+(it.patient_firstname || '')
								 	}));
								 });
							 }else{
								 toastr.error(data.error , "<?= $this->lang->line('request_error')?>");
							 }
						 },
						 error: function (resultat, statut, error) {
							 console.log(resultat + " " + error);
							 toastr.error("<?= $this->lang->line('error_message')?>", "<?= $this->lang->line('request_error')?>");
						 }
					 });
				});
				$('#execution').show();
			});

			$('#sheet-form').find('select[name="health_care_sheet_id"]').change(function () {
				var val = parseInt($(this).val());
				const result = consultations.filter(function(c) {
					return c.id === val
				});

				if(result.length > 0){
					const consultation = result[0];
					$('#sheet-form').find('input[name="patient_lastname"]').val(consultation.patient_lastname || '')
					$('#sheet-form').find('input[name="patient_firstname"]').val(consultation.patient_firstname || '')
					$('#sheet-form').find('input[name="practitioner_lastname"]').val(consultation.practitioner_lastname || '')
					$('#sheet-form').find('input[name="practitioner_firstname"]').val(consultation.practitioner_firstname || '')
					$('#sheet-form').find('select[name="practitioner_provider_class_id"]').val(consultation.practitioner_provider_class_id)

					if(consultation.exams.length !== 0){
						$('#exams-div').show();
					}else{
						$('#exams-div').hide();
					}
					const actions2 = '<a class="add add2" title="Add" data-toggle="tooltip"><i class="material-icons">&#xE03B;</i></a>\n' +
						'                            <a class="edit edit2" title="Edit" data-toggle="tooltip"><i class="material-icons">&#xE254;</i></a>\n';

					$("#exams tbody").children().remove();
					$.each(consultation.exams, function (j, it) {
						$('#exams').append('<tr>' +
							'<td id="'+it.id+'" act_id="'+it.act.id+'">'+(it.act.code|| '')+'</td>' +
							'<td>'+(it.description || '')+'</td>' +
							'<td>'+(it.quantity || '')+'</td>' +
							'<td>'+(parseFloat(it.unit_price) || '')+'</td>' +
							'<td>'+actions2+'</td>' +
							'</tr>')
					});


					if(consultation.prescriptions.length !== 0){
						$('#prescriptions-div').show();
					}else{
						$('#prescriptions-div').hide();
					}
					const actions3 = '<a class="add add3" title="Add" data-toggle="tooltip"><i class="material-icons">&#xE03B;</i></a>\n' +
							'                            <a class="edit edit3" title="Edit" data-toggle="tooltip"><i class="material-icons">&#xE254;</i></a>\n';

					$("#prescriptions tbody").children().remove();
					$.each(consultation.prescriptions, function (j, it) {
						$('#prescriptions').append('<tr>' +
							'<td id="'+it.id+'" drug_or_device_id="'+it.drug_or_device.id+'">'+(it.drug_or_device.name|| '')+'</td>' +
							'<td>'+(it.dosage || '')+'</td>' +
							'<td>'+(it.quantity || '')+'</td>' +
							'<td>'+(parseFloat(it.unit_price) || '')+'</td>' +
							'<td>'+actions3+'</td>' +
							'</tr>')
					});

					$('#patient-details').show();
				}
			});
		}else{
			history.back()
		}
	})


	$("#sheet-form").submit(function(e){
		e.preventDefault();

		// Paliers
		var exams = [];
		var prescriptions = [];

		$('#exams tr').has('td').each(function () {
			var arrayItem = {};
			$('td', $(this)).each(function (index, item) {
				if (index === 0){
					arrayItem['id'] = $(item).attr('id');
					arrayItem['act_id'] = $(item).attr('act_id');
				}
				if (index === 1)
					arrayItem['description'] = $(item).html();
				if (index === 2)
					arrayItem['quantity'] = parseFloat($(item).html());
				if (index === 3)
					arrayItem['unit_price'] = parseFloat($(item).html());
			});
			if(!isNaN(arrayItem['unit_price'])){
				exams.push(arrayItem);
			}
		});
		$('#prescriptions tr').has('td').each(function () {
			var arrayItem = {};
			$('td', $(this)).each(function (index, item) {
				if (index === 0){
					arrayItem['id'] = $(item).attr('id');
					arrayItem['drug_or_device_id'] = $(item).attr('drug_or_device_id');
				}
				if (index === 1)
					arrayItem['dosage'] = $(item).html();
				if (index === 2)
					arrayItem['quantity'] = parseFloat($(item).html());
				if (index === 3)
					arrayItem['unit_price'] = parseFloat($(item).html());
			});
			if(!isNaN(arrayItem['unit_price'])){
				prescriptions.push(arrayItem);
			}
		});

		if(exams.length === 0 && prescriptions.length === 0){
			return toastr.error("<?= $this->lang->line('execution_rule_1')?>", "<?= $this->lang->line('request_error')?>");
		}
		if(exams.length !== 0 && prescriptions.length !== 0){
			return toastr.error("<?= $this->lang->line('execution_rule_2')?>", "<?= $this->lang->line('request_error')?>");
		}

		var unindexed_array = $(this).serializeArray();
		var indexed_array = {};

		$.map(unindexed_array, function(n, i){
			indexed_array[n['name']] = n['value'];
		});
		

		$.ajax({
			url: '<?= base_url('NanoHealthController/updateHealthCareSheet/')?>'+indexed_array.health_care_sheet_id,
			type: 'POST',
			dataType: 'json',
			data: {
				...indexed_array, "network_agent_id" : "<?= $network_agent_id ?>",
				"exams": exams, "prescriptions": prescriptions,
			},
			success: function (data) {
				if(data.status === 200){
					Swal.fire({
						icon: 'success',
						title: "<?= $this->lang->line('execution_updated')?>",
						text:"<?= $this->lang->line('informations_updated')?>",
						timer: 3000
					}).then(()=>{
						location.reload();
					});
				}else{
					toastr.error(data.error , "<?= $this->lang->line('request_error')?>");
				}
			},
			error: function (resultat, statut, error) {
				console.log(resultat + " " + error);
				toastr.error("<?= $this->lang->line('error_message')?>", "<?= $this->lang->line('request_error')?>");
			}
		});
	});

</script>
<script type="text/javascript">
	// Paliers scripts
	$(document).ready(function () {
		
		$('[data-toggle="tooltip"]').tooltip();

		// Table Examens

		// Add row on add button click
		$(document).on("click", ".add2", function () {
			var empty = false;
			var input = $(this).parents("tr").find('input');
			var select = $(this).parents("tr").find('select');

			input.each(function () {
				if (!$(this)[0].checkValidity()) {
					$(this).addClass("error");
					$(this)[0].reportValidity();
					empty = true;
				} else {
					$(this).removeClass("error");
				}
			});
			$(this).parents("tr").find(".error").first().focus();
			if (!empty) {
				input.each(function () {
					$(this).parent("td").html($(this).val());
				});
				$(this).parents("tr").find(".add, .edit").toggle();
				$(".new2").removeAttr("disabled");
			}

			select.each(function () {
				$(this).parent("td").html($(this).find('option:selected').text()).attr("value",$(this).val());
			});
		});
		// Edit row on edit button click
		$(document).on("click", ".edit2", function () {
			$(this).parents("tr").find("td:not(:last-child)").each(function (index) {
				if (index == 3)
					$(this).html('<input class="form-control" name="unit_price"  min="1" step="1" required value="' + $(this).text() + '">');
			});
			$(this).parents("tr").find(".add, .edit").toggle();
			$(".new2").attr("disabled", "disabled");
		});


		// Table prescription

// Table prescriptions
		var actions3 = $("#prescriptions td:last-child").html();

// Add row on add button click
		$(document).on("click", ".add3", function () {
			var empty = false;
			var input = $(this).parents("tr").find('input');
			var select = $(this).parents("tr").find('select');

			input.each(function () {
				if (!$(this)[0].checkValidity()) {
					$(this).addClass("error");
					$(this)[0].reportValidity();
					empty = true;
				} else {
					$(this).removeClass("error");
				}
			});
			$(this).parents("tr").find(".error").first().focus();
			if (!empty) {
				input.each(function () {
					$(this).parent("td").html($(this).val());
				});
				$(this).parents("tr").find(".add, .edit").toggle();
				$(".new3").removeAttr("disabled");
			}
			select.each(function () {
				$(this).parent("td").html($(this).find('option:selected').text()).attr("value",$(this).val());
			});
		});
// Edit row on edit button click
		$(document).on("click", ".edit3", function () {
			$(this).parents("tr").find("td:not(:last-child)").each(function (index) {
				if (index == 3)
					$(this).html('<input type="number" required class="form-control" name="unit_price" required  min="1" step="1" value="' + $(this).text() + '">');
			});
			$(this).parents("tr").find(".add, .edit").toggle();
			$(".new3").attr("disabled", "disabled");
		});

	});
</script>
