<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') ?>">
<div class="content-wrapper">
	<!-- Content Header (Page header) -->
	<section class="content-header">
		<h1>
			<?= $this->lang->line('payment_aggregators') ; ?>
		</h1>
	</section>

	<section class="content">
		<div class="row">
			<div class="col-xs-8">
				<div class="box">
					<div class="box-header">
						<h3 class="box-title"><?= $this->lang->line('payment_aggregators'); ?></h3>
					</div>
					<div class="box-body" style="overflow-x:auto;">
						<table id="aggregators" class="table table-bordered table-striped">
							<thead>
							<tr>
								<th align='center'>#</th>
								<th><?= $this->lang->line('Nom'); ?></th>
								<th align='center'><?= $this->lang->line('Adresse'); ?></th>
								<th align='center'><?= $this->lang->line('Contact'); ?></th>
								<th align='center'><?= $this->lang->line('Statut'); ?></th>
								<th align='center'><?php echo $this->lang->line('Activer'); ?></th>
								<th>Action</th>
							</tr>
							</thead>
							<tbody>
							<?php
								if(isset($aggregators)){
									foreach ($aggregators as $i => $row) {
										?>
										<tr>
											<td align='center'><?= $i+1?></td>
											<td><?= $row->name ?></td>
											<td align='center'><?=$row->address?></td>
											<td align='center'><?=$row->phone?></td>
											<td align='center'><?= $this->lang->line($row->status ? 'Active' : 'Inactive'); ?></td>
											<td align='center'>
												<input type='checkbox' value='<?=$row->id?>' <?= $row->status ? 'checked' : '' ?>>
											</td>
											<td>
												<button class='btn btn-success edit-row' data-id="<?=$row->id?>" data-address="<?=$row->address?>" data-name="<?=$row->name?>"
														data-email="<?=$row->email?>" data-phone="<?=$row->phone?>" >
													<i class='fa fa-edit'></i>
												</button>
												<button data-toggle='modal' class='btn btn-danger delete-row' data-id="<?=$row->id?>">
													<i class='fa fa-trash'></i>
												</button>
											</td>
										 </tr>
									<?php
									}
								}
							?>
							</tbody>
						</table>
						<button type="button" class="btn btn-success" id="enableAggregator"><?php echo $this->lang->line('Activer/Désactiver'); ?></button>
					</div>
				</div>
			</div>
				<div class="col-xs-4">
					<div class="box">
						<div class="box-header">
							<h3 class="box-title"><?= $this->lang->line('add_aggregator'); ?></h3>
						</div>
						<div class="box-body">
							<form id="create-aggregator-form" class="bottom-75 center-block" method="post">
								<div class="form-group">
									<label for="name"><?= $this->lang->line('Nom'); ?></label>
									<input type="text" class="form-control input-lg" name="name" required>
								</div>
								<div class="form-group">
									<label for="email"><?= $this->lang->line('Email'); ?></label>
									<input type="email" class="form-control input-lg" name="email" required>
								</div>
								<div class="form-group">
									<label for="address"><?= $this->lang->line('Adresse'); ?></label>
									<input type="text" class="form-control input-lg" name="address">
								</div>
								<div class="form-group">
									<label for="contact"><?= $this->lang->line('Contact'); ?></label>
									<input type="text" class="form-control input-lg" name="phone">
								</div>
								<div class="form-group">
									<input type="submit"
										   value="<?= $this->lang->line('Ajouter'); ?>"
										   class="btn btn-primary">
								</div>
							</form>
						</div>
					</div>
				</div>
		</div>
		<div class="modal fade" id="editModal">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal" aria-label="Close">
							<span aria-hidden="true">&times;</span>
						</button>
						<h4 class="modal-title"><?= $this->lang->line('Mettre à jour des informations'); ?></h4>
					</div>
					<div class="modal-body">
						<form id="update-form" method="post" class="bottom-75 center-block">

							<div class="form-group">
								<label><?= $this->lang->line('Nom'); ?></label>
								<input type="text" class="form-control input-lg" name="name" required>
							</div>
							<div class="form-group">
								<label><?= $this->lang->line('Email'); ?></label>
								<input type="email" class="form-control input-lg" name="email" required>
							</div>
							<div class="form-group">
								<label><?= $this->lang->line('Adresse'); ?></label>
								<input type="text" class="form-control input-lg" name="address" >
							</div>
							<div class="form-group">
								<label><?= $this->lang->line('Contact'); ?></label>
								<input type="text" class="form-control input-lg" name="phone">
							</div>
							<div class="form-group" style="overflow-x:auto;">
								<div class="table-title">
									<div class="row">
										<div class="col-sm-8">
											<label for="nom"
												   class="col-form-label"><?=$this->lang->line('rate')?></label>
										</div>
										<div class="col-sm-4">
											<button type="button" class="btn btn-info add-new new5"><i class="fa fa-plus"></i> <?= $this->lang->line('add_rate') ; ?></button>
										</div>
									</div>
								</div>
								<table id="rates_list" class="table table-bordered">
									<thead>
									<tr>
										<th><?= $this->lang->line('Pays')?> </th>
										<th>Type</th>
										<th>Methode</th>
										<th><?=$this->lang->line('channel')?></th>
										<th><?=$this->lang->line('rate')?></th>
										<th><?=$this->lang->line('fixed_fees')?></th>
										<th><?=$this->lang->line('fixed_fees_currency')?></th>
										<th>Actions</th>
									</tr>
									</thead>
									<tbody>
									</tbody>
								</table>
							</div>
							<div class="form-group">
								<input id="btn-update" type="submit"
									   value="<?= $this->lang->line('save'); ?>" class="btn btn-primary">
								<button type="button" class="btn btn-default pull-right"
										data-dismiss="modal"><?= $this->lang->line('Fermer'); ?></button>
							</div>
						</form>
					</div>
				</div>
			</div>
		</div>

		<?php $this->load->view('include/delete_modal') ?>
		<?php $this->load->view('include/loader') ?>
	</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>
<script src="<?= base_url('bower_components/toastr/toastr.js') ?>"></script>
<script src="<?= base_url('dist/js/sweetalert2.js') ?>"></script>

<script>
	// Taxes
	const actions5 = '<a class="add add5" title="Add" data-toggle="tooltip"><i class="material-icons">&#xE03B;</i></a>\n' +
		'                            <a class="edit edit5" title="Edit" data-toggle="tooltip"><i class="material-icons">&#xE254;</i></a>\n' +
		'                            <a class="delete delete5" title="Delete" data-toggle="tooltip"><i class="material-icons">&#xE872;</i></a>';

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

		// Append table with add row form on add new button click
		$(".new5").click(function(){
			$(this).attr("disabled", "disabled");
			var index = $("#rates_list tbody tr:last-child").index();
			var row = "<tr> <td><input type='text' required class='form-control' name='country'></td> " +
				"<td><input type='text' required class='form-control' name='type'></td>" +
				"<td><input type='text' required class='form-control' name='method'></td>" +
				"<td><input type='text' class='form-control' name='channel'></td>" +
				"<td><input type='number' required class='form-control' min='0' value='0' step='.1' name='rate'></td>" +
				"<td><input type='number' class='form-control' min='0' step='.1' name='fixed_fees'></td>" +
				"<td><input type='text' class='form-control' name='fixed_fees_currency'></td>" +
				"<td>" + actions5 + "</td>" +
				"</tr>";
			$("#rates_list").append(row);
			$("#rates_list tbody tr").eq(index + 1).find(".add5, .edit5").toggle();
			$('[data-toggle="tooltip"]').tooltip();
		});
		// Add row on add button click
		$(document).on("click", ".add5", function(){
			var empty = false;
			var input = $(this).parents("tr").find('input');
			var select = $(this).parents("tr").find('select');
			input.each(function(){
				if(!$(this)[0].checkValidity()){
					$(this).addClass("error");
					$(this)[0].reportValidity();
					empty = true;
				} else{
					$(this).removeClass("error");
				}

			});
			$(this).parents("tr").find(".error").first().focus();
			if(!empty){
				select.each(function(){
					$(this).parent("td").html($(this).val());
				});
				input.each(function(){
					$(this).parent("td").html($(this).val());
				});
				$(this).parents("tr").find(".add, .edit").toggle();
				$(".new5").removeAttr("disabled");
			}
		});
		// Edit row on edit button click
		$(document).on("click", ".edit5", function(){
			$(this).parents("tr").find("td:not(:last-child)").each(function(index){
				if(index == 0)
					$(this).html('<input type="text" required class="form-control" value="' + $(this).text() + '">');
				if(index == 1)
					$(this).html('<input type="text" required class="form-control" value="' + $(this).text() + '">');
				if(index == 2)
					$(this).html('<input type="text" required class="form-control" value="' + $(this).text() + '">');
				if(index == 3)
					$(this).html('<input type="text" class="form-control" value="' + $(this).text() + '">');
				if(index == 4)
					$(this).html('<input type="number" min="0" required class="form-control" step=".1" value="' + $(this).text() + '">');
				if(index == 5)
					$(this).html('<input type="number" min="0" class="form-control" step=".1" value="' + $(this).text() + '">');
				if(index == 6)
					$(this).html('<input type="text" class="form-control" value="' + $(this).text() + '">');
			});
			$(this).parents("tr").find(".add, .edit").toggle();
			$(".new5").attr("disabled", "disabled");
		});
		// Delete row on delete button click
		$(document).on("click", ".delete5", function(){
			$(this).parents("tr").remove();
			$(".new5").removeAttr("disabled");
		});
	});
</script>

<script>

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

	var selectedId = null
	var checkedId = null
	var aggregators = <?= json_encode($aggregators ?? []) ?>;

	function showEnableButton() {
		if($("#aggregators input:checked").length){
			$('#enableAggregator').show();
			$("#aggregators input:checked").each(function() {
				checkedId = $(this).val()
			});
		}else{
			$('#enableAggregator').hide();
			checkedId = null
		}
	}

	$(function () {
		$('#aggregators').DataTable();
		showEnableButton()
	})

	$('#aggregators').on('change', 'input[type=checkbox]', function(e) {
		if(this.checked){
			$("#aggregators").find("input[type=checkbox]").not(this).prop('checked', false);
		}
		showEnableButton()
	});




	$(document).on("click", ".edit-row", function () {
		selectedId = $(this).data('id');
		$("#update-form input[name='name']").val($(this).data('name'));
		$("#update-form input[name='address']").val($(this).data('address'));
		$("#update-form input[name='email']").val($(this).data('email'));
		$("#update-form input[name='phone']").val($(this).data('phone'));

		// Load rates
		$("#rates_list tbody").children().remove();
		$.each(aggregators, function (j, it) {
			if(it.id == selectedId){
				$.each(aggregators[j].rates, function (j, r) {
					$('#rates_list').append('<tr>' +
						'<td>' + (r.country || '') + '</td>' +
						'<td>' + (r.type || '') + '</td>' +
						'<td>' + (r.method || '') + '</td>' +
						'<td>' + (r.channel || '') + '</td>' +
						'<td>' + (r.rate || 0) + '</td>' +
						'<td>' + (r.fixed_fees || '') + '</td>' +
						'<td>' + (r.fixed_fees_currency || '') + '</td>' +
						'<td>' + actions5 + '</td>' +
						'</tr>')
				});
			}
		});

		$('#editModal').modal('show');

	});

	$(document).on("click", ".delete-row", function () {
		selectedId = $(this).data('id');
		$('#delete-modal').modal('show');
	});


	$("#update-form").submit(function () {

		// Paliers
		var rates = [];

		$('#rates_list tr').has('td').each(function() {
			var arrayItem = {};
			$('td', $(this)).each(function(index, item) {
				if(index < 7){
					arrayItem[index] = $(item).html();
				}
			});
			rates.push(arrayItem);
		});

		$.ajax({
			url: '<?= base_url('PaymentController/storePaymentAggregator')?>',
			type: 'post',
			data: {
				id: selectedId,
				name: $("input[name=name]",this).val(),
				address:  $("input[name=address]",this).val(),
				email: $("input[name=email]",this).val(),
				phone: $("input[name=phone]",this).val(),
				rates: rates
			},
			dataType: 'json',
			success: function (data) {
				if(data.code === 200){
					Swal.fire({
						icon: 'success',
						title: "<?= $this->lang->line('aggregator_updated')?>",
						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();
	});

	$("#create-aggregator-form").submit(function (event) {

		$.ajax({
			url: '<?= base_url('PaymentController/storePaymentAggregator')?>',
			type: 'post',
			data: {
				name: $("input[name=name]",this).val(),
				address:  $("input[name=address]",this).val(),
				email: $("input[name=email]",this).val(),
				phone: $("input[name=phone]",this).val()
			},
			dataType: 'json',
			success: function (data) {
				if(data.code === 200){
					Swal.fire({
						icon: 'success',
						title: "<?= $this->lang->line('aggregator_created')?>",
						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();
	});

	$("#enableAggregator").click(function () {
		$.ajax({
			url: '<?= base_url('PaymentController/enableAggregator')?>',
			type: 'post',
			data: {id: checkedId},
			dataType: 'json',
			success: function (data) {
				if(data.code === 200){
					Swal.fire({
						icon: 'success',
						title: "<?= $this->lang->line('aggregator_activated')?>",
						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')?>");
			}
		});
	});



	$("#delete-btn").click(function () {
		$.ajax({
			url: '<?= base_url('PaymentController/deletePaymentAggregator')?>',
			type: 'post',
			data: {id: selectedId},
			dataType: 'json',
			success: function (data) {
				if(data.code === 200){
					Swal.fire({
						icon: 'success',
						title: "<?= $this->lang->line('aggregator_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>
