<!-- 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" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.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/toastr/toastr.css') ?>">
<div class="content-wrapper">
	<?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;

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

		<h1>
			<?= isset($category) ? 'Wallet' : $this->lang->line('Gestion des wallets');
			echo ' ' . $network . ' - ' . $country
					. ' :: ' . $this->lang->line('balance_statement'); ?>
			<!--			<input type="button" class="btn btn-primary pull-right" id="Bactiver"-->
			<!--				   value="Activer/Désactiver le(s) réseau(x)" />-->
		</h1>
		<?php
		

		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
			}
		}
		// 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
		$converter = new CurrencyConverter($provider);
		$context = new AutoContext();
		?>
	</section>
	<section class="content">
		<div class="row">
			<div class="col-xs-12">
				<div class="box">
					<div class="box-header">
						<h3 class="box-title"><?= $this->lang->line('export_balance_statement') ?></h3>
						<div class="box-tools">
							<?php if ($this->session->userdata('category') != 'super') { ?>
								<a class="btn btn-primary" href="<?= current_url().('?history=commission_payments')?>">
									<?= $this->lang->line('commission_payments_history'); ?>
								</a>
							<?php } ?>
						</div>
					</div>
					<div class="box-body" style="overflow-x:auto;">
						<?php
						if ($wallets){
						$numrows = $wallets->num_rows();
						$num = 0;
						if ($numrows > 0) {
						$fmt = new NumberFormatter('fr_FR', NumberFormatter::DECIMAL);
						?>

						<table id="transactions" class="table table-bordered table-striped"
							   data-lang="<?= $this->session->userdata('site_lang') ?>"
							   data-rows="<?= $numrows ?>"
							   data-currency="<?= $this->session->userdata('currency_code') ?>">
							<thead>
							<tr>
								<th align='center'>ID</th>
								<th><?= $this->lang->line('Solde Principal') ?></th>
								<th><?= $this->lang->line('Solde Commission') ?></th>
								<th><?= $this->lang->line('Telephone') ?></th>
								<th><?= $this->lang->line('code membre') ?></th>
								<th>Agent</th>
								<th><?=$this->lang->line('sponsor')?></th>
								<?php if ($this->session->userdata('category') != 'super') { ?>
									<th align='center'>Action</th>
								<?php } ?>
							</tr>
							</thead>
							<tbody>

							<?php
							foreach ($wallets->result() as $row) {
								$parrain = $row->parrain;
								if($row->codeMembre == $row->codeParrain)
									$parrain ='';
								else if($row->codeParrain == $this->session->userdata('member_code'))
									$parrain = $this->lang->line('Vous');

								$num++;
								echo "<tr>
											<td align='center' >$num</td>
											<td>" . Money::of(round($row->balance_princ, 2), $row->currency_code, $context)->formatTo('fr_FR') . "</td>
											<td>" . Money::of(round($row->balance_com, 2), $row->currency_code, $context)->formatTo('fr_FR') . "</td>
											<td>" . $row->transactionNumber . "</td>
											<td>" . $row->codeMembre . "</td>
											<td>" . $row->lastname . "</td>
											<td>" . $parrain . "</td>";
								?>
								<?php if ($this->session->userdata('category') != 'super') { ?>
									<td>
										<button data-toggle="modal" data-target="#payCommission" class="btn btn-danger payCommissionBtn"
												data-id_wallet_agent="<?=$row->wallet_id?>" <?php if($row->category != 'super') echo "style = 'display:none'"?> >
											<?= $this->lang->line('pay_commission_in_cash')?>
										</button>
									</td>
								<?php } ?>
								</tr>

								<?php
							}
							?>
							</tbody>
						</table>

							<?php
							} else {
								echo $this->lang->line('Aucune transaction');
							}
							} else {
								echo $this->lang->line('Aucune transaction');
							}
							?>


					</div>
				</div>
			</div>
		</div>
		<div class="modal fade" id="payCommission" tabindex="-1" role="dialog" aria-hidden="true">
			<div class="modal-dialog" role="document">
				<div class="modal-content">
					<div class="modal-header">
						<h3 class="modal-title"><?= $this->lang->line('pay_commission_in_cash'); ?></h3>
					</div>
					<div class="modal-body">
						<?php if ($walletPassword != null) { ?>
							<form id="payCommissionForm">
								<div class="form-group">
									<label for="montant" class="col-form-label"><?= $this->lang->line('Montant') ?></label>
									<input type="text"  required class="form-control" id="montant"  name="montant" >
								</div>
								<div class="form-group">
									<label><?= $this->lang->line('mot de passe') ?></label>
									<div class="input-group" id="show_hide_password">
										<input class="form-control"  name="password" id="password" type="password">
										<div class="input-group-addon">
											<a href=""><i class="fa fa-eye-slash" aria-hidden="true"></i></a>
										</div>
									</div>
								</div>
								<div class="clearfix">
									<a href="#" id="resetPassword" class="pull-right forgot-password" data-wallet_password_id="<?= $walletPassword->id ?>" data-network="<?= $network ?>" data-country="<?= $country ?>"
									   data-email="<?= $walletPassword->email ?>">
										<?= $this->lang->line('i_forgot_password') ?>
									</a>
								</div>
							</form>
						<?php }else{ ?>
							<div class="text-center">
								<h4> <?= $this->lang->line('no_wallet_password') ?></h4>
								<a href="<?= base_url('Hyperviseur_dash/walletPassword') ?>"  alt="" class="btn btn-primary"><?= $this->lang->line('click_here') ?></a>
							</div>
						<?php } ?>
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-secondary" data-dismiss="modal"><?= $this->lang->line('Fermer'); ?></button>
						<?php if ($walletPassword != null) { ?>
							<button type="button" class="btn btn-primary"  data-salt="<?= $walletPassword->salt ?>" data-encrypted_password="<?= $walletPassword->encrypted_password ?>" id="pay" >
								<?= $this->lang->line('recharge'); ?>
							</button>
						<?php }?>
					</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 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 src="<?= base_url('dist/js/sweetalert2.js') ?>"></script>
<script src="<?= base_url('bower_components/toastr/toastr.js') ?>"></script>
<script src="https://cdn.jsdelivr.net/npm/autonumeric@4.5.4"></script>

<script>
	$(function () {

		$("#show_hide_password a").on('click', function(event) {
			event.preventDefault();
			if($('#show_hide_password input').attr("type") == "text"){
				$('#show_hide_password input').attr('type', 'password');
				$('#show_hide_password i').addClass( "fa-eye-slash" );
				$('#show_hide_password i').removeClass( "fa-eye" );
			}else if($('#show_hide_password input').attr("type") == "password"){
				$('#show_hide_password input').attr('type', 'text');
				$('#show_hide_password i').removeClass( "fa-eye-slash" );
				$('#show_hide_password i').addClass( "fa-eye" );
			}
		});

		const lang = $('table').data('lang');
		var rows = $('table').data('rows');
		var currency = $('table').data('currency');
		const format = lang === 'french' ? 'fr' : 'en';
		moment.updateLocale(moment.locale(format), {invalidDate: ""}); // Blank text when is invalid date
		var table = $('#transactions').DataTable({
			"aaSorting": [[0, "asc"]],
			"columnDefs": [
				// {
				// targets: [8],
				// render: $.fn.dataTable.render.moment('YYYY-MM-DD HH:mm:ss', 'D MMMM YYYY HH:mm:ss', format),
				// },
				// {
				// 	"targets": [8],
				// 	"visible": false
				// }
			],
			dom: 'Bfrtip',
			"buttons": [
				'pageLength',
				{
					extend: 'excelHtml5',
					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 ([1, 2].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, ""));
								}
							}
						}
					},
					customize: function (xlsx) {
						var sheet = xlsx.xl.worksheets['sheet1.xml'],
								sum = 0;
						var sumCom = 0;

						// read each row
						// Loop over the cells in column `B`
						$('row c[r^="B"]', sheet).each(function () {

							// Get the value and strip the non numeric characters
							var value = $(this).text();
							value = value.replace(',', ".")
							sum += Number(value.replace(/[^0-9\.-]+/g, ""));
						});

						// Total commission
						$('row c[r^="C"]', sheet).each(function () {

							// Get the value and strip the non numeric characters
							var value = $(this).text();
							value = value.replace(',', ".")
							sumCom += Number(value.replace(/[^0-9\.-]+/g, ""));
						});

						// Create our number formatter.
						var formatter = new Intl.NumberFormat('en-US', {
							style: 'currency',
							currency: currency,

							// the default value for minimumFractionDigits depends on the currency
							// and is usually already 2
							minimumFractionDigits: 2,
						});


						function addTotal(index, data , sum , column) {
							msg = '<row r="' + index + '">';
							for (i = 0; i < data.length; i++) {
								var key = data[i].k;
								var value = data[i].v;
								msg += '<c t="inlineStr" r="' + column + (rows + 3) + '" s="42">';
								msg += '<is>';
								msg += '<t>' + formatter.format(sum) + '</t>';
								msg += '</is>';
								msg += '</c>';
							}
							msg += '</row>';
							return msg;
						}

						//insert
						var r1 = addTotal(1, [{
							k: 'A',
							v: 'ColA'
						}],sum ,'B');

						var r2 = addTotal(1, [{
							k: 'A',
							v: 'ColA'
						}],sumCom,'C');

						sheet.childNodes[0].childNodes[1].innerHTML = r1 + r2+ sheet.childNodes[0].childNodes[1].innerHTML;
					},
					title: "<?= $this->lang->line('balance_statement') ?>"+' - Date : ' + moment().format("dddd, Do MMMM YYYY, h:mm:ss")
				},
				{
					extend: 'csvHtml5',
					title: "<?= $this->lang->line('balance_statement') ?>"+' - Date : ' + moment().format("dddd, Do MMMM YYYY, h:mm:ss")
				},
				{
					extend: 'pdfHtml5',
					orientation: 'portrait',
					pageSize: 'LEGAL',
					title: "<?= $this->lang->line('balance_statement') ?>"+' - Date : ' + moment().format("dddd, Do MMMM YYYY, h:mm:ss")
				}
			]
		});

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

	var id_wallet_agent = null;
	var anElement = null;

	$('.payCommissionBtn').click(function () {
		id_wallet_agent = $(this).data('id_wallet_agent');
		anElement = new AutoNumeric('#montant', '', {digitGroupSeparator: ' ', decimalPlaces:'0', minimumValue : '1' , maximumValue: '99999999999999999999999999'});

	})

	$('#resetPassword').click(function () {
		const wallet_password_id = $(this).data('wallet_password_id');
		const network = $(this).data('network');
		const country = $(this).data('country');
		const email = $(this).data('email');
		let button  = $(this);
		button.prop("disabled",true);
		$.ajax({
			url: '<?= base_url('Hyperviseur_dash/resetWalletPassword')?>',
			type: 'POST',
			dataType: 'json',
			data: {
				"wallet_password_id": wallet_password_id,
				"email": email,
				"network" : network ,
				"country" : country
			},
			success: function (data) {
				if(data=='200'){
					Swal.fire({
						icon: 'success',
						title: "<?= $this->lang->line('password_has_been_reset')?>",
						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')?>");
			},
			complete: function (){
				button.prop("disabled",false);
			}
		});
	});


	$('#pay').click(function () {

		const salt = $(this).data('salt');
		const encrypted_password = $(this).data('encrypted_password');
		let button = $(this);

		if ($('#payCommissionForm')[0].checkValidity()) {
			const montant = anElement.getNumber();  //parseFloat($('#montant').val());
			const password = $('#password').val();

			button.prop("disabled",true);
			$.ajax({
				url: '<?= base_url('Hyperviseur_dash/pay_commission_in_cash')?>',
				type: 'POST',
				dataType: 'json',
				data: {
					"id_wallet_agent" : id_wallet_agent,
					"montant": montant ,
					"password": password,
					"salt" : salt,
					"encrypted_password" : encrypted_password
				},
				success: function (data) {
					if(data=='200'){
						Swal.fire({
							icon: 'success',
							title: "<?= $this->lang->line('payment_done')?>",
							text: "<?= $this->lang->line('informations_updated')?>",
							timer: 3000
						}).then(()=>{
							location.reload();
						});
						// alert("Les informations ont été mises à jour.") ? "" :
					}else if(data == '400'){
						toastr.error("<?= $this->lang->line('incorrect_password')?>" , "<?= $this->lang->line('request_error')?>");
					}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')?>");
				},
				complete : function () {
					button.prop("disabled",false);
				}
			});


		} else {
			$('#payCommissionForm')[0].reportValidity();
		}

	});
</script>
