<!-- DataTables -->
<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 rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.6.2/css/buttons.dataTables.min.css">
<div class="content-wrapper">

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

		<h1>
			<?= $this->lang->line('cancellation_credit_requests'); ?>
		</h1>
		<?php
		$site_url = base_url();

		if ($alert == "ok") {

			if (!$success == "ok") {
				?>
				<div class='alert alert-danger alert-dismissible col-xs-6'>
					<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>
					<h4><i class='icon fa fa-ban'></i> Erreur!</h4>
					<?= $message; ?>
				</div>

				<?php
			} else {
				?>
				<div class="alert alert-success alert-dismissible col-xs-6">
					<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
					<h4><i class="icon fa fa-check"></i> Success!</h4>
					<?= $message; ?>
				</div>

				<?php
			}
		}
		?>

	</section>
	<section class="content">
		<div class="row">
			<div class="col-md-4 col-sm-6 col-xs-12">
				<div class="info-box">
					<span class="info-box-icon bg-aqua"><i class="ion ion-android-arrow-down"></i></span>

					<div class="info-box-content">
						<span class="info-box-text"><?= $this->lang->line('Temps moyen de traitement entrant'); ?> </span>
						<span class="info-box-number">
                            <?php
							if ($temp_moyen) {
								if (duree($temp_moyen) == "") {
									echo "0s";
								} else {
									echo duree($temp_moyen);
								}
							} else {
								echo $this->lang->line('Aucune demande traitée');
							}
							?>
                        </span>
					</div>
				</div>
			</div>
			<div class="col-md-4 col-sm-6 col-xs-12">
				<div class="info-box">
					<span class="info-box-icon bg-aqua"><i class="ion ion-android-time"></i></span>
					<div class="info-box-content">
						<span class="info-box-text"> <?= $this->lang->line('Période') ?> </span>
						<span class="info-box-number">
                                    <input id="picker"
										   style="background: #fff; cursor: pointer; padding: 1px 1px; border: 1px solid #ccc; width: 100%"
										   type="text" name="daterange"
										   data-lang="<?= $this->session->userdata('site_lang') ?>"
										   data-type="<?= $demand_type ?>"
										   data-category="<?= $this->session->userdata('category') ?>"
										   value="<?= ($debut != null & $fin != null) ? $debut . ' - ' . $fin : '' ?>"
									/>
                            </span>
						<span> Format : <?= $this->session->userdata('site_lang') === 'french' ? 'Jour - Mois - Année ' : 'Year - Month - Day' ?> </span>
					</div>
				</div>
			</div>
		</div>
			<div class="row">
				<div class="col-md-12">
						<div class="box">
							<div class="box-header with-border">
								<h3 class="box-title"><?= $this->lang->line('incoming_credits_requests_accepted'); ?></h3>
								<div class="box-tools">
									<a class="btn btn-success" href="<?= current_url().'?show=history'?>">
										<?= $this->lang->line('Historique'); ?>
									</a>
								</div>
							</div>
							<div class="box-body" style="overflow-x:auto;">

								<table id="listeMembres1" class="table table-bordered table-striped table-modified">
									<thead>
									<?php
									echo "<tr class='label-primary'>
									<th> ID </th>
									<th>" . $this->lang->line('Emetteur') . "</th>
									<th>" . $this->lang->line('receiver'). "</th>
									<th>" . $this->lang->line('Montant') . "</th>
									<th>" . $this->lang->line('Date de la demande') . "</th>
									<th>" . $this->lang->line('Date de traitement') . "</th>
									<th>" . $this->lang->line('Délai de traitement') . "</th>
									<th>" . $this->lang->line('Délai de traitement')."(en minutes)" . "</th>
										<th> Action </th>
								</tr>";

									?>
									</thead>

								</table>


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


<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css"/>
<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/plug-ins/1.10.20/dataRender/datetime.js"></script>
<script src="<?= base_url('dist/js/sweetalert2.js') ?>"></script>
<script src="<?= base_url('bower_components/toastr/toastr.js') ?>"></script>

<script>
	$(function () {
		const lang = $('#picker').data('lang');
		const format = lang === 'french' ? 'fr' : 'en';
		moment.updateLocale(moment.locale(format), {invalidDate: ""}); // Blank text when is invalid date

		var table = $('#listeMembres1').DataTable({
			// Processing indicator
			"processing": true,
			"language": {
				"processing": "<?= $this->lang->line('loading') ?>"
			},
			// DataTables server-side processing mode
			"serverSide": true,
			// Initial no order.
			"order": [],
			// Load data from an Ajax source
			"ajax": {
				"url": "<?= base_url('pagination/AcceptedCreditRequests/getLists'); ?>",
				"data":{
					"startDate" : "<?= $startDate?>",
					"endDate" : "<?= $endDate?>",
					"id_network" : <?= $id_network ?>
				},
				"type": "POST"
			},
			"aaSorting": [[4, "desc"]],
			"columnDefs": [{
				"targets": [4, 5],
				// "orderable": false,
				render: $.fn.dataTable.render.moment('YYYY-MM-DD HH:mm:ss', 'D MMMM YYYY HH:mm:ss', format)
			},
				{ "orderable": false, "targets": 8 },
				{
					"targets": [ 7 ],
					"visible": false
				}
			],
			dom: 'Bfrtip',
			"buttons": [
				'pageLength',
				{
					"extend": 'excelHtml5',
					title: "<?= $this->lang->line('incoming_credits_requests_accepted') ?>",
					trim: false,
					"action": newexportaction
				},
				{
					extend: 'csvHtml5',
					title: "<?= $this->lang->line('incoming_credits_requests_accepted') ?>",
					trim: false,
					"action": newexportaction
				},
				{
					extend: 'pdfHtml5',
					orientation: 'landscape',
					pageSize: 'LEGAL',
					title: "<?= $this->lang->line('incoming_credits_requests_accepted') ?>",
					trim: false,
					"action": newexportaction
				},
				// 'colvis'
			]
		});

		table.buttons().container()
				.appendTo('#example_wrapper .col-sm-6:eq(0)');

		function newexportaction(e, dt, button, config) {
			var self = this;
			var oldStart = dt.settings()[0]._iDisplayStart;
			dt.one('preXhr', function (e, s, data) {
				// Just this once, load all data from the server...
				data.start = 0;
				data.length = 2147483647;
				dt.one('preDraw', function (e, settings) {
					// Call the original action function
					if (button[0].className.indexOf('buttons-copy') >= 0) {
						$.fn.dataTable.ext.buttons.copyHtml5.action.call(self, e, dt, button, config);
					} else if (button[0].className.indexOf('buttons-excel') >= 0) {
						$.fn.dataTable.ext.buttons.excelHtml5.available(dt, config) ?
								$.fn.dataTable.ext.buttons.excelHtml5.action.call(self, e, dt, button, config) :
								$.fn.dataTable.ext.buttons.excelFlash.action.call(self, e, dt, button, config);
					} else if (button[0].className.indexOf('buttons-csv') >= 0) {
						$.fn.dataTable.ext.buttons.csvHtml5.available(dt, config) ?
								$.fn.dataTable.ext.buttons.csvHtml5.action.call(self, e, dt, button, config) :
								$.fn.dataTable.ext.buttons.csvFlash.action.call(self, e, dt, button, config);
					} else if (button[0].className.indexOf('buttons-pdf') >= 0) {
						$.fn.dataTable.ext.buttons.pdfHtml5.available(dt, config) ?
								$.fn.dataTable.ext.buttons.pdfHtml5.action.call(self, e, dt, button, config) :
								$.fn.dataTable.ext.buttons.pdfFlash.action.call(self, e, dt, button, config);
					} else if (button[0].className.indexOf('buttons-print') >= 0) {
						$.fn.dataTable.ext.buttons.print.action(e, dt, button, config);
					}
					dt.one('preXhr', function (e, s, data) {
						// DataTables thinks the first item displayed is index 0, but we're not drawing that.
						// Set the property to what it was before exporting.
						settings._iDisplayStart = oldStart;
						data.start = oldStart;
					});
					// Reload the grid with the original page. Otherwise, API functions like table.cell(this) don't work properly.
					setTimeout(dt.ajax.reload, 0);
					// Prevent rendering of the full data to the DOM
					return false;
				});
			});
			// Requery the server with the new one-time export settings
			dt.ajax.reload();
		}
	});
</script>

<script type="text/javascript">
	var startDate;
	var endDate;

	$(function () {

		const lang = $('#picker').data('lang');
		$('input[name="daterange"]').daterangepicker({
			opens: 'left',
			autoUpdateInput: false,
			locale: {
				format: lang === 'french' ? 'DD-MM-YYYY' : 'YYYY-MM-DD',
				cancelLabel: 'Clear'
			}
		}, function (start, end, label) {
			const debut = start.format('YYYY-MM-DD');
			const fin = end.format('YYYY-MM-DD');

			window.location.replace("<?= base_url('Hyperviseur_dash/demandsCancellation')?>" + "?d=" + debut + "&f=" + fin);

		});
		$('input[name="daterange"]').on('cancel.daterangepicker', function (ev, picker) {
			//do something, like clearing an input
			$('#daterange').val('');
			window.location = "<?= current_url()?>";
		});
	});

</script>

<script>
	$(document).on("click", "#cancelDemand", function () {
		const id_demand = $(this).data('id-demand');
		let button  = $(this)
		button.prop("disabled",true);
		$.ajax({
			url: '<?= base_url('Hyperviseur_dash/cancelCreditRequest')?>',
			type: 'POST',
			dataType: 'json',
			data: {"id_demand": id_demand},
			async: true,
			success: function (data) {
				if (data == '200') {
					Swal.fire({
						icon: 'success',
						title: "<?= $this->lang->line('canceled_credit_request')?>",
						text: "<?= $this->lang->line('informations_updated')?>",
						timer: 3000
					}).then(() => {
						location.reload();
					});
					// alert("Les informations ont été mises à jour.") ? "" : location.reload();
				} else {
					toastr.error("<?= $this->lang->line('error_message')?>", "<?= $this->lang->line('request_error')?>");
				}
			},
			error: function (resultat, statut, erreur) {
				console.log(resultat + " " + erreur);
				toastr.error("<?= $this->lang->line('error_message')?>", "<?= $this->lang->line('request_error')?>");
			},
			complete: function (){
				button.prop("disabled",false);
			}
		});
	});
</script>
