<link rel="stylesheet"
	  href="<?= base_url('bower_components/bootstrap-datepicker/dist/css/bootstrap-datepicker.min.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="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/css/bootstrap-multiselect.css">
<link rel="stylesheet" href="https://cdn.datatables.net/select/1.3.1/css/select.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.6.2/css/buttons.dataTables.min.css">
<link rel="stylesheet"
	  href="<?= base_url('bower_components/jquery-ui/themes/base/jquery-ui.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') ?>">

<div class="content-wrapper">
	<section class="content-header">

		<h1 style="margin-bottom: 20px">
			<?= $this->lang->line('invoice_detail') . ' - ' . $invoice->invoice_id; ?>

			<div class="pull-right">
				<a href="<?=$invoice->file_url?>" class="btn btn-primary mr-3" target="_blank">
					<?= $this->lang->line('download') ?>
				</a>
				<?php if($invoice->state == 'UNDER_VALIDATION') { ?>
					<button id="accept-invoice" class="btn btn-success" >
						<?= $this->lang->line('accept') ?>
					</button>
					<button id="accept-and-update-invoice" class="btn btn-warning"  data-toggle="modal" data-target="#accept-update-modal">
						<?= $this->lang->line('accept_and_update') ?>
					</button>
					<button class="btn btn-danger" data-toggle="modal" data-target="#reject-modal">
						<?= $this->lang->line('reject') ?>
					</button>
				<?php } ?>
			</div>
		</h1>



		<?php

		use Brick\Money\Context\AutoContext;
		use Brick\Money\CurrencyConverter;
		use Brick\Money\ExchangeRateProvider\BaseCurrencyProvider;
		use Brick\Money\ExchangeRateProvider\PDOProvider;
		use Brick\Money\ExchangeRateProvider\PDOProviderConfiguration;
		use Brick\Money\Money;

		// set to whatever your rates are relative to
		$baseCurrency = 'USD';

		// use your own credentials, or re-use your existing PDO connection
		$pdo = new PDO('mysql:host=' . $this->db->hostname . ';dbname=' . $this->db->database, $this->db->username, $this->db->password);

		$configuration = new PDOProviderConfiguration();

		$configuration->tableName = 'exchange_rate';
		$configuration->exchangeRateColumnName = 'exchange_rate';
		$configuration->targetCurrencyColumnName = 'target_currency';
		$configuration->sourceCurrencyCode = $baseCurrency;

		// this provider loads exchange rates from your database
		$provider = new PDOProvider($pdo, $configuration);

		// this provider calculates exchange rates relative to the base currency
		$provider = new BaseCurrencyProvider($provider, $baseCurrency);

		// this currency converter can now handle any currency pair
		$this->converter = new CurrencyConverter($provider);
		$this->context = new AutoContext();
		$fmt = new NumberFormatter('fr_FR', NumberFormatter::DECIMAL);
		?>
	</section>

	<section class="content">
		<div class="box box-success">
			<div class="box-header with-border">
				<h3 class="box-title"><?= $this->lang->line('issuer_information')?></h3>
			</div>
			<div class="box-body row" style="overflow-x:auto;">
				<div class="col-lg-6" style="padding-left: 25px;">
					<table style="width: 100%">
						<colgroup>
							<col span="1" style="width: 30%;">
							<col span="1" style="width: 70%;">
						</colgroup>
						<thead>
						<tr>
							<th></th>
							<th></th>
						</tr>
						</thead>
						<tbody>
						<tr>
							<td><?= $this->lang->line('Nom'); ?></td>
							<td style="text-align: center"><strong><?= $agent->lastname ?? ''?></strong></td>
						</tr>

						<tr>
							<td><?= $this->lang->line('Adresse')?></td>
							<td style="text-align: center"><strong><?= $agent->code_membre ?></strong></td>
						</tr>
						<tr>
							<td><?= $this->lang->line('Contact')?></td>
							<td style="text-align: center"><strong><?= $agent->phone." | ".$agent->email ?></strong></td>
						</tr>
						</tbody>
					</table>
				</div>
				<div class="col-lg-6" style="padding-left: 25px;">
					<table style="width: 100%">
						<colgroup>
							<col span="1" style="width: 30%;">
							<col span="1" style="width: 70%;">
						</colgroup>
						<thead>
						<tr>
							<th></th>
							<th></th>
						</tr>
						</thead>
						<tbody>

						</tbody>
					</table>
				</div>
			</div>
		</div>

		<div class="row">
			<div class="col-lg-4 col-xs-6">
				<div class="small-box bg-blue-active">
					<div class="inner">
						<h3 style="white-space: pre-wrap; font-size: 1.9em;"><?=Money::of(round($invoice->insured_amount, 2), $invoice->currency_code, $this->context)->formatTo('fr_FR')?> </h3>
						<p><?= $this->lang->line('percentage_insured') ?></p>
					</div>
					<div class="icon">
						<i class="fa fa-money"></i>
					</div>
				</div>
			</div>

			<div class="col-lg-4 col-xs-6">
				<div class="small-box bg-blue-active">
					<div class="inner">
						<h3 style="white-space: pre-wrap; font-size: 1.9em;"><?= Money::of(round($invoice->insurer_amount, 2), $invoice->currency_code, $this->context)->formatTo('fr_FR')?> </h3>
						<p><?= $this->lang->line('percentage_insurer') ?></p>
					</div>
					<div class="icon">
						<i class="fa fa-money"></i>
					</div>
				</div>
			</div>

			<div class="col-lg-4 col-xs-6">
				<div class="small-box bg-light-blue">
					<div class="inner">
						<h3 style="white-space: pre-wrap; font-size: 1.9em;"><?= $this->lang->line($invoice->state) ?> </h3>
						<p><?= $this->lang->line('state') ?></p>
					</div>
					<div class="icon">
						<i class="fa fa-clock-o"></i>
					</div>
				</div>
			</div>

		</div>

		<?php if($invoice->state == 'ACCEPTED_MODIFIED') { ?>
		<div class="row">
			<div class="col-lg-12 col-xs-6">
				<div class="small-box bg-yellow-active">
					<div class="inner">
						<h3 style="white-space: pre-wrap; font-size: 1.9em;"><?=$invoice->reason?> </h3>
						<p><?= $this->lang->line('reason') ?></p>
					</div>
					<div class="icon">
						<i class="fa fa-file-medical"></i>
					</div>
				</div>
			</div>
		</div>
		<?php } ?>

		<div class="box box-primary">
			<div class="box-header with-border">
				<h3 class="box-title"><?= $this->lang->line('health_care_sheets') ?></h3>
			</div>
			<div class="box-body" style="overflow-x:auto;">
				<table id="example1" class="table table-bordered table-hover">
					<thead>
					<tr>
						<th>ID</th>
						<th>Type</th>
						<th>Patient</th>
						<th><?= $this->lang->line('practitioner'); ?></th>
						<th><?= $this->lang->line('insured_id'); ?></th>
						<th><?= $this->lang->line('total_amount'); ?></th>
						<th><?= $this->lang->line('total_insured_part'); ?></th>
						<th><?= $this->lang->line('total_insurance_part'); ?></th>
						<th>Actions</th>
					</tr>
					</thead>
					<tbody>
					<?php
					if (isset($health_care_sheets)) {
						foreach ($health_care_sheets->result() as $i => $row) {
							$amount = Money::of(round($row->insurance_amount + $row->insured_amount, 2), $invoice->currency_code, $this->context)->formatTo('fr_FR');
							$insurance_amount = Money::of(round($row->insurance_amount, 2), $invoice->currency_code, $this->context)->formatTo('fr_FR');
							$insured_amount = Money::of(round($row->insured_amount, 2), $invoice->currency_code, $this->context)->formatTo('fr_FR');

							echo "<tr>
												<td>" . ($row->health_care_sheet_id) . "</td>
												<td>" . $row->type . "</td>
												<td>" . $row->patient_lastname.' '.$row->patient_firstname . "</td>
											   <td>" . $row->practitioner_lastname.' '.$row->practitioner_firstname . "</td>
                                               <td>".$row->insured_id."</td>
                                                <td>".$amount."</td>
                                                 <td>".$insured_amount."</td>
                                               <td>" . $insurance_amount. "</td>";
							?>

							<td>
										<button class="btn btn-primary" onclick="openSheetDetails(<?=$row->id?>)">
											<?= $this->lang->line('show'); ?>
										</button>
								</td>
							</tr>
							<?php
						}
					}
					?>
					</tbody>
				</table>
			</div>
		</div>
		<div class="modal fade" id="reject-modal">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal" aria-label="Close">
							<span aria-hidden="true">&times;</span>
						</button>
						<h4 class="modal-title"><?= $this->lang->line('reject_invoice') ?></h4>
					</div>
					<div class="modal-body">
						<form id="reject-form">
							<div class="row">
								<div class="col-lg-12">
									<div class="form-group">
										<label class="col-form-label"><?= $this->lang->line('reject_reason'); ?></label>
										<textarea required class="form-control" rows="5" name="reason"></textarea>
									</div>
								</div>
							</div>
						</form>
					</div>
					<div class="modal-footer">
						<button class="btn btn-danger pull-left"
								id="reject-invoice"><?= $this->lang->line('Confirmer'); ?></button>
						<button type="button" class="btn btn-default pull-right"
								data-dismiss="modal"><?= $this->lang->line('Fermer'); ?></button>
					</div>
				</div>
			</div>
		</div>
		<div class="modal fade" id="accept-update-modal">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal" aria-label="Close">
							<span aria-hidden="true">&times;</span>
						</button>
						<h4 class="modal-title"><?= $this->lang->line('accept_and_update_invoice') ?></h4>
					</div>
					<div class="modal-body">
						<form id="update-form">
							<div class="row">
								<div class="col-lg-12">
									<div class="form-group">
										<label class="col-form-label"><?= $this->lang->line('reason'); ?></label>
										<textarea required class="form-control" rows="5" name="update-reason"></textarea>
									</div>
								</div>
							</div>
						</form>
					</div>
					<div class="modal-footer">
						<button class="btn btn-danger pull-left"
								id="update-invoice"><?= $this->lang->line('Confirmer'); ?></button>
						<button type="button" class="btn btn-default pull-right"
								data-dismiss="modal"><?= $this->lang->line('Fermer'); ?></button>
					</div>
				</div>
			</div>
		</div>
		<div class="modal fade" id="consultation-sheet-modal">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal" aria-label="Close">
							<span aria-hidden="true">&times;</span>
						</button>
						<h4 class="modal-title"><?= $this->lang->line('health_care_sheet_infos') ?></h4>
					</div>
					<div class="modal-body">
						<form class="sheet-form">
							<div class="row" style="overflow-x:auto;" id="details">
								<div class="col-lg-6" style="padding-left: 25px;">
									<table style="width: 100% ; border-collapse: separate; border-spacing: 0.4em;">
										<colgroup>
											<col span="1" style="width: 30%;">
											<col span="1" style="width: 70%;">
										</colgroup>
										<thead>
										<tr>
											<th style="text-align: center"><strong>Patient</strong></th>
											<th></th>
										</tr>
										</thead>
										<tbody>
										<tr>
											<td><?= $this->lang->line('insured'); ?></td>
											<td><strong class="insured"></strong></td>
										</tr>
										<tr>
											<td><?= $this->lang->line('patient_lastname'); ?></td>
											<td><strong class="patient-lastname"></strong></td>
										</tr>
										<tr>
											<td><?= $this->lang->line('patient_situation')?></td>
											<td><strong class="patient-situation"></strong></td>
										</tr>
										</tbody>
									</table>
								</div>
								<div class="col-lg-6" style="padding-left: 25px;">
									<table style="width: 100% ;border-collapse: separate; border-spacing: 0.4em;">
										<colgroup>
											<col span="1" style="width: 30%;">
											<col span="1" style="width: 70%;">
										</colgroup>
										<thead>
										<tr>
											<th><?=$this->lang->line('practitioner') ?></th>
											<th></th>
										</tr>
										</thead>
										<tbody>
										<tr>
											<td><?= $this->lang->line('institution'); ?></td>
											<td><strong class="institution"></strong></td>
										</tr>
										<tr>
											<td><?= $this->lang->line('practitioner_lastname'); ?></td>
											<td><strong class="practitioner-lastname"></strong></td>
										</tr>
										<tr>
											<td>Classification</td>
											<td><strong class="classification"></strong></td>
										</tr>
										<tr>
											<td><?= $this->lang->line('care_condition')?></td>
											<td><strong class="care-condition"></strong></td>
										</tr>
										<div class="accident-div">
											<tr>
												<td><?= $this->lang->line('accident_date'); ?></td>
												<td><strong class="accident_date"></strong></td>
											</tr>
										</div>

										<div class="pregnancy-div">
											<tr>
												<td><?= $this->lang->line('pregnancy_start_at'); ?></td>
												<td><strong class="pregnancy_start_at"></strong></td>
											</tr>
											<tr>
												<td><?= $this->lang->line('pregnancy_end_at'); ?></td>
												<td><strong class="pregnancy_end_at"></strong></td>
											</tr>
										</div>
										</tbody>
									</table>
								</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>
								</div>
								<table id="consultation-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>
										<?php if($invoice->state == 'UNDER_VALIDATION') { ?>
											<th>Actions</th>
										<?php } ?>
									</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>
								</div>
								<table id="consultation-exams" class="table table-bordered">
									<thead>
									<tr>
										<th width="50"><?= $this->lang->line('exam_class'); ?></th>
										<th><?= $this->lang->line('exam_description'); ?></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>
								</div>
								<table id="consultation-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>

									</tr>
									</thead>
									<tbody></tbody>
								</table>
							</div>
						</form>
					</div>
					<div class="modal-footer">
						<?php if($invoice->state == 'UNDER_VALIDATION') { ?>
							<button class="btn btn-danger pull-left" onclick="onSheetSave()">
								<?= $this->lang->line('save'); ?>
							</button>
						<?php } ?>
						<button type="button" class="btn btn-default pull-right"
								data-dismiss="modal"><?= $this->lang->line('Fermer'); ?></button>
					</div>
				</div>
			</div>
		</div>
		<div class="modal fade" id="execution-sheet-modal">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal" aria-label="Close">
							<span aria-hidden="true">&times;</span>
						</button>
						<h4 class="modal-title"><?= $this->lang->line('health_care_sheet_infos') ?></h4>
					</div>
					<div class="modal-body">
						<form class="sheet-form">
							<div class="row" style="overflow-x:auto;" id="details">
								<div class="col-lg-6" style="padding-left: 25px;">
									<table style="width: 100% ; border-collapse: separate; border-spacing: 0.4em;">
										<colgroup>
											<col span="1" style="width: 30%;">
											<col span="1" style="width: 70%;">
										</colgroup>
										<thead>
										<tr>
											<th style="text-align: center"><strong>Patient</strong></th>
											<th></th>
										</tr>
										</thead>
										<tbody>
										<tr>
											<td><?= $this->lang->line('insured'); ?></td>
											<td><strong class="insured"></strong></td>
										</tr>
										<tr>
											<td><?= $this->lang->line('patient_lastname'); ?></td>
											<td><strong class="patient-lastname"></strong></td>
										</tr>
										<tr>
											<td><?= $this->lang->line('patient_situation')?></td>
											<td><strong class="patient-situation"></strong></td>
										</tr>
										</tbody>
									</table>
								</div>
								<div class="col-lg-6" style="padding-left: 25px;">
									<table style="width: 100% ;border-collapse: separate; border-spacing: 0.4em;">
										<colgroup>
											<col span="1" style="width: 30%;">
											<col span="1" style="width: 70%;">
										</colgroup>
										<thead>
										<tr>
											<th><?=$this->lang->line('practitioner') ?></th>
											<th></th>
										</tr>
										</thead>
										<tbody>
										<tr>
											<td><?= $this->lang->line('institution'); ?></td>
											<td><strong class="institution"></strong></td>
										</tr>
										<tr>
											<td><?= $this->lang->line('practitioner_lastname'); ?></td>
											<td><strong class="practitioner-lastname"></strong></td>
										</tr>
										<tr>
											<td>Classification</td>
											<td><strong class="classification"></strong></td>
										</tr>
										<tr>
											<td><?= $this->lang->line('care_condition')?></td>
											<td><strong class="care-condition"></strong></td>
										</tr>
										<div class="accident-div">
											<tr>
												<td><?= $this->lang->line('accident_date'); ?></td>
												<td><strong class="accident_date"></strong></td>
											</tr>
										</div>

										<div class="pregnancy-div">
											<tr>
												<td><?= $this->lang->line('pregnancy_start_at'); ?></td>
												<td><strong class="pregnancy_start_at"></strong></td>
											</tr>
											<tr>
												<td><?= $this->lang->line('pregnancy_end_at'); ?></td>
												<td><strong class="pregnancy_end_at"></strong></td>
											</tr>
										</div>
										</tbody>
									</table>
								</div>
							</div>
							<div id="execution-exams-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>
								</div>
								<table id="execution-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>
										<?php if($invoice->state == 'UNDER_VALIDATION') { ?>
											<th>Actions</th>
										<?php } ?>
									</tr>
									</thead>
									<tbody></tbody>
								</table>
							</div>
							<div id="execution-prescriptions-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>
								</div>
								<table id="execution-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>
										<?php if($invoice->state == 'UNDER_VALIDATION') { ?>
											<th>Actions</th>
										<?php } ?>
									</tr>
									</thead>
									<tbody></tbody>
								</table>
							</div>
						</form>
					</div>
					<div class="modal-footer">
						<?php if($invoice->state == 'UNDER_VALIDATION') { ?>
							<button class="btn btn-danger pull-left" onclick="onSheetSave()">
								<?= $this->lang->line('save'); ?>
							</button>
						<?php } ?>
						<button type="button" class="btn btn-default pull-right"
								data-dismiss="modal"><?= $this->lang->line('Fermer'); ?></button>
					</div>
				</div>
			</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/jquery-ui/jquery-ui.js') ?>"></script>

<script src="<?= base_url('bower_components/moment/min/moment.min.js') ?>"></script>
<script src="https://cdn.datatables.net/select/1.3.1/js/dataTables.select.min.js"></script>
<script src="<?= base_url('bower_components/toastr/toastr.js') ?>"></script>
<script src="<?= base_url('dist/js/sweetalert2.js') ?>"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment-with-locales.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/plug-ins/1.10.19/sorting/datetime-moment.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/plug-ins/1.10.20/dataRender/datetime.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.6.2/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.print.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.colVis.min.js"></script>

<script type="text/javascript">
	toastr.options.closeButton = true;
	toastr.options.closeMethod = 'fadeOut';
	toastr.options.closeDuration = 5000;
	toastr.options.closeEasing = 'swing';
	var sheets = [];

	const format = "<?=$this->session->userdata('site_lang')?>" === 'french' ? 'fr' : 'en';
	moment.updateLocale(moment.locale(format), {invalidDate: ""}); // Blank text when is invalid date
	var table = $('#example1').DataTable(
			{
				order: [[1, 'asc']],
				dom: 'Bfrtip',
				"buttons": [
					'pageLength',
					{
						"extend": 'excelHtml5',
						title: "<?= $this->lang->line('health_care_sheets') . ' :: ' . $this->lang->line('invoice_detail') . ' - ' . $invoice->invoice_id?>",
						// exportOptions: {
						// 	columns: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
						// },
						customizeData: function (data) {
							for (var i = 0; i < data.body.length; i++) {
								for (var j = 0; j < data.body[i].length; j++) {
									// data.body[i][j] = '\u200C' + data.body[i][j];
									if ([5,6,7].includes(j)) {
										// Get the value and strip the non numeric characters
										// var value = $(this).text();
										value = data.body[i][j].replace(',', ".")
										data.body[i][j] = Number(value.replace(/[^0-9\.-]+/g, ""));
									}
								}
							}
						},
					},
					{
						extend: 'csvHtml5',
						title: "<?= $this->lang->line('health_care_sheets') . ' :: ' . $this->lang->line('invoice_detail') . ' - ' . $invoice->invoice_id?>",
					},
					{
						extend: 'pdfHtml5',
						orientation: 'landscape',
						pageSize: 'LEGAL',
						title: "<?= $this->lang->line('health_care_sheets') . ' :: ' . $this->lang->line('invoice_detail') . ' - ' . $invoice->invoice_id?>",
					},
					// 'colvis'
				]
			}
	);

	$('#accept-invoice').click(function() {
		$.ajax({
			url: '<?= base_url('NanoHealthController/validateInvoice/'.$invoice->id)?>',
			type: 'POST',
			dataType: 'json',
			data: {
				"action": "ACCEPT",
				"validating_agent_id": "<?= $this->session->userdata('agent_id') ?>"
			},
			success: function (data) {
				if(data.status === 200){
					Swal.fire({
						icon: 'success',
						title: data.response,
						text:"<?= $this->lang->line('informations_updated')?>",
						timer: 3000
					}).then(()=>{
						location.reload();
					});
					// alert("Les informations ont été mises à jour.") ? "" :
				}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')?>");
			}
		});
	});

	$('#reject-invoice').click(function () {
		if ($('#reject-form')[0].checkValidity()) {
			let reason = $("textarea[name=reason]").val();
			if(reason.length > 500 ){
				toastr.warning( "<?= $this->lang->line('reason_rule')?>", "<?= $this->lang->line('management_rule')?>");
			}else{
				$.ajax({
					url: '<?= base_url('NanoHealthController/validateInvoice/'.$invoice->id)?>',
					type: 'POST',
					dataType: 'json',
					data: {
						"action": "REJECT",
						"validating_agent_id": "<?= $this->session->userdata('agent_id') ?>",
						"reason": reason
					},
					success: function (data) {
						if (data.status === 200) {
							Swal.fire({
								icon: 'success',
								title: data.response,
								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')?>");
					}
				});
			}
		} else {
			$('#reject-form')[0].reportValidity();
		}
	});

	$('#update-invoice').click(function () {
		if ($('#update-form')[0].checkValidity()) {
			let reason = $("textarea[name=update-reason]").val();
			if(reason.length > 500 ){
				toastr.warning( "<?= $this->lang->line('reason_rule')?>", "<?= $this->lang->line('management_rule')?>");
			}else{
				$.ajax({
					url: '<?= base_url('NanoHealthController/validateInvoice/'.$invoice->id)?>',
					type: 'POST',
					dataType: 'json',
					data: {
						"action": "ACCEPT_AND_UPDATE",
						"validating_agent_id": "<?= $this->session->userdata('agent_id') ?>",
						"reason": reason,
						"sheets" : sheets
					},
					success: function (data) {
						if (data.status === 200) {
							Swal.fire({
								icon: 'success',
								title: data.response,
								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')?>");
					}
				});
			}
		} else {
			$('#update-form')[0].reportValidity();
		}
	});

	var care_condition = null;
	var showActionsButtons = "<?= $invoice->state == 'UNDER_VALIDATION' ?>"
	var currentSheetId = null
	var sheetUpdated = false
	$('#accept-and-update-invoice').hide()
	function openSheetDetails(id) {
		sheetUpdated = false
		$('#accident-div').hide();
		$('#pregnancy-div').hide();

		$.ajax({
			url: '<?= base_url('NanoHealthController/getSingleHealthCareSheet/')?>'+id,
			type: 'GET',
			dataType: 'json',
			success: function (data) {
				if(data.status === 200){
					// consultations = data.response;


					const sheet = data.response;
					currentSheetId = sheet.id
					care_condition = sheet._care_condition

					$(".insured").html(sheet.insured_id +' | '+sheet.insured_phone)
					$(".patient-lastname").html((sheet.patient_lastname || '') + ' ' + (sheet.patient_firstname || ''))
					$(".patient-situation").html(sheet.patient_situation)

					$(".institution").html((sheet.institution_name || '') + ' | ' + (sheet.institution_code || ''))
					$(".practitioner-lastname").html((sheet.practitioner_lastname || '') + ' ' + (sheet.practitioner_firstname || ''))
					$(".classification").html(sheet.practitioner_provider_class)
					$(".care-condition").html(sheet.care_condition)
					if(sheet.accident_date){
						$(".accident_date").val(sheet.accident_date);
						$('#accident-div').show();
					}else{
						$('#sheet-form').find('input[name="accident_date"]').val(null);
						$('#accident-div').hide();
					}

					if(sheet.pregnancy_start_at ||  sheet.pregnancy_end_at){
						$(".pregnancy_start_at").html(sheet.pregnancy_start_at);
						$(".pregnancy_end_at").html(sheet.pregnancy_end_at);
						$(".pregnancy-div").show();
					}else {
						$(".pregnancy_start_at").html(null);
						$(".pregnancy_end_at").html(null);
						$(".pregnancy-div").hide();
					}

					if(sheet.type === 'CONSULTATION'){

						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>';

						$("#consultation-prestations tbody").children().remove();
						$.each(sheet.performances, function (j, it) {
							$('#consultation-prestations').append('<tr>' +
								'<td id="'+it.id+'" act_id="'+it.act.id+'">'+(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>' +
								(showActionsButtons ? '<td>'+actions1+'</td>' : '' ) +
								'</tr>')
						});


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


						$("#consultation-prescriptions tbody").children().remove();
						$.each(sheet.prescriptions, function (j, it) {
							$('#consultation-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>' +
								'</tr>')
						});

						$('#consultation-sheet-modal').modal('show');

					}else{

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

						$("#execution-exams tbody").children().remove();
						$.each(sheet.exams, function (j, it) {
							$('#execution-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>' +
								(showActionsButtons ? '<td>'+actions2+'</td>' : '' ) +
								'</tr>')
						});


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

						$("#execution-prescriptions tbody").children().remove();
						$.each(sheet.prescriptions, function (j, it) {
							$('#execution-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>' +
								(showActionsButtons ? '<td>'+actions3+'</td>' : '' ) +
								'</tr>')
						});

						$('#execution-sheet-modal').modal('show');
					}


				}else{
					toastr.error(data.error , "<?= $this->lang->line('request_error')?>");
				}
			},
			error: function () {
				toastr.error("<?= $this->lang->line('error_message')?>", "<?= $this->lang->line('request_error')?>");
			}
		});
	}

</script>
<?php if($invoice->state == 'UNDER_VALIDATION') { ?>
	<script>
		var prestations = [];
		var exams = [];
		var prescriptions = [];

		function onSheetSave() {
			if(sheetUpdated){
				sheets = sheets.filter(function(item) {
					return item.sheet_id !== currentSheetId
				});

				sheets.push({
					'sheet_id' : currentSheetId,
					'prestations' : prestations,
					'exams' : exams,
					'prescriptions' : prescriptions
				})

				$('#accept-and-update-invoice').show()
				$('#accept-invoice').hide()

				console.log('sheet' , sheets)

				prestations = [];
				exams = [];
				prescriptions = [];
			}

			$('#consultation-sheet-modal').modal('hide');
			$('#execution-sheet-modal').modal('hide');
		}
	</script>
<!--	Consultation-->
	<script type="text/javascript">
		// Paliers scripts
		$(document).ready(function () {


			function calculatePrestationsAmount(){
				$('#amount').on('input',fetchPrestationsAmount)
				$('#fees').on('input',fetchPrestationsAmount)
			}

			function fetchPrestationsAmount(){
				var amount = parseFloat($("#amount").val());
				var fees = parseFloat($("#fees").val());
				fees = isNaN(fees) ? 0 : fees;
				if(isNaN(amount + fees)){
					$('#moderator-ticket').val('');
					$('#insurance-amount').val('');
				}else{
					$.ajax({
						url: '<?= base_url('NanoHealthController/calculateHealthCareSheetPerformancesAmount')?>',
						type: 'POST',
						dataType: 'json',
						data: {
							"network_id" : "<?= $network_id ?>", "amount": (amount + fees), "care_condition": care_condition
						},
						success: function (data) {
							if(data.status === 200){
								$('#moderator-ticket').val(data.response.moderator_ticket);
								$('#insurance-amount').val(data.response.insurance_amount);
							}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')?>");
						}
					});
				}
			}

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

			var actions1 = $("#consultation-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 = $("#consultation-prestations tbody tr:last-child").index();
				var row = '<tr>' +
					'<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>';
				$("#consultation-prestations").append(row);
				$("#consultation-prestations tbody tr").eq(index + 1).find(".add, .edit").toggle();
				$('[data-toggle="tooltip"]').tooltip();

				calculatePrestationsAmount();

			});
			// 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 () {
					$(this).parent("td").html($(this).find('option:selected').text()).attr("value",$(this).val());
				});

				// Add updated prestation
				var arrayItem = {};
				$(this).parents("tr").find("td:not(:last-child)").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;
				});
				sheetUpdated = true
				prestations.push(arrayItem)
			});
			// Edit row on edit button click
			$(document).on("click", ".edit1", function () {
				$(this).parents("tr").find("td:not(:last-child)").each(function (index) {
					if (index === 1)
						$(this).html('<input type="number" required class="form-control" name="amount" min="0" id="amount" 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;
							sheetUpdated = true
							prestations.push(deletedItem);
						}
					}
				});
			});

			// Table Examens

			var actions2 = $("#consultation-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 = $("#consultation-exams tbody tr:last-child").index();
				var row = '<tr>' +
					'<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>';
				$("#consultation-exams").append(row);
				$("#consultation-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());
				});

				// Add updated exams
				var arrayItem = {};
				$(this).parents("tr").find("td:not(:last-child)").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());
				});
				sheetUpdated = true
				exams.push(arrayItem)
			});
			// Edit row on edit button click
			$(document).on("click", ".edit2", function () {
				$(this).parents("tr").find("td:not(:last-child)").each(function (index) {
					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;
							sheetUpdated = true
							exams.push(deletedItem);
						}
					}
				});
			});


			// Table prescription
	// Table prescriptions
			var actions3 = $("#consultation-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 = $("#consultation-prescriptions tbody tr:last-child").index();
				var row = '<tr>' +
					'<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>';
				$("#consultation-prescriptions").append(row);
				$("#consultation-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());
				});
				// Add updated prescriptions
				var arrayItem = {};
				$(this).parents("tr").find("td:not(:last-child)").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());
				});
				sheetUpdated = true
				prescriptions.push(arrayItem)
			});
	// Edit row on edit button click
			$(document).on("click", ".edit3", function () {
				$(this).parents("tr").find("td:not(:last-child)").each(function (index) {
					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;
							sheetUpdated = true
							prescriptions.push(deletedItem);
						}
					}
				});
			});
		});
	</script>
<!--	Execution-->
	<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-execution", 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());
				});

				// Add updated exams
				var arrayItem = {};
				$(this).parents("tr").find("td:not(:last-child)").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());
				});
				sheetUpdated = true
				exams.push(arrayItem)
			});
			// Edit row on edit button click
			$(document).on("click", ".edit2-execution", 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

// Add row on add button click
			$(document).on("click", ".add3-execution", 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());
				});

				// Add updated prescriptions
				var arrayItem = {};
				$(this).parents("tr").find("td:not(:last-child)").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());
				});
				sheetUpdated = true
				prescriptions.push(arrayItem)
			});
// Edit row on edit button click
			$(document).on("click", ".edit3-execution", 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>
<?php } ?>

