<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('customers_accounts_configuration')?>
		</h1>
	</section>

	<?php
		use Brick\Money\Context\AutoContext;
		use Brick\Money\Money;
		$context = new AutoContext();
	?>

	<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( 'customer_account_types') ?></h3>
					</div>
					<div class="box-body" style="overflow-x:auto;">
						<table id="customer_account_types" class="table table-bordered table-striped">
							<thead>
							<tr>
								<th align='center'>#</th>
								<th><?= $this->lang->line('Nom'); ?></th>
								<th><?= $this->lang->line('product'); ?></th>
								<th>Description</th>
								<th>Parent</th>
								<th><?= $this->lang->line('opening_amount'); ?></th>
								<th><?= $this->lang->line('payment_period_days'); ?></th>
								<th>Action</th>
							</tr>
							</thead>
							<tbody>
								<?php foreach($types ?? [] as $i => $row) { ?>
									<tr>
									    <td><?=$i+1?></td>
										<td><?=$row->name?></td>
										<td><?=$row->product?></td>
										<td><?=$row->description?></td>
										<td><?=$row->parent?></td>
										<td><?= empty($row->opening_amount) ?  '' : Money::of(round($row->opening_amount, 2), $currency_code ?? 'XAF', $context)->formatTo('fr_FR')?></td>
										<td><?= $row->opening_amount_payment_period_days?></td>
										<td>
											<button class="btn btn-success edit-doc" data-id="<?=$row->id?>" data-name="<?=$row->name?>"  data-description="<?=$row->description?>"data-product="<?= $row->product ?>"
													data-parent_id="<?=$row->parent_id?>"  data-opening_amount="<?=$row->opening_amount?>" data-opening_amount_payment_period_days="<?=$row->opening_amount_payment_period_days?>">
												<i class="fa fa-edit"></i>
											</button>
											<button data-toggle="modal" class="btn btn-danger delete-doc" data-id="<?=$row->id?>" >
												<i class="fa fa-trash"></i>
											</button>
										</td>
									</tr>
								<?php } ?>
							</tbody>
						</table>
					</div>
				</div>
			</div>
				<div class="col-xs-4">
					<div class="box">
						<div class="box-header">
							<h3 class="box-title"><?= $this->lang->line('add_customer_account_type'); ?></h3>
						</div>
						<div class="box-body">
							<form id="create-form" class="bottom-75 center-block">
								<div class="form-group">
									<label for="name"><?= $this->lang->line('Nom'); ?></label>
									<input type="text" class="form-control input-lg" name="name" id="name" required>
								</div>
								<div class="form-group">
									<label for="product"><?= $this->lang->line('product'); ?></label>
									<input type="text" class="form-control input-lg" name="product" id="product" required>
								</div>								
								<div class="form-group">
									<label for="description">Description</label>
									<textarea class="form-control input-lg" name="description" id="description"></textarea>
								</div>
								<div class="form-group">
									<label for="opening_amount"><?= $this->lang->line('opening_amount'); ?></label>
									<input type="number" value="" class="form-control input-lg" name="opening_amount" id="opening_amount">
								</div>
								<div class="form-group">
									<label for="opening_amount_payment_period_days_u"><?= $this->lang->line('payment_period_days'); ?></label>
									<input type="number" value="" class="form-control input-lg" name="opening_amount_payment_period_days" id="opening_amount_payment_period_days_u">
								</div>
								<div class="form-group">
									<label  class="col-form-label">Parent</label>
									<select class="form-control input-lg" name="parent_id" >
										<option value="0"><?=$this->lang->line('no_parent')?></option>
										<?php foreach ($types ?? [] as $value) { ?>
											<option value="<?=$value->id?>"> <?=$value->name?> </option>
										<?php } ?>
									</select>
								</div>
								<div class="form-group">
									<input type="submit"
										   value="<?= $this->lang->line('save'); ?>"
										   class="btn btn-primary">
								</div>
							</form>
						</div>
					</div>
				</div>
		</div>
		<div class="modal fade" id="editModal">
			<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('Mettre à jour des informations'); ?></h4>
					</div>
					<div class="modal-body">
						<form id="update-form" class="bottom-75 center-block">
							<div class="form-group">
								<label for="name_u"><?= $this->lang->line('Nom'); ?></label>
								<input type="text" class="form-control input-lg" name="name" id="name_u" required>
							</div>
							<div class="form-group">
								<label for="product_u"><?= $this->lang->line('product'); ?></label>
								<input type="text" class="form-control input-lg" name="product" id="product_u" required>
							</div>							
							<div class="form-group">
								<label for="description_u">Description</label>
								<textarea class="form-control input-lg" name="description" id="description_u"></textarea>
							</div>
							<div class="form-group">
								<label for="opening_amount_u"><?= $this->lang->line('opening_amount'); ?></label>
								<input type="number" value="" class="form-control input-lg" name="opening_amount" id="opening_amount_u">
							</div>
							<div class="form-group">
								<label for="opening_amount_payment_period_days_u"><?= $this->lang->line('payment_period_days'); ?></label>
								<input type="number" value="" class="form-control input-lg" name="opening_amount_payment_period_days" id="opening_amount_payment_period_days_u">
							</div>
							<div class="form-group">
								<label  class="col-form-label">Parent</label>
								<select class="form-control input-lg" name="parent_id" ></select>
							</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('documents_list') ; ?></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_document') ; ?></button>
										</div>
									</div>
								</div>
								<table id="documents_list" class="table table-bordered">
									<thead>
									<tr>
										<th><?= $this->lang->line('Nom') ; ?> </th>
										<th>Description</th>
										<th>Actions</th>
									</tr>
									</thead>
									<tbody>
									</tbody>
								</table>
							</div>
							<div class="form-group">
								<button type="submit" class="btn btn-primary">
									<?= $this->lang->line('save'); ?>
								</button>
								<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',['title' => $this->lang->line('delete_customer_account_type')]) ?>
		<?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 = $("#documents_list tbody tr:last-child").index();
			var row = "<tr> <td><input type='text' required class='form-control' name='name'></td> " +
				"<td><input type='text' class='form-control' name='description'></td>" +
				"<td>" + actions5 + "</td>" +
				"</tr>";
			$("#documents_list").append(row);
			$("#documents_list tbody tr").eq(index + 1).find(".add, .edit").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() + '">');
			});
			$(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';

	$(function () {
		$('#customer_account_types').DataTable({
			"language": {
				"processing": "<?= $this->lang->line('loading') ?>",
				"emptyTable" : "<?= $this->lang->line('no_customer_account_type') ?>"
			},
			dom: 'Bfrtip',
		});
	})

	var networkId = <?= $network_id ?>;
	var selectedId = null
	var types = <?= json_encode($types ?? []) ?>;

	$(document).on("click", ".edit-doc", function () {
		selectedId = $(this).data('id');
		$("#update-form input[name='name']").val($(this).data('name'));
		$("#update-form input[name='product']").val($(this).data('product'));
		$("#update-form textarea[name='description']").val($(this).data('description'));
		$("#update-form input[name='opening_amount']").val($(this).data('opening_amount'));
		$("#update-form input[name='opening_amount_payment_period_days']").val($(this).data('opening_amount_payment_period_days'));

		$("#update-form select[name='parent_id']").empty().append("<option value='0'>"+ "<?= $this->lang->line('no_parent')?>" + "</option>");
		$.each(types, function (j, it) {
			$("#update-form select[name='parent_id']").append(`<option value='${it.id}'>${it.name}</option>`);
		});
		$(`#update-form select[name='parent_id'] option[value='${selectedId}']`).remove();
		$("#update-form select[name='parent_id']").val($(this).data('parent_id'));

		// Load documents
		$("#documents_list tbody").children().remove();
		$.each(types, function (j, it) {
			if(it.id == selectedId){
				$.each(types[j].documents, function (j, doc) {
					$('#documents_list').append('<tr>' +
						'<td>' + (doc.name || '') + '</td>' +
						'<td>' + (doc.description || '') + '</td>' +
						'<td>' + actions5 + '</td>' +
						'</tr>')
				});
			}
		});

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

	});

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

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

		let openingAmount = $("input[name=opening_amount]",this).val();
		let paymentPeriod = $("input[name=opening_amount_payment_period_days]",this).val();

		if (openingAmount && !paymentPeriod){
			toastr.warning("<?= $this->lang->line('required_payment_period_days')?>" , "<?= $this->lang->line('request_error')?>");
		}else {
			// Paliers
			var documents = [];

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

			$.ajax({
				url: '<?= base_url('Hyperviseur_dash/storeCustomerAccountType')?>',
				type: 'post',
				data: {
					id: selectedId,
					network_id : networkId,
					name:  $("input[name=name]",this).val(),
					product:  $("input[name=product]",this).val(),
					description:  $("textarea[name=description]",this).val(),
					opening_amount:  $("input[name=opening_amount]",this).val(),
					opening_amount_payment_period_days: $("input[name=opening_amount_payment_period_days]", this).val(),
					parent_id : $("select[name=parent_id]",this).val(),
					documents: documents
				},
				dataType: 'json',
				success: function (data) {
					if(data.code === 200){
						Swal.fire({
							icon: 'success',
							title: "<?= $this->lang->line('customer_account_type_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-form").submit(function (event) {

		let openingAmount = $("input[name=opening_amount]",this).val();
		let paymentPeriod = $("input[name=opening_amount_payment_period_days]",this).val();
		if (openingAmount && !paymentPeriod){
			toastr.warning("<?= $this->lang->line('required_payment_period_days')?>" , "<?= $this->lang->line('request_error')?>");
		}else {
			$.ajax({
				url: '<?= base_url('Hyperviseur_dash/storeCustomerAccountType')?>',
				type: 'post',
				data: {
					network_id: networkId,
					name: $("input[name=name]", this).val(),
					product: $("input[name=product]", this).val(),
					description: $("textarea[name=description]", this).val(),
					opening_amount: $("input[name=opening_amount]", this).val(),
					opening_amount_payment_period_days: $("input[name=opening_amount_payment_period_days]", this).val(),
					parent_id: $("select[name=parent_id]", this).val()
				},
				dataType: 'json',
				success: function (data) {
					if (data.code === 200) {
						Swal.fire({
							icon: 'success',
							title: "<?= $this->lang->line('customer_account_type_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();
	});


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