<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\Money;
$context = new \Brick\Money\Context\AutoContext();

$month = time();
$months[] = convertDate(date("M"));
$label_months [] = date("M") . " " . date("Y");
$years[] = date("Y");
for ($i = 1; $i <= 11; $i++) {
	$month = strtotime('last month', $month);
	$months [] = convertDate(date("M", $month));
	$years[] = date("Y", $month);
	$label_months [] = date("M", $month) . " " . date("Y", $month);
}

/**
 ** Liste des souscriptions
 **/
$date = date("Y");
$insuranceSubcriptions =array();
for ($i = 1; $i <= 12; $i++) {
	$monthQuery = $this->db->query("SELECT id FROM nh_insurances_subscriptions
                      WHERE MONTH(created_at) = '".$months[$i-1]."' AND YEAR(created_at) = '".$years[$i-1]."'
                         AND network_id ='".$this->session->userdata('network_id')."'");
	array_push($insuranceSubcriptions, $monthQuery->num_rows());
}

$careRequests = [];

//if ($transactions) {
//	$transac = $transactions->num_rows();
//	$array_transac = array();
//	$num = 0;
//	if ($transac > 0) {
//		foreach ($transactions->result() as $row) {
//			$num++;
//			$array_transac[] = $row->type_transac;
//		}
//		$vals_transac = array_count_values($array_transac);
//		$pieChart = array();
//		foreach (array_keys($vals_transac) as $paramName) {
//			$color = dechex(rand(0x000000, 0xFFFFFF));
//			$trash = array("value" => $vals_transac[$paramName],
//				"color" => "#" . $color,
//				"highlight" => "#" . $color,
//				"label" => $paramName);
//
//			$pieChart[] = $trash;
//		}
//	}
//} else {
	$pieChart = array();
//}

?>

<div class="content-wrapper">
	<!-- Content Header (Page header) -->
	<section class="content-header">
		<h1>
			<?= $this->lang->line('Gestion des wallets'). ' '. $network .' - '.$country; ?>
		</h1>

	</section>

	<section class="content">
		<div class="row">
			<div class="col-lg-4 col-xs-6">
				<div class="small-box bg-aqua">
					<div class="inner">
						<h3><?= $principal ?></h3>
						<p><?= $this->lang->line('Solde Principal') ?></p>
					</div>
					<div class="icon">
						<i class="ion ion-cash"></i>
					</div>
				</div>
			</div>

			<div class="col-lg-4 col-xs-6">
				<div class="small-box bg-green">
					<div class="inner">
						<h3><?= $commission; ?></h3>
						<p><?= $this->lang->line('Solde Commission') ?></p>
					</div>
					<div class="icon">
						<i class="ion ion-cash"></i>
					</div>
				</div>
			</div>
		</div>
		<div class="row">
			<div class="col-lg-4">
				<button type="button" class="btn btn-primary btn-block margin" data-toggle="modal" data-target="#rechargeAccount"><?= $this->lang->line('recharge_hypervisor_account') ?> </button>
			</div>
			<div class="col-lg-8">
				<button type="button" class="btn btn-primary margin" data-toggle="modal" data-target="#modal-update"
						style="width: 100%"><?= $this->lang->line('Modifier la configuration') ?></button>
			</div>
		</div>
		<div class="row centered">
			<div class="col-lg-4 col-xs-3">
				<div class="small-box bg-red-active">
					<div class="inner">
						<h3><?= $this->lang->line($nh_config->provider_billing_period ?? ''); ?></h3>
						<p><?= $this->lang->line('provider_billing_period') ?></p>
					</div>
					<div class="icon">
						<i class="ion ion-ios-timer"></i>
					</div>
				</div>
			</div>
			<div class="col-lg-4 col-xs-3">
				<div class="small-box bg-orange">
					<div class="inner">
						<h3><?= $this->lang->line($nh_config->family_coverage_sharing ? 'Oui' : 'Non'); ?></h3>
						<p><?= $this->lang->line('family_coverage_sharing') ?></p>
					</div>
					<div class="icon">
						<i class="fa fa-group"></i>
					</div>
				</div>
			</div>
			<div class="col-lg-4 col-xs-6">
				<div class="small-box bg-aqua-active">
					<div class="inner">
						<h3><?= $this->lang->line($nh_config->password_validation) ?></h3>
						<p><?= $this->lang->line('password_validation') ?> </p>
					</div>
					<div class="icon">
						<i class="fa fa-sort-numeric-desc"></i>
					</div>
				</div>
			</div>
		</div>
		<div class="row centered">
			<div class="col-lg-2 col-xs-6">
				<div class="small-box bg-aqua-active">
					<div class="inner">
						<h3><?= $nh_config->max_number_of_beneficiaries ?? ''; ?></h3>
						<p><?= $this->lang->line('max_number_of_beneficiaries') ?> </p>
					</div>
					<div class="icon">
						<i class="fa fa-sort-numeric-desc"></i>
					</div>
				</div>
			</div>
			<div class="col-lg-2 col-xs-6">
				<div class="small-box bg-aqua-active">
					<div class="inner">
						<h3><?= $nh_config->age_limit_of_insured_and_spouse ?? ''; ?></h3>
						<p><?= $this->lang->line('age_limit_of_insured_and_spouse') ?> </p>
					</div>
					<div class="icon">
						<i class="ion ion-android-calendar"></i>
					</div>
				</div>
			</div>
			<div class="col-lg-2 col-xs-6">
				<div class="small-box bg-aqua-active">
					<div class="inner">
						<h3><?= $nh_config->age_limit_of_child_beneficiary ?? ''; ?></h3>
						<p><?= $this->lang->line('age_limit_of_child_beneficiary') ?> </p>
					</div>
					<div class="icon">
						<i class="ion ion-android-calendar"></i>
					</div>
				</div>
			</div>
			<div class="col-lg-3 col-xs-6">
				<div class="small-box bg-orange-active">
					<div class="inner">
						<h3><?= $nh_config->reminder_delay_days ?? ''; ?></h3>
						<p><?= $this->lang->line('reminder_delay_days') ?> </p>
					</div>
					<div class="icon">
						<i class="ion ion-android-calendar"></i>
					</div>
				</div>
			</div>
			<div class="col-lg-3 col-xs-6">
				<div class="small-box bg-orange-active">
					<div class="inner">
						<h3><?= $nh_config->suspension_delay_days_after_reminder ?? ''; ?></h3>
						<p><?= $this->lang->line('suspension_delay_days_after_reminder') ?> </p>
					</div>
					<div class="icon">
						<i class="ion ion-android-calendar"></i>
					</div>
				</div>
			</div>
		</div>
		<div class="row">
			<div class="col-lg-2 col-xs-6">
				<div class="small-box bg-green-active">
					<div class="inner">
						<h3><?= $nh_config->current_affection_percentage_insurer ?? ''; ?><sup style="font-size: 20px">%</sup></h3>
						<p><?= $this->lang->line('current_affection').' : '.$this->lang->line('percentage_insurer') ?></p>
					</div>
					<div class="icon">
						<i class="ion ion-pie-graph"></i>
					</div>
				</div>
			</div>

			<div class="col-lg-2 col-xs-6">
				<div class="small-box bg-green-active">
					<div class="inner">
						<h3><?= $nh_config->current_affection_percentage_insured ?? ''; ?><sup style="font-size: 20px">%</sup></h3>
						<p><?= $this->lang->line('current_affection').' : '.$this->lang->line('percentage_insured') ?></p>
					</div>
					<div class="icon">
						<i class="ion ion-pie-graph"></i>
					</div>
				</div>
			</div>
			<div class="col-lg-2 col-xs-6">
				<div class="small-box bg-light-blue-active">
					<div class="inner">
						<h3><?= $nh_config->long_term_affection_percentage_insurer ?? ''; ?><sup style="font-size: 20px">%</sup></h3>
						<p><?= $this->lang->line('long_term_affection').' : '.$this->lang->line('percentage_insurer') ?></p>
					</div>
					<div class="icon">
						<i class="ion ion-pie-graph"></i>
					</div>
				</div>
			</div>

			<div class="col-lg-2 col-xs-6">
				<div class="small-box bg-light-blue-active">
					<div class="inner">
						<h3><?= $nh_config->long_term_affection_percentage_insured ?? ''; ?><sup style="font-size: 20px">%</sup></h3>
						<p><?= $this->lang->line('long_term_affection').' : '.$this->lang->line('percentage_insured') ?></p>
					</div>
					<div class="icon">
						<i class="ion ion-pie-graph"></i>
					</div>
				</div>
			</div>
			<div class="col-lg-2 col-xs-6">
				<div class="small-box bg-aqua">
					<div class="inner">
						<h3><?= $nh_config->exoneration_percentage_insurer ?? ''; ?><sup style="font-size: 20px">%</sup></h3>
						<p><?= $this->lang->line('exoneration').' : '.$this->lang->line('percentage_insurer') ?></p>
					</div>
					<div class="icon">
						<i class="ion ion-pie-graph"></i>
					</div>
				</div>
			</div>

			<div class="col-lg-2 col-xs-6">
				<div class="small-box bg-aqua">
					<div class="inner">
						<h3><?= $nh_config->exoneration_percentage_insured ?? ''; ?><sup style="font-size: 20px">%</sup></h3>
						<p><?= $this->lang->line('exoneration').' : '.$this->lang->line('percentage_insured') ?></p>
					</div>
					<div class="icon">
						<i class="ion ion-pie-graph"></i>
					</div>
				</div>
			</div>
		</div>
		<div class="row centered">
			<div class="col-lg-4 col-xs-12">
				<div class="box">
					<div class="box-header">
						<h3 class="box-title"><?= $this->lang->line('years_price_grid') ?></h3>
					</div>
					<div class="box-body" style="overflow-x:auto;">
						<table class="table table-bordered" >
							<thead>
							<tr>
								<th width="20"><?= $this->lang->line('min_age')?></th>
								<th width="20"><?= $this->lang->line('max_age') ?> </th>
								<th><?= $this->lang->line('markup_percentage') ; ?></th>
							</tr>
							</thead>
							<tbody>
							<?php
							if(isset($years_prices_grid)){
								foreach($years_prices_grid->result() as $i => $row) { ?>
									<tr>
										<td><?= $row->min_age ?></td>
										<td><?= $row->max_age ?></td>
										<td><?= floatval($row->markup_percentage).'%' ?></td>
									</tr>
									<?php
								}
							}
							?>
							</tbody>
						</table>
						<button type="button" class="btn btn-primary btn-block" style="margin-top: 15px" data-toggle="modal" data-target="#modal-years-grid" >
							<b><?= $this->lang->line('edit_years_prices_grid'); ?></b>
						</button>
					</div>
				</div>
			</div>
			<div class="col-lg-8 col-xs-12">
				<div class="box">
					<div class="box-header">
						<h3 class="box-title"><?= $this->lang->line('months_price_grid') ?></h3>
					</div>
					<div class="box-body" style="overflow-x:auto;">
						<table class="table table-bordered" >
							<thead>
							<tr>
								<th><?= $this->lang->line('number_of_months') ?> </th>
								<th><?= $this->lang->line('min_amount') ?> </th>
								<th><?= $this->lang->line('max_insurance_coverage_amount') ?> </th>
								<th><?= $this->lang->line('waiting_period_days') ?> </th>
								<th><?= $this->lang->line('payment_period') ?> </th>
								<th><?= $this->lang->line('payment_duration_months') ?> </th>
								<th><?= $this->lang->line('number_of_fractions') ?></th>
							</tr>
							</thead>
							<tbody>
							<?php
							if(isset($months_prices_grid)){
								foreach($months_prices_grid->result() as $i => $row) { ?>
									<tr>
										<td><?= $row->number_of_months ?></td>
										<td><?= Money::of(round($row->min_amount, 2), $currency_code, $context)->formatTo('fr_FR'); ?></td>
										<td><?= Money::of(round($row->max_insurance_coverage_amount, 2), $currency_code, $context)->formatTo('fr_FR'); ?></td>
										<td><?= $row->waiting_period_days ?? '' ?> </td>
										<td><?= $this->lang->line($row->payment_period) ?> </td>
										<td><?= $row->payment_duration_months ?> </td>
										<td><?= $row->number_of_fractions ?></td>
									</tr>
									<?php
								}
							}
							?>
							</tbody>
						</table>
						<button type="button" class="btn btn-primary btn-block" style="margin-top: 15px" data-toggle="modal" data-target="#modal-months-grid" >
							<b><?= $this->lang->line('edit_months_prices_grid'); ?></b>
						</button>
					</div>
				</div>
			</div>
		</div>
		<div class="row">
			<div class="col-xs-12">
				<div class="box box-success">
					<div class="box-header with-border">
						<h3 class="box-title">
							<?= $this->lang->line('subscriptions_of_the_last_12_months'); ?></h3>
						<div class="box-tools">
							<a class="btn btn-primary" href="<?= current_url().('?history=insurance-subscriptions')?>">
								<?= $this->lang->line('subscriptions_historic'); ?>
							</a>
						</div>
					</div>
					<div class="box-body">
						<div class="chart" id="chart">
							<canvas id="barChart" style="height:230px"></canvas>
						</div>
					</div>
				</div>
			</div>
		</div>

		<div class="row">
			<div class="col-lg-8">
				<div class="box">
					<div class="box-header">
						<h3 class="box-title"><?= $this->lang->line('list_of_acts') ?></h3>
						<div class="box-tools">
							<button class="btn btn-success" id="addAct">
								<?= $this->lang->line('add_act'); ?>
							</button>
						</div>
					</div>
					<div class="box-body" style="overflow-x:auto;">
						<table id="example1" class="table table-bordered table-hover">
							<thead>
							<tr>
								<?php
									echo "<th>Code</th>
									<th>".$this->lang->line('Nom')."</th>
									<th>Type</th>
									<th>".$this->lang->line('billing_type')."</th>
									<th>".$this->lang->line('unit_value')."</th>
									<th>".$this->lang->line('authorization_type')."</th>
									<th>".$this->lang->line('Montant')."</th>
									<th>Action</th>";
									?>
							</tr>
							</thead>
							<tbody>
							<?php
							if(isset($acts)){
								foreach($acts->result() as $i => $row) {
									$amount = isset($row->amount) ?  Money::of(round($row->amount, 2), $currency_code, $context)->formatTo('fr_FR') : ''
									?>
									<tr>
										<td><?= $row->code ?></td>
										<td><?= $row->name ?></td>
										<td><?= $this->lang->line($row->type);  ?></td>
										<td><?= $this->lang->line($row->billing_type); ?></td>
										<td><?= $row->unit_value ?></td>
										<td><?= $this->lang->line($row->authorization_type); ?></td>
										<td><?= $amount ?></td>
										<td>
											<button class='btn btn-success editAct' data-id="<?=$row->id?>" data-name="<?=$row->name?>" data-type="<?=$row->type?>"  data-billing_type="<?=$row->billing_type?>"
												data-authorization_type="<?=$row->authorization_type?>" data-code="<?=$row->code?>" data-amount="<?=$row->amount?>"  data-unit_value="<?=$row->unit_value?>">
												<i class='fa fa-edit'></i>
											</button>
											<button data-toggle='modal' class='btn btn-danger deleteAct' data-id="<?=$row->id?>" >
												<i class='fa fa-trash'></i>
											</button>
										</td>
									</tr>
									<?php
								}
							}
							?>
							</tbody>
						</table>
					</div>
				</div>
			</div>
			<div class="col-lg-4">
				<div class="box">
					<div class="box-header">
						<h3 class="box-title"><?= $this->lang->line('provider_classes') ?></h3>
						<div class="box-tools">
							<button class="btn btn-success" id="add-class">
								<?= $this->lang->line('add_provider_class'); ?>
							</button>
						</div>
					</div>
					<div class="box-body" style="overflow-x:auto;">
						<table id="provider_classes" class="table table-bordered table-hover">
							<thead>
							<tr>
								<?php
								echo "<th>".$this->lang->line('Nom')."</th>
									<th>Action</th>";
								?>
							</tr>
							</thead>
							<tbody>
							<?php
							if(isset($provider_classes)){
								foreach($provider_classes->result() as $i => $row) { ?>
									<tr>
										<td><?= $row->name ?></td>
										<td>
											<button class='btn btn-success edit-class' data-id="<?=$row->id?>" data-name="<?=$row->name?>">
												<i class='fa fa-edit'></i>
											</button>
											<button data-toggle='modal' class='btn btn-danger delete-class' data-id="<?=$row->id?>" >
												<i class='fa fa-trash'></i>
											</button>
										</td>
									</tr>
									<?php
								}
							}
							?>
							</tbody>
						</table>
					</div>
				</div>
			</div>
		</div>

		<div class="modal fade" id="modal-update">
			<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>
						<h3 class="modal-title"><?= $this->lang->line('Configuration du wallet'); ?></h3>
					</div>
					<div class="modal-body">
						<form id="walletForm">
							<div class="row">
								<div class="col-lg-6">
									<div class="form-group">
										<label for="nom"
											   class="col-form-label"><?= $this->lang->line('provider_billing_period'); ?></label>
										<select class="form-control" name="provider_billing_period" required>
											<?php $array = array_values($provider_billing_periods);
											foreach ($array as $value) { ?>
												<option value="<?=$value?>" <?= $value === ($nh_config->provider_billing_period ?? '') ? 'selected' : '' ?> > <?=$this->lang->line($value)?> </option>
											<?php } ?>
										</select>
									</div>
									<div class="form-group">
										<label class="col-form-label" style="margin-right: 5px"><?= $this->lang->line('family_coverage_sharing'); ?></label>
										<input type="checkbox" name="family_coverage_sharing">
									</div>

									<div class="form-group" style="margin-top: 40px">
										<label class="col-form-label"><?= $this->lang->line('max_number_of_beneficiaries'); ?></label>
										<input type="number" min="0" max="1000" step="1" required class="form-control"
											   name="max_number_of_beneficiaries"  value="<?= $nh_config->max_number_of_beneficiaries ?? 0 ?>">
									</div>
									<div class="form-group">
										<label class="col-form-label"><?= $this->lang->line('age_limit_of_insured_and_spouse'); ?></label>
										<input type="number" min="0" max="99" step="1" required class="form-control"
											   name="age_limit_of_insured_and_spouse"  value="<?= $nh_config->age_limit_of_insured_and_spouse ?? 0 ?>">
									</div>
									<div class="form-group">
										<label class="col-form-label"><?= $this->lang->line('age_limit_of_child_beneficiary'); ?></label>
										<input type="number" min="0" max="99" step="1" required class="form-control"
											   name="age_limit_of_child_beneficiary"  value="<?= $nh_config->age_limit_of_child_beneficiary ?? 0 ?>">
									</div>
									<div class="form-group">
										<label class="col-form-label"><?= $this->lang->line('reminder_delay_days'); ?></label>
										<input type="number" min="1" max="99" step="1" required class="form-control"
											   name="reminder_delay_days"  value="<?= $nh_config->reminder_delay_days ?? 0 ?>">
									</div>
									<div class="form-group">
										<label class="col-form-label"><?= $this->lang->line('suspension_delay_days_after_reminder'); ?></label>
										<input type="number" min="0" max="99" step="1" required class="form-control"
											   name="suspension_delay_days_after_reminder"  value="<?= $nh_config->suspension_delay_days_after_reminder ?? 0 ?>">
									</div>
									<div class="form-group">
										<label class="col-form-label"><?= $this->lang->line('password_validation'); ?></label>
										<select class="form-control" name="password_validation" required>
											<?php $array = array_values($password_validation_types);
											foreach ($array as $value) { ?>
												<option value="<?=$value?>" <?= $value === ($nh_config->password_validation ?? '') ? 'selected' : '' ?> >
													<?=$this->lang->line($value)?>
												</option>
											<?php } ?>
										</select>
									</div>
								</div>

								<div class="col-lg-6">
									<div class="form-group">
										<label class="col-form-label"><?= $this->lang->line('current_affection').' : '.$this->lang->line('percentage_insurer') . ' (%)'; ?></label>
										<input type="number" min="0" step=".01" required class="form-control"
											   name="current_affection_percentage_insurer" value="<?= $nh_config->current_affection_percentage_insurer ?? 0  ?>">
									</div>
									<div class="form-group">
										<label class="col-form-label"><?= $this->lang->line('current_affection').' : '.$this->lang->line('percentage_insured') . ' (%)'; ?></label>
										<input type="number" min="0" step=".01" required class="form-control"
											   name="current_affection_percentage_insured" value="<?= $nh_config->current_affection_percentage_insured ?? 0  ?>">
									</div>

									<div class="form-group">
										<label class="col-form-label"><?= $this->lang->line('long_term_affection').' : '.$this->lang->line('percentage_insurer') . ' (%)'; ?></label>
										<input type="number" min="0" step=".01" required class="form-control"
											   name="long_term_affection_percentage_insurer" value="<?= $nh_config->long_term_affection_percentage_insurer ?? 0  ?>">
									</div>
									<div class="form-group">
										<label class="col-form-label"><?= $this->lang->line('long_term_affection').' : '.$this->lang->line('percentage_insured') . ' (%)'; ?></label>
										<input type="number" min="0" step=".01" required class="form-control"
											   name="long_term_affection_percentage_insured" value="<?= $nh_config->long_term_affection_percentage_insured ?? 0  ?>">
									</div>

									<div class="form-group">
										<label class="col-form-label"><?= $this->lang->line('exoneration').' : '.$this->lang->line('percentage_insurer') . ' (%)'; ?></label>
										<input type="number" min="0" step=".01" required class="form-control"
											   name="exoneration_percentage_insurer" value="<?= $nh_config->exoneration_percentage_insurer ?? 0  ?>">
									</div>
									<div class="form-group">
										<label class="col-form-label"><?= $this->lang->line('exoneration').' : '.$this->lang->line('percentage_insured') . ' (%)'; ?></label>
										<input type="number" min="0" step=".01" required class="form-control"
											   name="exoneration_percentage_insured" value="<?= $nh_config->exoneration_percentage_insured ?? 0  ?>">
									</div>
								</div>

							</div>
						</form>
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-default pull-left"
								data-dismiss="modal"><?= $this->lang->line('Fermer'); ?></button>
						<button type="button" id="updateWallet" class="btn btn-primary"><?= $this->lang->line('save'); ?></button>
					</div>
				</div>
			</div>
		</div>
		<div class="modal fade" id="modal-years-grid">
			<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>
						<h3 class="modal-title"><?= $this->lang->line('edit_years_prices_grid'); ?></h3>
					</div>
					<div class="modal-body">
						<form id="yearsGridForm">
							<div class="form-group" style="overflow-x:auto;">
								<div class="table-title">
									<div class="row">
										<div class="col-sm-8">

										</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_level'); ?>
											</button>
										</div>
									</div>
								</div>
								<table id="years_prices_grid" class="table table-bordered">
									<thead>
									<tr>
										<th><?= $this->lang->line('min_age')?></th>
										<th><?= $this->lang->line('max_age') ?> </th>
										<th><?= $this->lang->line('markup_percentage') ; ?> (%) </th>
										<th>Actions</th>
									</tr>
									</thead>
									<tbody>
									<?php
									if (isset($years_prices_grid)) {
										foreach ($years_prices_grid->result() as $row) { ?>
											<tr>
												<td><?= $row->min_age ?></td>
												<td><?= $row->max_age ?></td>
												<td><?= floatval($row->markup_percentage)?></td>
												<td>
													<a class="add add1" title="Add" data-toggle="tooltip"><i class="material-icons">&#xE03B;</i></a>
													<a class="edit edit1" title="Edit" data-toggle="tooltip"><i class="material-icons">&#xE254;</i></a>
													<a class="delete delete1" title="Delete" data-toggle="tooltip"><i class="material-icons">&#xE872;</i></a>
												</td>
											</tr>
											<?php
										}
									}
									?>
									</tbody>
								</table>
							</div>
						</form>
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-default pull-left"
								data-dismiss="modal"><?= $this->lang->line('Fermer'); ?></button>
						<button type="button" id="updateYearsGrid"
								class="btn btn-primary"><?= $this->lang->line('save'); ?></button>
					</div>
				</div>
			</div>
		</div>
		<div class="modal fade" id="modal-months-grid">
			<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>
						<h3 class="modal-title"><?= $this->lang->line('edit_months_prices_grid'); ?></h3>
					</div>
					<div class="modal-body">
						<form id="monthsGridForm">
							<div class="form-group" style="overflow-x:auto;">
								<div class="table-title">
									<div class="row">
										<div class="col-sm-8">

										</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_level'); ?>
											</button>
										</div>
									</div>
								</div>
								<table id="months_prices_grid" class="table table-bordered">
									<thead>
									<tr>
										<th style="display: none;">ID</th>
										<th><?= $this->lang->line('number_of_months') ?> </th>
										<th><?= $this->lang->line('min_amount') ?> </th>
										<th><?= $this->lang->line('max_insurance_coverage_amount') ?> </th>
										<th><?= $this->lang->line('waiting_period_days') ?> </th>
										<th><?= $this->lang->line('payment_period') ?> </th>
										<th><?= $this->lang->line('payment_duration_months') ?></th>
										<th>Actions</th>
									</tr>
									</thead>
									<tbody>
									<?php
									if (isset($months_prices_grid)) {
										foreach ($months_prices_grid->result() as $row) { ?>
											<tr>
												<td name='id' style="display: none;"><?=$row->id?></td>
												<td name='number_of_months'><?= $row->number_of_months ?></td>
												<td name='min_amount'><?= floatval($row->min_amount) ?></td>
												<td name='max_insurance_coverage_amount'><?= floatval($row->max_insurance_coverage_amount) ?></td>
												<td name='waiting_period_days'><?= $row->waiting_period_days ?? '' ?></td>
												<td name='payment_period' value="<?=$row->payment_period?>"><?= $this->lang->line($row->payment_period) ?></td>
												<td name='payment_duration_months' ><?= $row->payment_duration_months ?></td>
												<td>
													<a class="add add2" title="Add" data-toggle="tooltip"><i class="material-icons">&#xE03B;</i></a>
													<a class="edit edit2" title="Edit" data-toggle="tooltip"><i class="material-icons">&#xE254;</i></a>
													<a class="delete delete2" title="Delete" data-toggle="tooltip"><i class="material-icons">&#xE872;</i></a>
												</td>
											</tr>
											<?php
										}
									}
									?>
									</tbody>
								</table>
							</div>
						</form>
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-default pull-left"
								data-dismiss="modal"><?= $this->lang->line('Fermer'); ?></button>
						<button type="button" id="updateMonthsGrid"
								class="btn btn-primary"><?= $this->lang->line('save'); ?></button>
					</div>
				</div>
			</div>
		</div>
		<div class="modal fade" id="modal-act">
			<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>
						<h3 class="modal-title"><?= $this->lang->line('add_act'); ?></h3>
					</div>
					<form id="actForm">
						<div class="modal-body">
								<div class="form-group">
									<label class="col-form-label">Code</label>
									<input type="text" required class="form-control input-lg" name="code">
								</div>
								<div class="form-group">
									<label class="col-form-label"><?= $this->lang->line('Nom'); ?></label>
									<input type="text" required class="form-control input-lg" name="name">
								</div>
								<div class="form-group">
									<label  class="col-form-label">Type</label>
									<select class="form-control input-lg" name="type" required>
										<?php $array = array_values($acts_types);
										foreach ($array as $value) { ?>
											<option value="<?=$value?>" > <?=$this->lang->line($value)?> </option>
										<?php } ?>
									</select>
								</div>
								<div class="form-group">
									<label  class="col-form-label"><?= $this->lang->line('billing_type'); ?></label>
									<select class="form-control input-lg" name="billing_type" required>
										<?php $array = array_values($billing_types);
										foreach ($array as $value) { ?>
											<option value="<?=$value?>" > <?=$this->lang->line($value)?> </option>
										<?php } ?>
									</select>
								</div>
								<div id="div-amounts">
									<div class="form-group" id="div-unit-value">
										<label class="col-form-label"><?= $this->lang->line('unit_value'); ?></label>
										<input type="text" class="form-control input-lg" name="unit_value">
									</div>
									<div class="form-group">
										<label class="col-form-label"><?= $this->lang->line('Montant'); ?></label>
										<input type="number" min="0" step="1" class="form-control input-lg" name="amount">
									</div>
								</div>
								<div class="form-group">
									<label class="col-form-label"><?= $this->lang->line('authorization_type'); ?></label>
									<select class="form-control input-lg" name="authorization_type" required>
										<?php $array = array_values($authorization_types);
										foreach ($array as $value) { ?>
											<option value="<?=$value?>" > <?=$this->lang->line($value)?> </option>
										<?php } ?>
									</select>
								</div>

						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-default pull-left"
									data-dismiss="modal"><?= $this->lang->line('Fermer'); ?></button>
							<button type="submit" id="updateWallet" class="btn btn-primary"><?= $this->lang->line('save'); ?></button>
						</div>
					</form>
				</div>
			</div>
		</div>
		<div class="modal fade" id="modal-class">
			<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>
						<h3 class="modal-title"><?= $this->lang->line('add_provider_class'); ?></h3>
					</div>
					<form id="class-form">
						<div class="modal-body">
							<div class="form-group">
								<label class="col-form-label"><?= $this->lang->line('Nom'); ?></label>
								<input type="text" required class="form-control input-lg" name="name">
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-default pull-left"
									data-dismiss="modal"><?= $this->lang->line('Fermer'); ?></button>
							<button type="submit" id="updateWallet" class="btn btn-primary"><?= $this->lang->line('save'); ?></button>
						</div>
					</form>
				</div>
			</div>
		</div>

		<?php $this->load->view('include/delete_modal',['title' => $this->lang->line('delete_of_act')]) ?>
		<?php $this->load->view('include/delete_modal',['title' => $this->lang->line('delete_provider_class'), 'id' => 'class']) ?>
		<?php $this->load->view('include/loader') ?>
	</section>

	<?php $this->load->view('include/recharge_account_modal',['walletPassword' => $walletPassword, 'network' => $network, 'country' => $country, 'wallet_id' => $wallet_id]) ?>

</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>
<scriptf
	src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></scriptf>
<!-- 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>
	$(function () {
		$('#example1').DataTable();
		$('#provider_classes').DataTable();

	})
</script>
<script>

	var areaChartData = {
		labels  : <?= json_encode($label_months) ?>,
		datasets: [
			{
				label               : "<?= $this->lang->line('subscriptions') ?>",
				fillColor           : 'rgba(255, 162, 0, 1)',
				strokeColor         : 'rgba(255, 162, 0, 1)',
				pointColor          : 'rgba(255, 162, 0, 1)',
				pointStrokeColor    : '#ffa200',
				pointHighlightFill  : '#fff',
				pointHighlightStroke: 'rgba(220,220,220,1)',
				data: <?= json_encode($insuranceSubcriptions) ?>
			},
			{
				label               :  "<?= $this->lang->line('care_requests') ?>",
				fillColor           : 'rgba(0, 187, 255, 1)',
				strokeColor         : 'rgba(0, 187, 255, 1)',
				pointColor          : '#00bbff',
				pointStrokeColor    : 'rgba(0, 187, 255, 1)',
				pointHighlightFill  : '#fff',
				pointHighlightStroke: 'rgba(0, 187, 255, 1)',
				data                : <?= json_encode($careRequests) ?>
			}
		]
	};
</script>

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

	let config_id = "<?=$config_id?>";
	var selectedActId = null;
	var selectedClassId = null;

	// Init checkbox
	$('input[name=family_coverage_sharing]').prop("checked", <?= $nh_config->family_coverage_sharing ?>);

	$('#updateWallet').click(function () {
		var network_id = $(this).data('network-id');

		if ($('#walletForm')[0].checkValidity()) {
			const family_coverage_sharing = $('input[name=family_coverage_sharing]').prop('checked') ? 1 : 0;

			const age_limit_of_insured_and_spouse = parseFloat($('input[name=age_limit_of_insured_and_spouse]').val());
			const age_limit_of_child_beneficiary = parseFloat($('input[name=age_limit_of_child_beneficiary]').val());

			const current_affection_percentage_insurer = parseFloat($('input[name=current_affection_percentage_insurer]').val());
			const current_affection_percentage_insured = parseFloat($('input[name=current_affection_percentage_insured]').val());

			const long_term_affection_percentage_insurer = parseFloat($('input[name=long_term_affection_percentage_insurer]').val());
			const long_term_affection_percentage_insured = parseFloat($('input[name=long_term_affection_percentage_insured]').val());

			const exoneration_percentage_insurer = parseFloat($('input[name=exoneration_percentage_insurer]').val());
			const exoneration_percentage_insured = parseFloat($('input[name=exoneration_percentage_insured]').val());

			if(age_limit_of_insured_and_spouse < age_limit_of_child_beneficiary){
				toastr.error("<?= $this->lang->line('age_limit_rule')?>", "<?= $this->lang->line('management_rule')?>");
			}else if((current_affection_percentage_insurer +  current_affection_percentage_insured) !== 100){
				toastr.error("<?= $this->lang->line('current_affection_rule')?>", "<?= $this->lang->line('management_rule')?>");
			}else if( (long_term_affection_percentage_insurer + long_term_affection_percentage_insured) !== 100){
				toastr.error("<?= $this->lang->line('long_term_affection_rule')?>", "<?= $this->lang->line('management_rule')?>");
			}else if( (exoneration_percentage_insurer + exoneration_percentage_insured) !== 100){
				toastr.error("<?= $this->lang->line('exoneration_rule')?>", "<?= $this->lang->line('management_rule')?>");
			}else{
				$.ajax({
					url: '<?= base_url('Gestion/config_wallet/update')?>',
					type: 'POST',
					dataType: 'json',
					data: {
						"id_config": config_id,
						"provider_billing_period": $("select[name=provider_billing_period]").val(),
						"max_number_of_beneficiaries": $("input[name=max_number_of_beneficiaries]").val(),
						"age_limit_of_insured_and_spouse": $("input[name=age_limit_of_insured_and_spouse]").val(),
						"age_limit_of_child_beneficiary": $("input[name=age_limit_of_child_beneficiary]").val(),
						"family_coverage_sharing" : family_coverage_sharing,
						"reminder_delay_days" : $("input[name=reminder_delay_days]").val(),
						"suspension_delay_days_after_reminder" : $("input[name=suspension_delay_days_after_reminder]").val(),
						"password_validation" : $("select[name=password_validation]").val(),
						"current_affection_percentage_insurer": current_affection_percentage_insurer,
						"current_affection_percentage_insured": current_affection_percentage_insured,
						"long_term_affection_percentage_insurer": long_term_affection_percentage_insurer,
						"long_term_affection_percentage_insured": long_term_affection_percentage_insured,
						"exoneration_percentage_insurer": exoneration_percentage_insurer,
						"exoneration_percentage_insured": exoneration_percentage_insured,
						"type" : "ilink_sante"
					},
					success: function (data) {
						if(data==='200'){
							Swal.fire({
								icon: 'success',
								title: "<?= $this->lang->line('wallet_update')?>",
								text:"<?= $this->lang->line('informations_updated')?>",
								timer: 3000
							}).then(()=>{
								location.reload();
							});
							// alert("Les informations ont été mises à jour.") ? "" :
						}else{
							toastr.error("<?= $this->lang->line('error_message')?>" , "<?= $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 {
			$('#walletForm')[0].reportValidity();
		}
	});

	$('#updateYearsGrid').click(function () {
		if ($('#yearsGridForm')[0].checkValidity()) {

			// Paliers de tarifs
			var grid = [];

			$('#years_prices_grid tr').has('td').each(function (i, el) {
				var arrayItem = {};
				var row = [];
				$('td', $(this)).each(function (index, item) {
					row.push(parseFloat($(item).html()));
				});
				arrayItem.nh_network_config_id = config_id
				arrayItem.min_age = row[0]
				arrayItem.max_age =  row[1];
				arrayItem.markup_percentage =  row[2];
				grid.push(arrayItem);
			});

			$.ajax({
				url: '<?= base_url('NanoHealthController/updateConfigYearsPricesGrid')?>',
				type: 'POST',
				dataType: 'json',
				data: {
					"config_id": config_id,
					"grid": grid,
				},
				success: function (data) {
					if (data === '200') {
						Swal.fire({
							icon: 'success',
							title: "<?= $this->lang->line('wallet_update')?>",
							text: "<?= $this->lang->line('informations_updated')?>",
							timer: 3000
						}).then(() => {
							location.reload();
						});
					} else {
						toastr.error("<?= $this->lang->line('error_message')?>", "<?= $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 {
			$('#yearsGridForm')[0].reportValidity();
		}
	});

	$('#updateMonthsGrid').click(function () {
		if ($('#monthsGridForm')[0].checkValidity()) {

			// Paliers de tarifs
			var grid = [];
			//

			$('#months_prices_grid tr').has('td').each(function (i, el) {
				var arrayItem = {};
				var row = [];
				arrayItem.nh_network_config_id = config_id
				$('td', $(this)).each(function (index, item) {
					if($(item).attr('name')){
						if($(item).attr("name") === 'payment_period'){
							arrayItem[$(item).attr("name")] = $(item).attr("value")
						}else{
							arrayItem[$(item).attr("name")] = parseFloat($(item).html()) || null
						}
					}
				});
				grid.push(arrayItem);
			});

			$.ajax({
				url: '<?= base_url('NanoHealthController/updateConfigMonthsPricesGrid')?>',
				type: 'POST',
				dataType: 'json',
				data: {
					"config_id": config_id,
					"grid": grid,
				},
				success: function (data) {
					if (data === '200') {
						Swal.fire({
							icon: 'success',
							title: "<?= $this->lang->line('wallet_update')?>",
							text: "<?= $this->lang->line('informations_updated')?>",
							timer: 3000
						}).then(() => {
							location.reload();
						});
					} else {
						toastr.error("<?= $this->lang->line('error_message')?>", "<?= $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 {
			$('#monthsGridForm')[0].reportValidity();
		}
	});

	$("#actForm").submit(function( event ) {
		let billing_type = $("select[name='billing_type'] :selected",this).val()
		let type = $("select[name='type'] :selected",this).val()
		let amount = parseFloat($("input[name='amount']",this).val())
		let unit_value = $("input[name='unit_value']",this).val()
		if(type === "CONSULTATION" && billing_type === "UNIT_PRICE") {
			toastr.error("<?= $this->lang->line('consultation_cannot_have_unit_price')?>", "<?= $this->lang->line('management_rule')?>");
		}else if( ['UNIT_PRICE','PACKAGE'].includes(billing_type) && isNaN(amount)) {
			toastr.error("<?= $this->lang->line('amount_required')?>", "<?= $this->lang->line('management_rule')?>");
		}else if(billing_type === "UNIT_PRICE" && unit_value.length === 0) {
			toastr.error("<?= $this->lang->line('unit_value_required')?>", "<?= $this->lang->line('management_rule')?>");
		}else{
			$.ajax({
				url: '<?= base_url('NanoHealthController/storeAct')?>',
				type: 'POST',
				dataType: 'json',
				data: {
					"config_id": config_id,
					"id" : selectedActId,
					"code": $("input[name='code']",this).val(),
					"name": $("input[name='name']",this).val(),
					"type": type,
					"billing_type": billing_type,
					"authorization_type": $("select[name='authorization_type'] :selected",this).val(),
					"unit_value": $("input[name='unit_value']",this).val(),
					"amount" : billing_type === 'FREE' ? null : amount
				},
				success: function (data) {
					if (data.code === 200) {
						Swal.fire({
							icon: 'success',
							title: "<?= $this->lang->line('wallet_update')?>",
							text: "<?= $this->lang->line('informations_updated')?>",
							timer: 3000
						}).then(() => {
							location.reload();
						});
					} else {
						toastr.error(data.message , "<?= $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')?>");
				}
			});
		}
		event.preventDefault();
	});

	function hideOrShowUnitValueDiv(billing_type){
		if(billing_type === 'FREE'){
			$("#actForm div[id='div-amounts']").hide()
		}else{
			$("#actForm div[id='div-amounts']").show()
			if(billing_type === 'PACKAGE'){
				$("#actForm div[id='div-unit-value']").hide()
			}else{
				$("#actForm div[id='div-unit-value']").show()
			}
		}
	}

	$("#actForm select[name='billing_type']").change(function () {
		hideOrShowUnitValueDiv($(this).val())
	});

	$('.editAct').click(function (){
		selectedActId = $(this).data('id');
		$("#modal-act h3").html("<?=$this->lang->line('edit_act')?>");
		$("#actForm input[name='code']").val($(this).data('code'));
		$("#actForm input[name='name']").val($(this).data('name'));
		$("#actForm select[name='type']").val($(this).data('type'));
		$("#actForm select[name='billing_type']").val($(this).data('billing_type'));
		$("#actForm input[name='amount']").val($(this).data('amount'));
		$("#actForm input[name='unit_value']").val($(this).data('unit_value'));
		$("#actForm select[name='authorization_type']").val($(this).data('authorization_type'));
		hideOrShowUnitValueDiv($(this).data('billing_type'))
		$('#modal-act').modal('show');
	});

	$('#addAct').click(function (){
		selectedActId = null;
		$("#modal-act h3").html("<?=$this->lang->line('add_act')?>");
		$("#actForm input[name='code']").val(null);
		$("#actForm input[name='name']").val(null);
		$("#actForm select[name='type']").prop('selectedIndex',0);
		$("#actForm select[name='billing_type']").prop('selectedIndex',0);
		$("#actForm input[name='amount']").val(null);
		$("#actForm input[name='unit_value']").val(null);
		$("#actForm select[name='authorization_type']").prop('selectedIndex',0);

		$("#actForm div[id='div-unit-value']").hide();
		$('#modal-act').modal('show');
	});

	$('.deleteAct').click(function () {
		selectedActId = $(this).data('id');
		$('#delete-modal').modal('show');
	});

	$("#delete-btn").click(function () {
		$.ajax({
			url: '<?= base_url('NanoHealthController/deleteAct')?>',
			type: 'post',
			data: {id: selectedActId},
			dataType: 'json',
			success: function (data) {
				if(data.code === 200){
					Swal.fire({
						icon: 'success',
						title: "<?= $this->lang->line('act_deleted')?>",
						text:"<?= $this->lang->line('informations_updated')?>",
						timer: 3000
					}).then(()=>{
						location.reload();
					});
				}else{
					toastr.error(data.message , "<?= $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')?>");
			}
		});
		event.preventDefault();
	});

	// Classes de prestataires

	$('#add-class').click(function (){
		selectedClassId = null;
		$("#modal-class h3").html("<?=$this->lang->line('add_provider_class')?>");
		$("#class-form input[name='name']").val(null);
		$('#modal-class').modal('show');
	});

	$('.edit-class').click(function (){
		selectedClassId = $(this).data('id');
		$("#modal-act h3").html("<?=$this->lang->line('edit_provider_class')?>");
		$("#class-form input[name='name']").val($(this).data('name'));
		$('#modal-class').modal('show');
	});

	$('.delete-class').click(function () {
		selectedClassId = $(this).data('id');
		$('#class-delete-modal').modal('show');
	});

	$("#class-form").submit(function( event ) {
		$.ajax({
			url: '<?= base_url('NanoHealthController/storeProviderClass')?>',
			type: 'POST',
			dataType: 'json',
			data: {
				"config_id": config_id,
				"id" : selectedClassId,
				"name": $("input[name='name']",this).val(),
			},
			success: function (data) {
				if (data.code == 200) {
					Swal.fire({
						icon: 'success',
						title: "<?= $this->lang->line('wallet_update')?>",
						text: "<?= $this->lang->line('informations_updated')?>",
						timer: 3000
					}).then(() => {
						location.reload();
					});
				} else {
					toastr.error("<?= $this->lang->line('error_message')?>", "<?= $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')?>");
			}
		});
		event.preventDefault();
	});
	$("#class-delete-btn").click(function () {
		$.ajax({
			url: '<?= base_url('NanoHealthController/deleteProviderClass')?>',
			type: 'post',
			data: {id: selectedClassId},
			dataType: 'json',
			success: function (data) {
				if(data.code === 200){
					Swal.fire({
						icon: 'success',
						title: "<?= $this->lang->line('provider_class_deleted')?>",
						text:"<?= $this->lang->line('informations_updated')?>",
						timer: 3000
					}).then(()=>{
						location.reload();
					});
				}else{
					toastr.error(data.message , "<?= $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')?>");
			}
		});
		event.preventDefault();
	});
</script>
<script type="text/javascript">

	$(document).ready(function () {
		$('[data-toggle="tooltip"]').tooltip();

		// Years Grid
		var actions1 = $("#years_prices_grid td:last-child").html();
		let maxAge = <?= $nh_config->age_limit_of_child_beneficiary ?? 0 ?>;
		// 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 = $("#years_prices_grid tbody tr:last-child").index();
			var initValue = 0;

			$("#years_prices_grid").find('tr').eq(index+1).each(function(i, element) {
				$(element).find('td').each(function(i, element) {
					// Recuperer l'ancien age maximal
					var colVal = $(element).text();
					if(i === 1 ){
						initValue = parseInt(colVal.trim()) + 1 ;
					}
				});
			});


			var row = '<tr>' +
				`<td><input type="number" required min="0" max="99" class="form-control" name="min_age" value="${initValue}" disabled></td>` +
				`<td><input type="number"  required min="0" max="99" class="form-control" name="max_age" value="${maxAge}" ></td>` +
				'<td><input type="number" required class="form-control" min="-100" max="100" step="any" name="markup_percentage"></td>' +
				'<td> ' + actions1 + '</td>' +
				'</tr>';
			$("#years_prices_grid").append(row);
			$("#years_prices_grid tbody tr").eq(index + 1).find(".add, .edit").toggle();
			$('[data-toggle="tooltip"]').tooltip();
		});
		// Add row on add button click
		$(document).on("click", ".add1", function () {
			var empty = false;
			var input = $(this).parents("tr").find('input[type="number"]');
			var min = parseFloat($(this).parents("tr").find('input[name="min_age"]').first().val());
			var max = parseFloat($(this).parents("tr").find('input[name="max_age"]').first().val());

			input.each(function () {
				if ($(this).attr('name') == 'min_age') {
					if (min > maxAge || min >= max) {
						$(this).addClass("error");
						$(this)[0].reportValidity();
						empty = true;
						if(min > maxAge){
							toastr.error("<?= $this->lang->line('first_rule_years_price_grid')?>", "<?= $this->lang->line('request_error')?>");
						}
					} else {
						$(this).removeClass("error");
					}
				} else if ($(this).attr('name') == 'max_age') {
					console.log('max')
					if (max > maxAge || max <= min) {
						$(this).addClass("error");
						$(this)[0].reportValidity();
						empty = true;
						if(max > maxAge){
							toastr.error("<?= $this->lang->line('second_rule_years_price_grid')?>", "<?= $this->lang->line('request_error')?>");
						}
					} else {
						$(this).removeClass("error");
					}
				} else {
					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");
			}
		});
		// Edit row on edit button click
		$(document).on("click", ".edit1", function () {
			$(this).parents("tr").find("td:not(:last-child)").each(function (index) {
				if (index == 0)
					$(this).html('<input type="number" required class="form-control" min="0" name="min_age" value="' + $(this).text() + '" disabled>');
				if (index == 1)
					$(this).html('<input type="number" required class="form-control" name="max_age" value="' + $(this).text() + '" disabled>');
				if (index == 2)
					$(this).html('<input type="number" required class="form-control"  min="-100" max="100" step="any" name="markup_percentage" value="' + $(this).text() + '">');
			});
			$(this).parents("tr").find(".add, .edit").toggle();
			$(".new1").attr("disabled", "disabled");
		});
		// Delete row on delete button click
		$(document).on("click", ".delete1", function () {
			$(this).parents("tr").remove();
			$(".new1").removeAttr("disabled");
		});

		//Months Grid
		var actions2 = $("#months_prices_grid td:last-child").html();

		function getPaymentPeriods(selectedValue) {
			var periods = '';
			<?php foreach ($payment_periods as $p ) {?>
			var val = "<?=$p?>";
			var selected = val === selectedValue ? 'selected' : '';
			periods += (`<option value='<?= $p ?>' ${selected} > <?= $this->lang->line($p) ?> </option>`);
			<?php } ?>
			return periods;
		}


			// 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 = $("#months_prices_grid tbody tr:last-child").index();
			var row = '<tr>' +
				'<td><input type="number" required min="1"  class="form-control" name="number_of_months"></td>' +
				'<td><input type="number" required min="0" step="0.01" class="form-control" name="min_amount" ></td>' +
				'<td><input type="number" required min="0" step="0.01" class="form-control" name="max_insurance_coverage_amount" ></td>' +
				'<td><input type="number" min="1" step="1" class="form-control" name="waiting_period_days" ></td>' +
				'<td>' +
					'<select  required class="form-control" name="payment_period" >' +
						getPaymentPeriods(null)+
					'</select>' +
				'</td>' +
				'<td><input type="number" min="1" step="1" class="form-control" name="payment_duration_months" ></td>' +
				'<td> ' + actions2 + '</td>' +
				'</tr>';
			$("#months_prices_grid").append(row);
			$("#months_prices_grid 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[type="number"]');
			var minAmount = parseFloat($(this).parents("tr").find('input[name="min_amount"]').first().val());
			var maxAmount = parseFloat($(this).parents("tr").find('input[name="max_insurance_coverage_amount"]').first().val());
			var select = $(this).parents("tr").find('select');

			input.each(function () {
				if ($(this).attr('name') == 'min_amount') {
					if (minAmount > maxAmount) {
						$(this).addClass("error");
						$(this)[0].reportValidity();
						empty = true;
						toastr.error("<?= $this->lang->line('first_rule_months_price_grid')?>", "<?= $this->lang->line('request_error')?>");
					} else {
						$(this).removeClass("error");
					}
				} else {
					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").attr('name', $(this).attr('name')).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()).attr("name",$(this).attr('name'));
			});
		});
		// Edit row on edit button click
		$(document).on("click", ".edit2", function () {
			var length = $(this).parents("tr").find("td:not(:last-child)").length;
			// If startAt =7 , alors il exite deja en BD, car on a hidden la 1ere colonne qui contient l'id
			var startAt = length === 7 ? 1 : 0;
			$(this).parents("tr").find("td:not(:last-child)").each(function (index) {
				if (index === startAt)
					$(this).html('<input type="number" required class="form-control" min="1" name="number_of_months" value="' + $(this).text() + '">');
				if (index === (startAt + 1))
					$(this).html('<input type="number" required class="form-control"  min="0"  step="0.01" name="min_amount" value="' + $(this).text() + '">');
				if (index === (startAt + 2))
					$(this).html('<input type="number" required class="form-control"  min="0"  step="0.01" name="max_insurance_coverage_amount" value="' + $(this).text() + '">');
				if (index === (startAt + 3))
					$(this).html('<input type="number"  class="form-control"  min="1"  step="1" name="waiting_period_days" value="' + $(this).text() + '">');
				if (index === (startAt + 4)){
					let val = $(this).attr("value");
					if(!val){
						val = $(this).attr("payment_period");
					}
					$(this).html('<select class="form-control" name="payment_period" required >'+ getPaymentPeriods(val)+ '</select>');
				}
				if (index === (startAt + 5))
					$(this).html('<input type="number"  class="form-control"  min="1"  step="1" name="payment_duration_months" 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");
		});
	});
</script>
<!-- Page script -->
<script src="<?= base_url('dist/js/custom.js') ?>"></script>
