{% extends '../template.html' %}
{% block style %}
	<link href="{% nav public %}css/infomodal.css" rel="stylesheet">
{% endblock %}
{% block subcontent %}
<!-- iModal -->
<div id="infoModal" class="imodal" style="display:none">
  <!-- iModal content -->
	<div class="imodal-content">
		<span class="close">&times;</span>
		<div class="detail-content">
			<input class="idk" style="display:none" value="0"></input>
			<h3 style="margin:5px 0px;">-- Data Pembeli --</h3>
			<table>
				<tr>
					<td>Nama</td>
					<td>:</td>
					<td class="nama"></td>
				</tr>
				<tr>
					<td>Golongan</td>
					<td>:</td>
					<td class="gol"></td>
				</tr>
			</table>
			<h3 style="margin:5px 0px;">-- Obat --</h3>
			<div class="obat">
				<table class="data" cellpadding="0" cellspacing="0" border="0">
					<tr>
						<th style="width:300px">Nama</th>
						<th style="width:30px">Jumlah</th>
						<th style="width:80px">Total Harga</th>
					</tr>
					<tbody class="tabelo"></tbody>
				</table>
				<label class="loadingo"><i>loading...</i></label>
			</div>
			<h3 style="margin:5px 0px;">-- Biaya Lain --</h3>
			<div class="biaya">
				<div class="clearfix"></div>
				<div class="plus btn-success"><i class="fas fa-plus"></i></div>
			</div>
			<br/><br/><br/>
			<table>
				<tr>
					<td style="width:360px;"><h2>Total </h2></td>
					<td style="width:150px;"><h2>Rp  <span class="total_sum">0</span></h2></td>
				</tr>
				<tr>
					<td colspan=2><b>Metode Pembayaran :</b></td>
				</tr>
				<tr>
					<td>Cash</td>
					<td>
						Rp. <input class="pembayaran cash" style="width:70px;text-align:right" onkeyup="isiOtomatis('cash');"/>
						<span class="isi btn btn-default">isi</span>
					</td>
				</tr>
				<tr>
					<td>Transfer</td>
					<td>
						Rp. <input class="pembayaran transfer" style="width:70px;text-align:right" onkeyup="isiOtomatis('transfer');"/>
						<span class="isi btn btn-default">isi</span>
					</td>
				</tr>
				<tr>
					<td>Sisa</td>
					<td>
						Rp. <input class="pembayaran hutang" style="width:70px;text-align:right" onkeyup="isiOtomatis('hutang');"/>
						<span class="isi btn btn-default">isi</span>
					</td>
				</tr>
			</table>
			<br/><br/><br/>
			<button class="submit btn btn-primary" type="submit">Simpan</button>&nbsp
			<button class="cetak btn btn-warning" type="submit">Cetak</button>&nbsp
			<button class="tutup btn btn-default" style="width:70px;">Tutup</button>
			<br/><br/>
		</div>
	</div>
</div>
<div class="biaya_item_master" style="display:none">
	<div class="option">
		<div class="minus btn-danger"><i class="fas fa-minus"></i></div>
	</div>
	<table style="margin-left:30px">
		<tr>
			<td style="width:330px">
				<select class="menu1" name="biaya[]">
				{% for b in biaya %}
					<option gol="{{b.id_golongan}}" harga="{{b.harga}}" value="{{b.id}}">{{b.nama | safe}}</option>
				{% endfor %}
				</select>
			</td>
			<td style="width:150px">
				Rp. <input class="harga" value="0" name="harga[]" type="text" style="text-align:right;width:80px;" onkeyup='currency(this);'/>
			</td>
		</tr>
	</table>
</div>
<h2>List Penjualan: <input type="text" id="date_picker" value="{{tgl}}">
	Cari: <input type="text" id="find"/>
</h2>

{% if data.length > 0 %}
<table class="orderhistory data">
	<tr>
		<th>Tanggal</th>
		<th>Pembeli</th>
		<th>Golongan</th>
		<th style="width:80px">Status</th>
		<th></th>
	</tr>
	{% for row in data %}
		<tr class="order_histori_{{row.id}} orders" valign="top">
			<td>{{row.tgl}}</td>
			<td>{{row.nama}}</abbr></td>
			<td>{{row.golongan}}</td>
			<td class="status"><b>{%if row.status == 'bayar'%}<button class="btn btn-primary bayar" idk="{{row.id}}">Bayar</button>{%else%}{{row.status}}{%endif%}</b></td>
		</tr>
	{% endfor %}
</table>
<div id="current_time" year="{{current.year}}" month="{{current.mon}}" day="{{current.mday}}" hour="{{current.hours}}" minute="{{current.minutes}}" second="{{current.seconds}}"></div>
{% else %}
	- Penjualan Masih Kosong -<br/><br/>
{% endif %}

{% endblock %}
{% block script %}
<script type="text/javascript" src="{% nav public %}js/glDatePicker.min.js"></script>
<script type="text/javascript" src="{% nav public %}js/infomodal.js"></script>
<script type="text/javascript">
	var totalT = 0;
	var totalO = 0;
	$(document).ready(function() {
		menuSelected("mAdministrasi","smPenjualan");
		$('#find').keyup(function() {
			$this = $(this);
			$('.orders').hide();
			if ($this.val().trim() != '') {
				$('.orders').each(function() {
					$va = $(this).find('td');
					if ((
						$va.eq(2).text().toLowerCase().indexOf($this.val().toLowerCase()) >= 0 || 
						$va.eq(3).text().toLowerCase().indexOf($this.val().toLowerCase()) >= 0)
					) {
						console.debug($va.eq(2).text().toLowerCase().indexOf($this.val().toLowerCase()));
						$(this).show();
					}
				});
			} else {
				$('.orders').show();
			}
		});
		$('#date_picker').glDatePicker({
			cssName: "android",
			selectedDate:new Date("{{tgl_js}}"),
			startDate: new Date("{{tgl_js}}"),
		    allowOld: true,
			onChange: function(target, newDate)
				{
					var month= ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Des"];
					target.val
					(
						newDate.getDate()  + "-" +
						month[newDate.getMonth()] + "-" +
						newDate.getFullYear() 
					);
					
					location.href = "{% nav registrasi_administrasi_penjualan %}?tgl=" + newDate.getDate()  + "-" + (newDate.getMonth() + 1) + "-" + newDate.getFullYear();
				}
		});
		$('.bayar').on('click', function(){
			$('#infoModal').show();
			$('.loadingo').show();
			$('.tabelo').hide();
			$('.tabelo').empty();
			$('.biaya_item').each(function() {
				$(this).remove();
			});
			$('.total_sum').text('0');
			var idk = $(this).attr('idk');
			$('.idk').val(idk);
			$.ajax({
				type: "GET",
				url: "{% nav registrasi_administrasi_penjualan_getbiaya %}?idk="+idk,
				dataType: "json",
				success: function (data) {
					loadData(data);
				}
			});
		});
		$('.plus').on('click',function() {
			newItemB();
			edited(1);
		});
		$('.minus').on('click',function() {
			$(this).parent().parent().remove();
			edited(1);
		});
		$('.menu1').on('change',function() {
			$menu = $(this).parent().parent();
			resetHarga($menu.find('.harga'));
			edited(1);
		});
		$('.pembayaran').on('change',function() {
			edited(1);
		});
		$('.isi').on('click',function() {
			$('.cash').val(0);
			$('.transfer').val(0);
			$('.hutang').val(0);
			$(this).parent().find('.pembayaran').val($('.total_sum').text());
			edited(1);
		});
		$('.submit').on('click',function() {
			var totalBayar = $('.cash').val().replace(/[^,\d]/g, '')*1 + $('.transfer').val().replace(/[^,\d]/g, '')*1 + $('.hutang').val().replace(/[^,\d]/g, '')*1;
			var totalTagihan = $('.total_sum').text().replace(/[^,\d]/g, '')*1;
			if (totalBayar != totalTagihan) {
				alert("Total tagihan dan Pembayaran tidak sama");
				return false;
			}
			var arridb = [];
			var arrharga = [];
			$('.biaya_item').each(function() {
				arridb.push($(this).find('.menu1').val());
				arrharga.push($(this).find('.harga').val());
			});
			var arrbayar = $.map($('.pembayaran'), function (el) { return el.value; });
			$.post(		// Simpan data biaya
				'{% nav registrasi_administrasi_penjualan_simpanbiaya %}',
				{ idk:$('.idk').val(), idb:arridb, harga:arrharga, pembayaran:arrbayar, totalObat:totalO },
				alert("Data berhasil disimpan")
			);
			edited(0);
		});
		$('.tutup').on('click',function() {
			$('#infoModal').hide();
		});
		$('.harga').on('keyup',function() {
			edited(1);
		});
		$('.cetak').on('click',function() {
			$('#print').load("{% nav registrasi_administrasi_penjualan_struk %}?idk="+$('.idk').val(),function(){window.print()});
			<!-- window.open("{% nav registrasi_administrasi_penjualan_struk %}?idk="+$(".idk").val(),"struk"); -->
		});
	});
	function loadData(d) {
		$('.nama').text(d.pembeli.nama);
		$('.gol').text(d.pembeli.golongan);
		totalO = 0;
		$.each(d.obat,function() {
			totalharga = this.harga * this.jumlah;
			row = "<tr><td>"+this.nama+"</td><td style='text-align:center'>"+this.jumlah+"</td><td style='text-align:right;padding-right:20px'>"+totalharga.formatMoney(0,',','.')+"</td></tr>";
			$('.tabelo').append(row);
			totalO += totalharga;
		});
		if (d.biaya != null) {
			$.each(d.biaya,function(){
				newItemB();
			});
			var key = 0;
			$('.biaya_item').each(function() {
				$(this).find('.menu1').val(d.biaya[key].id_biaya);
				$(this).find('.harga').val(d.biaya[key].harga);
				key += 1;
			});
		}
		if (d.pembayaran.cash == 0 && d.pembayaran.transfer == 0 && d.pembayaran.hutang == 0) {
			edited(1);
			$('.hutang').val($('.total_sum').text());
		} else {
			edited(0);
			$('.hutang').val(d.pembayaran.hutang);
			hitungTotal();
		}
		$('.cash').val(d.pembayaran.cash);
		$('.transfer').val(d.pembayaran.transfer);
		
		$('.loadingo').hide();
		$('.tabelo').show();
	}
	function hitungTotal() {
		var total = 0;
		$('.harga').each(function() {
			total += $(this).val().replace(/[^,\d]/g, '')*1;
		});
		total = total + totalO;
		$('.total_sum').text(total.formatMoney(0,',','.'));
	}
	function isiOtomatis(tipe) {
		currency($('.'+tipe).get(0));
		cash = $('.cash').val().replace(/[^,\d]/g, '')*1;
		transfer = $('.transfer').val().replace(/[^,\d]/g, '')*1;
		hutang = $('.hutang').val().replace(/[^,\d]/g, '')*1;
		total = $('.total_sum').text().replace(/[^,\d]/g, '')*1;
		switch (tipe) {
			case "cash":
				if (cash > total) {
					cash = total;
					transfer = 0;
					hutang = 0;
				} else if (cash + transfer + hutang > total) {
					lebih = cash + transfer + hutang - total;
					if (hutang >= lebih) {
						hutang -= lebih;
					} else {
						lebih -= hutang;
						hutang = 0;
						transfer -= lebih;
					}					
				} else {
					sisa = total - cash - transfer - hutang;
					hutang += sisa;
				}
				break;
			case "transfer":
				if (transfer > total) {
					transfer = total;
					cash = 0;
					hutang = 0;
				} else if (cash + transfer + hutang > total) {
					lebih = cash + transfer + hutang - total;
					if (hutang >= lebih) {
						hutang -= lebih;
					} else {
						lebih -= hutang;
						hutang = 0;
						cash -= lebih;
					}					
				} else {
					sisa = total - cash - transfer - hutang;
					hutang += sisa;
				}
				break;
			case "hutang":
				if (hutang > total) {
					hutang = total;
					transfer = 0;
					cash = 0;
				} else if (cash + transfer + hutang > total) {
					lebih = cash + transfer + hutang - total;
					if (transfer >= lebih) {
						transfer -= lebih;
					} else {
						lebih -= transfer;
						transfer = 0;
						cash -= lebih;
					}					
				} else {
					sisa = total - cash - transfer - hutang;
					cash += sisa;
				}
		}
		$('.cash').val(cash);
		$('.transfer').val(transfer);
		$('.hutang').val(hutang);
		currency($('.cash').get(0));
		currency($('.transfer').get(0));
		currency($('.hutang').get(0));
		edited(1);
	}
	function resetHarga(h) {
		$parent = h.parent().parent().parent();
		price = $parent.find('option:selected').attr('harga');
		h.val(price);
	}
	function newItemB() {
		$menu = $('.biaya_item_master').clone(true).removeClass('biaya_item_master').addClass('biaya_item').show();
		$menu.insertBefore($('.plus'));
		resetHarga($menu.find('.harga'));
	}
	function edited(i) {
		if (i == 0) {
			$('.submit').hide();
			$('.cetak').show();
		} else {
			$('.submit').show();
			$('.cetak').hide();
			hitungTotal();
		}
	}
	function currency(angka){
		var number_string = angka.value.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);

		if(ribuan){
			separator = sisa ? '.' : '';
			rupiah += separator + ribuan.join('.');
		}
		if(split[1] != undefined){
			if(split[1].length > 2){
				split[1] = '0.'+split[1];
				split[1] = parseFloat(split[1]).toFixed(2);
				split[1] = split[1].toString().substr(2);
			}
		}

		rupiah = split[1] != undefined ? rupiah + ',' + split[1] : rupiah;
		angka.value = rupiah;
	}
</script>
{% endblock %}