<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_consultation') ?>
		</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="consultation">
										<label>Consultation</label>
										<select class="form-control" name="health_care_sheet_id" required>
											<option value="" selected disabled> Choisissez la consultation</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 class="form-group row">
											<div class="col-md-6">
												<div class="form-group">
													<label><?= $this->lang->line('accident')?></label>
													<input type="checkbox" id="accident-checkbox">
												</div>
											</div>
											<div class="col-md-6">
												<div class="form-group">
													<label><?= $this->lang->line('pregnancy')?></label>
													<input type="checkbox" id="pregnancy-checkbox">
												</div>
											</div>
										</div>

										<div class="form-group" id="accident-div">
											<label><?= $this->lang->line('accident_date')?></label>
											<input class="form-control" name="accident_date" type="date">
										</div>

										<div class="form-group row" id="pregnancy-div">
											<div class="col-md-6">
												<div class="form-group">
													<label><?= $this->lang->line('pregnancy_start_at')?></label>
													<input class="form-control" name="pregnancy_start_at" type="date">
												</div>
											</div>
											<div class="col-md-6">
												<div class="form-group">
													<label><?= $this->lang->line('pregnancy_end_at')?></label>
													<input class="form-control" name="pregnancy_end_at" type="date">
												</div>
											</div>
										</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 class="form-group">
										<label><?= $this->lang->line('care_condition')?></label>
										<select class="form-control" name="care_condition" required>
											<option value="CURRENT_AFFECTION"> <?= $this->lang->line('CURRENT_AFFECTION')?></option>
											<option value="LONG_TERM_AFFECTION"> <?= $this->lang->line('LONG_TERM_AFFECTION')?></option>
											<option value="EXONERATION"> <?= $this->lang->line('EXONERATION')?></option>
										</select>
									</div>
								</div>

							</div>

							<div class="form-group mt-2" style="overflow-x:auto;">
								<div class="table-title">
									<div class="row">
										<div class="col-sm-8">
											<label for="nom"
												   class="col-form-label"><?= $this->lang->line('performances'); ?></label>
										</div>
										<div class="col-sm-4">
											<button type="button" class="btn btn-info add-new new1"><i
														class="fa fa-plus"></i> <?= $this->lang->line('new_prestation'); ?>
											</button>
										</div>
									</div>
								</div>
								<table id="prestations" class="table table-bordered">
									<thead>
									<tr>
										<th><?= $this->lang->line('act_code'); ?> </th>
										<th><?= $this->lang->line('Montant'); ?></th>
										<th><?= $this->lang->line('home_visit_fees'); ?></th>
										<th><?= $this->lang->line('moderator_ticket'); ?></th>
										<th><?= $this->lang->line('insurance_amount'); ?></th>
										<th>Actions</th>
									</tr>
									</thead>
									<tbody></tbody>
								</table>
							</div>
							<div class="form-group mt-4" style="overflow-x:auto;">
								<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 class="col-sm-4">
											<button type="button" class="btn btn-info add-new new2"><i
														class="fa fa-plus"></i> <?= $this->lang->line('new_exam'); ?>
											</button>
										</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>Actions</th>
									</tr>
									</thead>
									<tbody></tbody>
								</table>
							</div>

							<div class="form-group mt-4" style="overflow-x:auto;">
								<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 class="col-sm-4">
											<button type="button" class="btn btn-info add-new new3"><i
														class="fa fa-plus"></i> <?= $this->lang->line('new_prescription'); ?>
											</button>
										</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>Actions</th>
									</tr>
									</thead>
									<tbody>
									<?php
									if (isset($plr_prescriptions)) {
										foreach ($plr_prescriptions->result() as $row) {
											echo "<tr>
																	<td>" . $row->min . "</td>
																	<td>" . $row->max . "</td>
																	  <td>" . $row->taux . "</td>" . '
																	  <td>
																		<a class="add add3" title="Add" data-toggle="tooltip"><i class="material-icons">&#xE03B;</i></a>
																		<a class="edit edit3" title="Edit" data-toggle="tooltip"><i class="material-icons">&#xE254;</i></a>
																		<a class="delete delete3" title="Delete" data-toggle="tooltip"><i class="material-icons">&#xE872;</i></a>
																	</td>
																	 </tr>';
										}
									}
									?>
									</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';

	let network_id = "<?= $network_id ?>"
	var acts = []
	$(document).ready(function (){
		$('#consultation').hide();
		$('#patient-details').hide();
		$('#accident-div').hide();
		$('#pregnancy-div').hide();

		$('#accident-checkbox').change(function() {
			if($(this).is(":checked")) {
				$('#accident-div').show();
			}else{
				$('#accident-div').hide();
			}
		});

		$('#pregnancy-checkbox').change(function() {
			if($(this).is(":checked")) {
				$('#pregnancy-div').show();
			}else{
				$('#pregnancy-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'
					}));
				});
			});

			let beneficiary_id = null
			$('#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
				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" : "CONSULTATION",
							'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 la consultation</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')?>");
						}
					});
				});
				$('#consultation').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)
					$('#sheet-form').find('select[name="care_condition"]').val(consultation._care_condition)
					if(consultation.accident_date){
						$('#sheet-form').find('input[name="accident_date"]').val(consultation.accident_date);
						$('#accident-checkbox').prop("checked", true);
						$('#accident-div').show();
					}else{
						$('#sheet-form').find('input[name="accident_date"]').val(null);
						$('#accident-checkbox').prop("checked", false);
						$('#accident-div').hide();
					}

					if(consultation.pregnancy_start_at ||  consultation.pregnancy_end_at){
						$('#sheet-form').find('input[name="pregnancy_start_at"]').val(consultation.pregnancy_start_at);
						$('#sheet-form').find('input[name="pregnancy_end_at"]').val(consultation.pregnancy_end_at);
						$('#pregnancy-checkbox').prop("checked", true);
						$('#pregnancy-div').show();
					}else {
						$('#sheet-form').find('input[name="pregnancy_start_at"]').val(null);
						$('#sheet-form').find('input[name="pregnancy_end_at"]').val(null);
						$('#pregnancy-checkbox').prop("checked", false);
						$('#pregnancy-div').hide();
					}

					const actions1 = '<a class="add add1" title="Add" data-toggle="tooltip"><i class="material-icons">&#xE03B;</i></a>\n' +
									'<a class="edit edit1" title="Edit" data-toggle="tooltip"><i class="material-icons">&#xE254;</i></a>\n'+
										'<a class="delete delete1" title="Delete" data-toggle="tooltip"><i class="material-icons">&#xE872;</i></a>';

					$("#prestations tbody").children().remove();
					$.each(consultation.performances, function (j, it) {
						$('#prestations').append('<tr>' +
							'<td id="'+it.id+'" act_id="'+it.act.id+'" amount="'+it.act.amount+'">'+(it.act.name|| '')+'</td>' +
							'<td>'+(parseFloat(it.amount) || '')+'</td>' +
							'<td>'+(parseFloat(it.home_visit_fees) || '')+'</td>' +
							'<td>'+(it.moderator_ticket_formatted || '')+'</td>' +
							'<td>'+(it.insurance_amount_formatted || '')+'</td>' +
							'<td>'+actions1+'</td>' +
							'</tr>')
					});

					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'+
									'<a class="delete delete2" title="Delete" data-toggle="tooltip"><i class="material-icons">&#xE872;</i></a>';

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



					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'+
						            '<a class="delete delete3" title="Delete" data-toggle="tooltip"><i class="material-icons">&#xE872;</i></a>';

					$("#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>'+actions3+'</td>' +
							'</tr>')
					});

					$('#patient-details').show();

					fetchActs(currentInsurance.user.id, beneficiary_id);
				}
			});
		}else{
			history.back()
		}
	})


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

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

		$('#prestations 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('value');
					if(!arrayItem['act_id']){
						arrayItem['act_id'] = $(item).attr('act_id');
					}
				}
				if (index === 1)
					arrayItem['amount'] = parseFloat($(item).html());
				if (index === 2)
					arrayItem['home_visit_fees'] = parseFloat($(item).html()) || null;
			});
			prestations.push(arrayItem);
		});
		$('#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('value');
					if(!arrayItem['act_id']){
						arrayItem['act_id'] = $(item).attr('act_id');
					}
				}
				if (index === 1)
					arrayItem['description'] = $(item).html();
				// if (index === 2)
				// 	arrayItem['quantity'] = parseFloat($(item).html());
			});
			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('value');
					if(!arrayItem['drug_or_device_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());
			});
			prescriptions.push(arrayItem);
		});

		if(prestations.length === 0){
			return toastr.error("Vous devez saisir au moins une prestation", "<?= $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'];
		});

		indexed_array.beneficiary_id = parseInt(indexed_array.beneficiary_id) === 0 ? null : indexed_array.beneficiary_id;
		if (!$('#accident-checkbox').prop('checked')) {
			indexed_array.accident_date = null;
		}

		if (!$('#pregnancy-checkbox').prop('checked')) {
			indexed_array.pregnancy_start_at = null;
			indexed_array.pregnancy_end_at = null;
		}

		$.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 ?>",
				"performances": prestations, "exams": exams, "prescriptions": prescriptions,
			},
			success: function (data) {
				if(data.status === 200){
					Swal.fire({
						icon: 'success',
						title: "<?= $this->lang->line('consultation_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>

<!-- Common scripts-->
<?php $this->load->view('nano_health/agent/scripts') ?>
<script type="text/javascript">
	// Paliers scripts
	$(document).ready(function () {

		$('[data-toggle="tooltip"]').tooltip();

		var actions1 = $("#prestations td:last-child").html();
		// Append table with add row form on add new button click
		$(".new1").click(function () {
			if (!actions1) {
				actions1 = '<a class="add add1" title="Add" data-toggle="tooltip"><i class="material-icons">&#xE03B;</i></a>\n' +
						'                            <a class="edit edit1" title="Edit" data-toggle="tooltip"><i class="material-icons">&#xE254;</i></a>\n' +
						'                            <a class="delete delete1" title="Delete" data-toggle="tooltip"><i class="material-icons">&#xE872;</i></a>';
			}
			$(this).attr("disabled", "disabled");
			var index = $("#prestations tbody tr:last-child").index();
			var row = '<tr>' +
					'<td>' +
						'<select  required class="form-control" name="act_id" id="act">' +
								getActsOptions(null,'CONSULTATION')+
				        '</select>' +
				    '</td>' +
					'<td><input type="number" required class="form-control" name="amount" min="0" id="amount"></td>' +
					'<td><input type="number" class="form-control" name="home_visit_fees" id="fees" min="0"></td>' +
					'<td><input class="form-control" name="moderator_ticket" disabled id="moderator-ticket"></td>' +
					'<td><input class="form-control" name="insurance_amount" disabled id="insurance-amount"></td>' +
					'<td> ' + actions1 + '</td>' +
					'</tr>';
			$("#prestations").append(row);
			$("#prestations tbody tr").eq(index + 1).find(".add, .edit").toggle();
			$('[data-toggle="tooltip"]').tooltip();

			calculatePrestationsAmount();
			autoFetchPrestationAmount();
		});
		// Add row on add button click
		$(document).on("click", ".add1", 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();
				$(".new1").removeAttr("disabled");
			}

			select.each(function () {
				let selected = $(this).find('option:selected')
				$(this).parent("td").html(selected.text()).attr("value",$(this).val()).attr("amount",selected.data('amount'));
			});
		});
		// Edit row on edit button click
		$(document).on("click", ".edit1", function () {
			let amount = NaN
			$(this).parents("tr").find("td:not(:last-child)").each(function (index) {
				if (index === 0){
					let val = $(this).attr("value");
					if(!val){
						val = $(this).attr("act_id");
					}
					$(this).html('<select class="form-control" name="act_id" required >'+ getActsOptions(val,'CONSULTATION')+ '</select>');
					amount = parseFloat($(this).attr("amount"))
				}
				if (index == 1) {
					$(this).html(`<input type="number" required class="form-control" name="amount" min="0" id="amount" ${(isNaN(amount) ? '' : 'disabled')}  value="${$(this).text()}">`);
				}
				if (index === 2)
					$(this).html('<input type="number"  class="form-control" name="home_visit_fees" id="fees"  min="0" value="' + $(this).text() + '">');
				if (index === 3)
					$(this).html('<input class="form-control" name="moderator_ticket" disabled  id="moderator-ticket" value="' + $(this).text() + '">');
				if (index === 4)
					$(this).html('<input class="form-control" name="insurance_amount" disabled id="insurance-amount" value="' + $(this).text() + '">');

			});
			$(this).parents("tr").find(".add, .edit").toggle();
			$(".new1").attr("disabled", "disabled");
			calculatePrestationsAmount();
		});
		// Delete row on delete button click
		$(document).on("click", ".delete1", function () {
			$(this).parents("tr").remove();
			$(".new1").removeAttr("disabled");
			// Remove delete items
			$(this).parents("tr").find("td:not(:last-child)").each(function (index) {
				if (index === 0){
					var deletedItem = {};
					deletedItem['id'] = $(this).attr("id");
					if(deletedItem['id']){
						deletedItem['act_id'] = $(this).attr("act_id");
						deletedItem['amount'] = 0;
						deletedItem['to_delete'] = 1;
						prestations.push(deletedItem);
					}
				}
			});
		});

		// Table Examens

		var actions2 = $("#exams td:last-child").html();
		// Append table with add row form on add new button click
		$(".new2").click(function () {
			if (!actions2) {
				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' +
					'                            <a class="delete delete2" title="Delete" data-toggle="tooltip"><i class="material-icons">&#xE872;</i></a>';
			}
			$(this).attr("disabled", "disabled");
			var index = $("#exams tbody tr:last-child").index();
			var row = '<tr>' +
				'<td>' +
				'<select  required class="form-control" name="act_id" >' +
				getActsOptions(null,'EXAM_OR_OTHER')+
				'</select>' +
				'</td>' +
				'<td><input class="form-control" name="description"></td>' +
				// '<td><input class="form-control" name="quantity" min="1"  step="1" type="number"></td>' +
				'<td> ' + actions2 + '</td>' +
				'</tr>';
			$("#exams").append(row);
			$("#exams tbody tr").eq(index + 1).find(".add, .edit").toggle();
			$('[data-toggle="tooltip"]').tooltip();
		});
		// 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 == 0){
					let val = $(this).attr("value");
					if(!val){
						val = $(this).attr("act_id");
					}
					$(this).html('<select class="form-control" name="act_id" required >'+ getActsOptions(val,'EXAM_OR_OTHER')+ '</select>');
				}
				if (index == 1)
					$(this).html('<input class="form-control" name="description" value="' + $(this).text() + '">');
				// if (index == 2)
				// 	$(this).html('<input class="form-control" name="quantity"  min="1" step="1"   value="' + $(this).text() + '">');
			});
			$(this).parents("tr").find(".add, .edit").toggle();
			$(".new2").attr("disabled", "disabled");
		});
		// Delete row on delete button click
		$(document).on("click", ".delete2", function () {
			$(this).parents("tr").remove();
			$(".new2").removeAttr("disabled");
			// Remove delete items
			$(this).parents("tr").find("td:not(:last-child)").each(function (index) {
				if (index === 0){
					var deletedItem = {};
					deletedItem['id'] = $(this).attr("id");
					if(deletedItem['id']){
						deletedItem['act_id'] = $(this).attr("act_id");
						deletedItem['description'] = 'description';
						deletedItem['quantity'] = 1;
						deletedItem['to_delete'] = 1;
						exams.push(deletedItem);
					}
				}
			});
		});


		// Table prescription

		function getDrugAndDevicesOptions(selectedValue) {
			var actsOptions = '';
			<?php foreach ($drugs_and_devices->result() as $a ) {?>
			var id = <?= $a->id ?>;
			var selected = id === parseInt(selectedValue) ? 'selected' : '';
			actsOptions += (`<option value=<?= $a->id ?> ${selected} > <?= $a->name ?> </option>`);
			<?php } ?>
			return actsOptions;
		}

// Table prescriptions
		var actions3 = $("#prescriptions td:last-child").html();
// Append table with add row form on add new button click
		$(".new3").click(function () {
			if (!actions3) {
				actions3 = '<a class="add add3" title="Add" data-toggle="tooltip"><i class="material-icons">&#xE07B;</i></a>\n' +
						'                            <a class="edit edit3" title="Edit" data-toggle="tooltip"><i class="material-icons">&#xE254;</i></a>\n' +
						'                            <a class="delete delete3" title="Delete" data-toggle="tooltip"><i class="material-icons">&#xE872;</i></a>';
			}
			$(this).attr("disabled", "disabled");
			var index = $("#prescriptions tbody tr:last-child").index();
			var row = '<tr>' +
					'<td>' +
						'<select  required class="form-control" name="drug_or_device_id" >' +
							getDrugAndDevicesOptions(null)+
						'</select>' +
					'</td>' +
					'<td><input required class="form-control" name="dosage" ></td>' +
					'<td><input type="number" required class="form-control" min="1" step="1" name="quantity"></td>' +
					'<td> ' + actions3 + '</td>' +
					'</tr>';
			$("#prescriptions").append(row);
			$("#prescriptions tbody tr").eq(index + 1).find(".add, .edit").toggle();
			$('[data-toggle="tooltip"]').tooltip();
		});
// 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 == 0){
					let val = $(this).attr("value");
					if(!val){
						val = $(this).attr("drug_or_device_id");
					}
					$(this).html('<select class="form-control" name="drug_or_device_id" required >'+ getDrugAndDevicesOptions(val)+ '</select>');
				}
				if (index == 1)
					$(this).html('<input required class="form-control" name="dosage" value="' + $(this).text() + '">');
				if (index == 2)
					$(this).html('<input type="number" required class="form-control" name="quantity"  min="1" step="1" value="' + $(this).text() + '">');
			});
			$(this).parents("tr").find(".add, .edit").toggle();
			$(".new3").attr("disabled", "disabled");
		});
// Delete row on delete button click
		$(document).on("click", ".delete3", function () {
			$(this).parents("tr").remove();
			$(".new3").removeAttr("disabled");
			// Remove delete items
			$(this).parents("tr").find("td:not(:last-child)").each(function (index) {
				if (index === 0){
					var deletedItem = {};
					deletedItem['id'] = $(this).attr("id");
					if(deletedItem['id']){
						deletedItem['drug_or_device_id'] = $(this).attr("drug_or_device_id");
						deletedItem['dosage'] = 'dosage';
						deletedItem['quantity'] = 1;
						deletedItem['to_delete'] = 1;
						prescriptions.push(deletedItem);
					}
				}
			});
		});
	});
</script>
