<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') ?>">
<div class="content-wrapper">
	<section class="content-header">

		<h1 style="margin-bottom: 20px">
			<?= $this->lang->line('subscriptions') . ' :: ' . $this->lang->line('subscription_detail') . ' - ' . $insurance_subscription_id; ?>

			<div class="pull-right">
				<?php if(in_array($subscription->state,['UNDER_VALIDATION','AWAITING_FURTHER_INFORMATION'])) { ?>
					<button id="accept-subscription" class="btn btn-success" >
						<?= $this->lang->line('accept') ?>
					</button>
					<?php if($subscription->state == 'UNDER_VALIDATION') { ?>
						<button class="btn btn-warning" data-toggle="modal" data-target="#more-information-modal">
							<?= $this->lang->line('more_information') ?>
						</button>
					<?php } ?>
					<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('insured_infos')?></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><?= $user->lastname ?? '' . $user->firstname ?? ''; ?></strong></td>
						</tr>

						<tr>
							<td><?= $this->lang->line('Adresse')?></td>
							<td style="text-align: center"><strong><?= $user->adresse ?></strong></td>
						</tr>
						<tr>
							<td><?= $this->lang->line('Contact')?></td>
							<td style="text-align: center"><strong><?= $user->phone." | ".$user->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-3 col-xs-6">
				<div class="small-box bg-green-active">
					<div class="inner">
						<h3><?= Money::of(round($subscription->total_bonus_amount, 2), $subscription->currency_code, $this->context)->formatTo('fr_FR') ?></h3>
						<p><?= $this->lang->line('bonus_amount') ?></p>
					</div>
					<div class="icon">
						<i class="ion ion-cash"></i>
					</div>
				</div>
			</div>

			<div class="col-lg-3 col-xs-6">
				<div class="small-box bg-red">
					<div class="inner">
						<h3><?= Money::of(round($subscription->bonus_amount, 2), $subscription->currency_code, $this->context)->formatTo('fr_FR') ?></h3>
						<p><?= $this->lang->line('insured_bonus_amount') ?></p>
					</div>
					<div class="icon">
						<i class="ion ion-cash"></i>
					</div>
				</div>
			</div>

			<div class="col-lg-3 col-xs-6">
				<div class="small-box bg-light-blue">
					<div class="inner">
						<h3> <?= $subscription->number_of_months ?> </h3>
						<p><?= $this->lang->line('number_of_months') ?></p>
					</div>
					<div class="icon">
						<i class="fa fa-clock-o"></i>
					</div>
				</div>
			</div>

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

		</div>


		<div class="row">
			<div class="col-lg-6 col-xs-6">
				<div class="small-box bg-aqua-active">
					<div class="inner">
						<h3 style="white-space: pre-wrap; font-size: 1.9em;"><?= $this->lang->line($subscription->insurance_action) ?></h3>
						<p><?= $this->lang->line('reason') ?></p>
					</div>
					<div class="icon">
						<i class="fa fa-info"></i>
					</div>
				</div>
			</div>
			<div class="col-lg-3 col-xs-6">
				<div class="small-box bg-aqua-active">
					<div class="inner">
						<h3 style="white-space: pre-wrap; font-size: 1.9em;"><?= $this->lang->line($subscription->payment_period) ?></h3>
						<p><?= $this->lang->line('payment_period') ?></p>
					</div>
					<div class="icon">
						<i class="fa fa-clock"></i>
					</div>
				</div>
			</div>
			<div class="col-lg-3 col-xs-6">
				<div class="small-box bg-aqua-active">
					<div class="inner">
						<h3 style="white-space: pre-wrap; font-size: 1.9em;"><?= $subscription->number_of_fractions ?></h3>
						<p><?= $this->lang->line('number_of_fractions') ?></p>
					</div>
					<div class="icon">
						<i class="fa fa-clock"></i>
					</div>
				</div>
			</div>
		</div>

		<div class="box box-primary">
			<div class="box-header with-border">
				<h3 class="box-title"><?= $this->lang->line('beneficiaries') ?></h3>
			</div>
			<div class="box-body" style="overflow-x:auto;">
				<table id="example1" class="table table-bordered table-hover">
					<thead>
					<tr>
						<th>#</th>
						<th><?= $this->lang->line('Nom'); ?></th>
						<th><?= $this->lang->line('gender'); ?></th>
						<th><?= $this->lang->line('birth_date'); ?></th>
						<th>Affiliation</th>
						<th><?= $this->lang->line('bonus_amount'); ?></th>
						<th>Images</th>
					</tr>
					</thead>
					<tbody>
					<?php
					if (isset($beneficiaries)) {

						foreach ($beneficiaries->result() as $i => $row) {
							$bonus_amount = Money::of(round($row->bonus_amount, 2), $subscription->currency_code, $this->context)->formatTo('fr_FR');

							echo "<tr>
												<td>" . ($i+1) . "</td>
												<td>" . $row->lastname.' '.$row->firstname . "</td>
												<td>" . $row->gender . "</td>
											   <td>" . $row->birthdate . "</td>
                                               <td>".$this->lang->line($row->affiliation)."</td>
                                               <td>" . $bonus_amount. "</td>";
							?>

							<td>
										<button class="btn btn-primary" data-target="<?= '#images-modal'.$i ?>" data-toggle="modal">
											<?= $this->lang->line('show'); ?>
										</button>
								</td>
							</tr>
							<?php $this->load->view('nano_health/modals/beneficiary_images_modal',['i' => $i, 'row' => $row]) ?>
							<?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_subscription') ?></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-subscription"><?= $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="more-information-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('more_information_subscription') ?></h4>
					</div>
					<div class="modal-body">
						<form id="more-information-form">
							<div class="row">
								<div class="col-lg-12">
									<div class="form-group">
										<label class="col-form-label">Message</label>
										<textarea required class="form-control" rows="5" name="message"></textarea>
									</div>
								</div>
							</div>
						</form>
					</div>
					<div class="modal-footer">
						<button class="btn btn-danger pull-left"
								id="more-information-subscription"><?= $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>

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

	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('beneficiaries') . ' :: ' . $this->lang->line('subscription_detail') . ' - ' . $insurance_subscription_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].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('beneficiaries') . ' :: ' . $this->lang->line('subscription_detail') . ' - ' . $insurance_subscription_id?>",
					},
					{
						extend: 'pdfHtml5',
						orientation: 'landscape',
						pageSize: 'LEGAL',
						title: "<?= $this->lang->line('beneficiaries') . ' :: ' . $this->lang->line('subscription_detail') . ' - ' . $insurance_subscription_id?>",
					},
					// 'colvis'
				]
			}
	);

	$('#accept-subscription').click(function() {
		$.ajax({
			url: '<?= base_url('NanoHealthController/validateSubscription/'.$subscription->id )?>',
			type: 'POST',
			dataType: 'json',
			data: {
				<?php if(isset($category) && $category == 'AGENT') { ?>
					"nh_validating_agent_id": "<?= $this->session->userdata('agent_id') ?>",
				<?php } else { ?>
					"agent_id": "<?= $this->session->userdata('agent_id') ?>",
				<?php } ?>
			},
			success: function (data) {
				// console.log('data',data);
				if(data.status === 200){
					Swal.fire({
						icon: 'success',
						title: "<?= $this->lang->line('subscription_accepted')?>",
						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-subscription').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/rejectSubscription/'.$subscription->id)?>',
					type: 'POST',
					dataType: 'json',
					data: {
						<?php if(isset($category) && $category == 'AGENT') { ?>
							"nh_validating_agent_id": "<?= $this->session->userdata('agent_id') ?>",
						<?php } else { ?>
							"agent_id": "<?= $this->session->userdata('agent_id') ?>",
						<?php } ?>
						"reason": reason,
						"type" : "NORMAL"
					},
					success: function (data) {
						if (data.status === 200) {
							Swal.fire({
								icon: 'success',
								title: "<?= $this->lang->line('subscription_rejected')?>",
								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();
		}
	});

	$('#more-information-subscription').click(function () {
		if ($('#more-information-form')[0].checkValidity()) {
			let message = $("textarea[name=message]").val();
			if(message.length > 500 ){
				toastr.warning( "<?= $this->lang->line('message_rule')?>", "<?= $this->lang->line('management_rule')?>");
			}else{
				$.ajax({
					url: '<?= base_url('NanoHealthController/rejectSubscription/'.$subscription->id)?>',
					type: 'POST',
					dataType: 'json',
					data: {
						<?php if(isset($category) && $category == 'AGENT') { ?>
						"nh_validating_agent_id": "<?= $this->session->userdata('agent_id') ?>",
						<?php } else { ?>
						"agent_id": "<?= $this->session->userdata('agent_id') ?>",
						<?php } ?>
						"reason": message,
						"type" : "MORE_INFORMATION"
					},
					success: function (data) {
						if (data.status === 200) {
							Swal.fire({
								icon: 'success',
								title: "<?= $this->lang->line('subscription_more_information')?>",
								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 {
			$('#more-information-form')[0].reportValidity();
		}
	});

</script>
