<!-- Begin Page Content -->
<div class="container-fluid">
	<div class="d-sm-flex align-items-center justify-content-between mb-4">
		<h1 class="h3 mb-0 text-gray-800"><?= $title;  ?></h1>
		<ol class="breadcrumb">
			<li class="breadcrumb-item"><a href="./">Home</a></li>
			<li class="breadcrumb-item"><a href="<?=base_url('journal');?>">Journal</a></li>
			<li class="breadcrumb-item active" aria-current="page"><?= $title;  ?></li>
		</ol>
	</div>
	
	<div class="card border-bottom-primary shadow mb-4">
		<div class="row" id="tambah-data-transaksi">
			<div class="col-sm">
	            <div class="card-header py-3">
	            	<div class="row">
	            		<div class="col-sm">
				            <h6 class="m-0 font-weight-bold text-primary mt-2">Form Tambah Data Transaksi</h6>
						</div>
					</div>
				</div>
				<div class="card-body">
					<form autocomplete="off" class="form-add" id="form-add">
						<input type="text" class="form-control" id="idUser" name="idUser" value="<?= $user['id_user']; ?>" hidden>
						<div class="row">
							<div class="col-sm">
								<div class="form-group row">
									<label for="tglTransaksi" class="col-sm-2 col-form-label">Tanggal Transaksi *</label>
									<div class="col-sm-10">
										<input type="date" class="form-control" id="tglTransaksi" name="tglTransaksi" value="<?= $date; ?>" required>
									</div>
								</div>
								<div class="form-group row">
									<label for="noTransaksi" class="col-sm-2 col-form-label">Nomor Transaksi *</label>
									<div class="col-sm-10">
										<input type="text" class="form-control" id="noTransaksi" name="noTransaksi" placeholder="No. Transaksi" value="<?= $no; ?><?= sprintf("%04s", $no_trans);?>">
									</div>
								</div>
								<div class="form-group row">
									<label for="keterangan" class="col-sm-2 col-form-label">Keterangan *</label>
									<div class="col-sm-10">
										<input type="text" class="form-control" id="keterangan" name="keterangan" placeholder="Keterangan" autocomplete="off" required>
									</div>
								</div>
								<div class="form-group row">
									<label for="keterangan" class="col-sm-2 col-form-label">
										Upload Bukti (Opsional) <br>
										<small class="text-primary">*format : pdf/jpg/jpeg/png. maksimal: 5mb</small>
									</label>
									<div class="col-sm-10">
										<div class="custom-file">
											<input type="file" class="custom-file-input col-sm-12" id="bukti" name="bukti">
											<label class="custom-file-label" for="bukti">Choose file</label>
										</div>
									</div>
								</div>
							</div>
						</div>
						<div class="row">
							<div class="table-responsive">
								<table class="table table-sm table-hover table-bordered">
									<thead>
										<tr>
											<th scope="col">Nomor Akun</th>
											<th scope="col">Nama Akun</th>
											<th scope="col">Nominal</th>
											<th scope="col">Perkiraan</th>
											<th class="text-center"><a href="#" class="text-success addsection" id="tambah-tab-input"><i class="fa fa-fw fa-plus"></i></a></th>
										</tr>
									</thead>
									<tbody id="insert-form">
										<tr>
											<td>
												<select type="text" class="form-control bootstrap-select" id="idAkun" name="idAkun[]" title="Nomor Akun" data-container="body" data-live-search="true" required>
													<?php foreach ($akun as $ak) : ?>
													<option value="<?= $ak['id_akun']; ?>"><?= $ak['kel_akun']; ?>-<?= $ak['noakun']; ?></option>
													<?php endforeach; ?>
												</select>
											</td>
											<td>
												<select type="text" class="form-control bootstrap-select" id="namaAkunJurnal" name="namaAkun[]" data-container="body" title="Pilih Nama Akun" data-live-search="true" required>
													<?php foreach ($akun as $ak) : ?>
													<option value="<?= $ak['nama']; ?>"><?= $ak['nama']; ?></option>
													<?php endforeach; ?>
												</select>
											</td>
											<td>
												<input type="text" class="form-control" id="nominalJurnal" name="nominal[]" placeholder="Nominal" autocomplete="off" required>
											</td>
											<td>
												<select type="text" class="form-control bootstrap-select" id="perkiraanJurnal" name="perkiraan[]" data-container="body" data-width="100%" title="Select perkiraan" required>
													<?php foreach ($perkiraan as $p) : ?>
													<option value="<?= $p['id_perkiraan']; ?>"><?= $p['nama']; ?></option>
													<?php endforeach; ?>
												</select>
											</td>
											<td class="text-center"></td>
										</tr>
										<tr>
											<td>
												<select type="text" class="form-control bootstrap-select" id="idAkun" name="idAkun[]" title="Nomor Akun"  data-container="body" data-live-search="true" required>
													<?php foreach ($akun as $ak) : ?>
													<option value="<?= $ak['id_akun']; ?>"><?= $ak['kel_akun']; ?>-<?= $ak['noakun']; ?></option>
													<?php endforeach; ?>
												</select>
											</td>
											<td>
												<select type="text" class="form-control bootstrap-select" id="namaAkunJurnal" name="namaAkun[]" data-container="body" title="Pilih Nama Akun" data-live-search="true" required>
													<?php foreach ($akun as $ak) : ?>
													<option value="<?= $ak['nama']; ?>"><?= $ak['nama']; ?></option>
													<?php endforeach; ?>
												</select>
											</td>
											<td>
												<input type="text" class="form-control" id="nominalJurnal" name="nominal[]" placeholder="Nominal" autocomplete="off" required>
											</td>
											<td>
												<select type="text" class="form-control bootstrap-select" id="perkiraanJurnal" name="perkiraan[]" data-container="body" data-width="100%" title="Select perkiraan" required>
													<?php foreach ($perkiraan as $p) : ?>
													<option value="<?= $p['id_perkiraan']; ?>"><?= $p['nama']; ?></option>
													<?php endforeach; ?>
												</select>
											</td>
											<td class="text-center"></td>
										</tr>
									</tbody>
								</table>
							</div>
						</div>
						<div class="row mt-2">
							<div class="col-sm text-right">
								<a href="<?=base_url('journal');?>" class="btn btn-danger btn-sm">
									<i class="fa fa-fw fa-arrow-left"></i> Kembali
								</a>
								<button type="button" class="btn btn-primary btn-sm simpan-journal">
									<span class="icon text-white-50">
										<i class="fa fa-fw fa-save"></i>
									</span>
									<span class="text">Simpan</span>
								</button>
							</div>
						</div>
					</form>
				</div>
			</div>
		</div>
	</div>
	
</div>
<!-- /.container-fluid -->

<script>
	var auto_name = base_url+"journal/auto_name";
	var auto_account_id = base_url+"journal/auto_account_id";
	
	$(document).on('click','.simpan-journal',function(){
		$("#form-add").submit();
	});
	$("#form-add").submit(function (e) {
		e.preventDefault();
		
		if($('#tglTransaksi').val()==''){
			showNotif('bottom-right','Peringatan!!!','tgl Transaksi harus diisi','warning');
			$('#tglTransaksi').focus();
			return;
		}
		if($('#noTransaksi').val()==''){
			showNotif('bottom-right','Peringatan!!!','noTransaksi harus diisi','warning');
			$('#noTransaksi').focus();
			return;
		}
		if($('#keterangan').val()==''){
			showNotif('bottom-right','Peringatan!!!','keterangan harus diisi','warning');
			$('#keterangan').focus();
			return;
		}
		
		var formData = new FormData(this);
		if(!formData.has("nominal[]"))
		{
			notify('Peringatan!','Nominal masih kosong','warning');
			return;
		}
		
		var contentType ="application/x-www-form-urlencoded; charset=utf-8";
		
		if(window.XDomainRequest) contentType = "text/plain";
		$.ajax({
			xhr: function() {
				var xhr = new window.XMLHttpRequest();         
				xhr.upload.addEventListener("progress", function(element) {
					if (element.lengthComputable) {
						var percentComplete = ((element.loaded / element.total) * 100);
						$("#file-progress-bar").width(percentComplete + '%');
						$("#file-progress-bar").html(percentComplete+'%');
					}
				}, false);
				return xhr;
			},
			url: base_url +'journal/save_journal',
			type: 'POST',
			data: formData,
			dataType: 'json',
			contentType:contentType,
			contentType: false,  
			processData:false,
			cache: false,
			beforeSend: function(){
				$("body").loading({zIndex:1051,message:'saving data'});
				// $("#file-progress-bar").width('0%');
			},
			success:function(data){
				if(data.status==true)
				{
					showNotif('bottom-right','Simpan data',data.msg,'success');
					// Simulate a mouse click:
					window.location.href = base_url+"journal";
					}else{
					showNotif('bottom-right','Peringatan!!!',data.msg,'warning');
				}
				console.log(data)
				$("body").loading('stop');
			},
			error : function(res, status, httpMessage) {
				$('body').loading('stop');
				console.log(res.status)
				if(res.status==401){
					// sweet_login(httpMessage,'warning',base_url);
					}else{
					// sweet("Peringatan!!!", httpMessage, "warning", "warning");
				}			
			}
		})
		return false;
	});
	$(document).on("keyup", "#nominalJurnal", function() {
		//Menangani Input otomatis Format Ribuan
		let rupiah = $(this).val();
		
		$(this).val(formatRupiah(rupiah, 'Rp. '));
		
		/* Fungsi formatRupiah */
		function formatRupiah(angka, prefix){
			let number_string = angka.replace(/[^,\d]/g, '').toString(),
			split   		= number_string.split(','),
			sisa     		= split[0].length % 3,
			rupiah     		= split[0].substr(0, sisa),
			ribuan     		= split[0].substr(sisa).match(/\d{3}/gi);
			
			// tambahkan titik jika yang di input sudah menjadi angka ribuan
			if(ribuan){
				separator = sisa ? '.' : '';
				rupiah += separator + ribuan.join('.');
			}
			
			rupiah = split[1] != undefined ? rupiah + ',' + split[1] : rupiah;
			return prefix == undefined ? rupiah : (rupiah ? 'Rp. ' + rupiah : '');
		}
	});
	
	
	// Menangani tambah data transakdi +
	let parent = $("#tambah-data-transaksi");
	let form = parent.find($("form"));
	let table = form.find($("table"));
	let index = 1;
	
	let akun = <?php echo json_encode( $akun ) ?>;
	let perkiraan = <?php echo json_encode( $perkiraan ) ?>;
	
	table.find($("#tambah-tab-input")).click(function() {
		
		let optionAkun = '';
		let optionNamaAkun = '';
		let optionPerkiraan = '';
		$.each( akun, function( index, row ) {
			optionAkun += `
		<option value="${row.id_akun}">${row.kel_akun}-${row.noakun}</option>
		`;
		});
		$.each( akun, function( index, row ) {
		optionNamaAkun += `
		<option value="${row.nama}">${row.nama}</option>
		`;
		});
		$.each( perkiraan, function( index, row ) {
		optionPerkiraan += `
		<option value="${row.id_perkiraan}">${row.nama}</option>
		`;
		});
		
		let el = `<tr id="data${index}">
			<td>
				<select type="text" class="form-control bootstrap-select" id="idAkun" name="idAkun[]" title="Nomor Akun" data-container="body" data-live-search="true" required>
					${optionAkun}
				</select>
			</td>
			<td>
				<select type="text" class="form-control bootstrap-select" id="namaAkunJurnal" name="namaAkun[]" data-container="body" title="Pilih Nama Akun" data-live-search="true" required>
					${optionNamaAkun}
				</select>
			</td>
			<td>
				<input type="text" class="form-control" id="nominalJurnal" name="nominal[]" placeholder="Nominal" autocomplete="off" required>
			</td>
			<td>
				<select type="text" class="form-control bootstrap-select" id="perkiraanJurnal" name="perkiraan[]"  data-container="body" data-width="100%" title="Select perkiraan" required>
					${optionPerkiraan}
				</select>
			</td>
			<td class="text-center">
				<a href="#" data-position="${index}" id="hapus-tab-input" class="text-danger"><i class="fa fa-fw fa-times"></i></a>
			</td>
		</tr>`;
		
		table.find($("#insert-form")).append(el);
		
		index++;
		
		$(document).ready(function(){
		$(".bootstrap-select").selectpicker();
		
		$("select[name='idAkun[]']").change(function(){
		let value = $(this).val();
		
		let select = $(this).parent();
		let td = select.parent();
		let parent = td.parent();
		
		$.ajax({
		url: auto_name,
		method : "POST",
		data : {id: value},
		async : true,
		dataType : 'json',
		success: function(data){
		if(!data){
		parent.find("#idAkun").val('')
		parent.find("#namaAkunJurnal").val('')
		parent.find("#nominalJurnal").val('')
		parent.find("#perkiraanJurnal").val('')
		} else {
		parent.find("#namaAkunJurnal option[value='" + data.nama + "']").prop("selected", true),
		parent.find("#perkiraanJurnal option[value='" + data.id_perkiraan + "']").prop("selected", true),
		parent.find("#namaAkunJurnal").selectpicker('refresh'),
		parent.find("#perkiraanJurnal").selectpicker('refresh');
		}
		}
		});
		});
		
		$("select[name='namaAkun[]']").change(function(){
		let value = $(this).val();
		
		let select = $(this).parent();
		let td = select.parent();
		let parent = td.parent();
		
		$.ajax({
		url: auto_account_id,
		method : "POST",
		data : {name: value},
		async : true,
		dataType : 'json',
		success: function(data){
		if(!data){
		parent.find("#idAkun").val('')
		parent.find("#namaAkunJurnal").val('')
		parent.find("#nominalJurnal").val('')
		parent.find("#perkiraanJurnal").val('')
		} else {
		parent.find("#idAkun option[value='" + data + "']").prop("selected", true).trigger('change'),
		parent.find("#perkiraanJurnal option[value='" + data.id_perkiraan + "']").prop("selected", true),
		parent.find("#idAkun").selectpicker('refresh'),
		parent.find("#perkiraanJurnal").selectpicker('refresh');
		}
		}
		});
		});
		
		});
		
		$(document).on("keyup", "#nominalJurnal", function() {
		//Menangani Input otomatis Format Ribuan
		let rupiah = $(this).val();
		
		$(this).val(formatRupiah(rupiah, 'Rp. '));
		
		/* Fungsi formatRupiah */
		function formatRupiah(angka, prefix){
		let number_string = angka.replace(/[^,\d]/g, '').toString(),
		split   		= number_string.split(','),
		sisa     		= split[0].length % 3,
		rupiah     		= split[0].substr(0, sisa),
		ribuan     		= split[0].substr(sisa).match(/\d{3}/gi);
		
		// tambahkan titik jika yang di input sudah menjadi angka ribuan
		if(ribuan){
		separator = sisa ? '.' : '';
		rupiah += separator + ribuan.join('.');
		}
		
		rupiah = split[1] != undefined ? rupiah + ',' + split[1] : rupiah;
		return prefix == undefined ? rupiah : (rupiah ? 'Rp. ' + rupiah : '');
		}
	    });
		})
		
		// Menangani hapus row
		$(document).on("click", "#hapus-tab-input", function() {
        let id = $(this).attr("data-position");
		table.find($("tr#data"+id)).remove();
		});
		
		// menangani otomatis nomor akun dan nama akun
		$(document).ready(function(){
		$(".bootstrap-select").selectpicker();
		
		$("select[name='idAkun[]']").change(function(){
		let value = $(this).val();
		
		let select = $(this).parent();
		let td = select.parent();
		let parent = td.parent();
		
		$.ajax({
		url: auto_name,
		method : "POST",
		data : {id: value},
		async : true,
		dataType : 'json',
		success: function(data){
		if(!data){
		parent.find("#idAkun").val('')
		parent.find("#namaAkunJurnal").val('')
		parent.find("#nominalJurnal").val('')
		parent.find("#perkiraanJurnal").val('')
		} else {
		parent.find("#namaAkunJurnal option[value='" + data.nama + "']").prop("selected", true),
		parent.find("#perkiraanJurnal option[value='" + data.id_perkiraan + "']").prop("selected", true),
		parent.find("#namaAkunJurnal").selectpicker('refresh'),
		parent.find("#perkiraanJurnal").selectpicker('refresh');
		}
		}
		});
		});
		
		$("select[name='namaAkun[]']").change(function(){
		let value = $(this).val();
		
		let select = $(this).parent();
		let td = select.parent();
		let parent = td.parent();
		
		$.ajax({
		url: auto_account_id,
		method : "POST",
		data : {name: value},
		async : true,
		dataType : 'json',
		success: function(data){
		if(!data){
		parent.find("#idAkun").val('')
		parent.find("#namaAkunJurnal").val('')
		parent.find("#nominalJurnal").val('')
		parent.find("#perkiraanJurnal").val('')
		} else {
		parent.find("#idAkun option[value='" + data + "']").prop("selected", true).trigger('change'),
		parent.find("#perkiraanJurnal option[value='" + data.id_perkiraan + "']").prop("selected", true),
		parent.find("#idAkun").selectpicker('refresh'),
		parent.find("#perkiraanJurnal").selectpicker('refresh');
		}
		}
		});
		});
		
		
		});
		
		
	</script>												