@extends('layout')

@section('content')

<div class="page-header page-header-default">
	<div class="breadcrumb-line">
		<ul class="breadcrumb">
			<li><a href="#"><i class="icon-home2 position-left"></i> Produksi</a></li>
			<li class="active">Upah Produksi Langsung</li>
		</ul>
	</div>
</div>

<div class="content">
	<div class="panel panel-flat">
		<div class="panel-heading">
			<h5 class="panel-title">Form Input Upah Produksi Langsung</h5>
			<div class="heading-elements">
				<ul class="icons-list">
					<li><a href="{{ url('upah_produksitanpahasil') }}" class="text-warning"><i class="icon-circle-left2 warning"></i> Kembali</a></li>
				</ul>
			</div>
		</div>
		<div class="panel-body">
			<form class="form-horizontal" id="form_submit" method="post" action="{{ url('upah_produksitanpahasil/bayar') }}" autocomplete="off">
				<input type="hidden" name="_token" value="{{ csrf_token() }}">
				<input type="hidden" name="id_upah" value="{{ $data['id_upah'] }}">
				<table class="table table-striped">
					<div class="col-sm-6">
						<div class="form-group">
							<label class="control-label col-sm-4">Pegawai</label>
							<div class="col-sm-8">       				
								<input type="text" name="pegawai" class="form-control" value="{{ $data['parent']->nama_pegawai }}" readonly>
							</div>
						</div>
						<div class="form-group">
							<label class="control-label col-sm-4">Proses</label>
							<div class="col-sm-8">       				
								<input type="text" name="proses" class="form-control" value="{{ $data['parent']->nama_proses }}" readonly>
							</div>
						</div>
						<div class="form-group">
							<label class="control-label col-sm-4">Tanggal Upah</label>
							<div class="col-sm-8">       				
								<input type="text" name="tanggal_upah" class="form-control" value="{{ tgl_full($data['parent']->tanggal_upah, '') }}" readonly>
							</div>
						</div>
						<div class="form-group">
							<label class="control-label col-sm-4">Nomor</label>
							<div class="col-sm-8">       				
								<input type="text" name="nomor" class="form-control" value="{{ $data['parent']->nomor }}" readonly>
							</div>
						</div>
						<div class="form-group">
							<label class="control-label col-sm-4">Lap. Hasil</label>
							<div class="col-sm-8">       				
								<input type="text" name="tanggal_akhir" class="form-control" value="{{ tgl_full($data['parent']->tanggal_hasil, '') }}" readonly>
							</div>
						</div>
					</div>
					<div class="col-sm-6">
						<div class="form-group">
							<label class="control-label col-sm-4">Rekanan</label>
							<div class="col-sm-8">       				
								<input type="text" name="rekanan" class="form-control" value="{{ get_stripe([$data['parent']->nama_rekanan, $data['parent']->nama_kelompok]) }}" readonly>
							</div>
						</div>
						<div class="form-group">
							<label class="control-label col-sm-4">Lokasi</label>
							<div class="col-sm-8">       				
								<input type="text" name="lokasi" class="form-control" value="{{ $data['parent']->nama_lokasi }}" readonly>
							</div>
						</div>
					</div>					
				</table>

				<div class="col-sm-12 form-group">
					<h5>Hasil</h5>
					{{-- <div class="pull-right">
						<button type="button" id="btn_tambah_upah" class="btn btn-success"><i class="fa fa-plus"></i></button>
					</div> --}}
					<table class="table table-striped" id="table_hasil">
						<thead>
							<tr>
								<th width="5%">No</th>
								<th width="40%">Keterangan</th>
								<th width="15%">Upah</th>
								<th width="20%">Jumlah Barang</th>
								<th>Total</th>
								<th></th>
							</tr>
						</thead>
						<tbody>
							@php
							$total_upah = 0;
							if($data['detail']->count() > 0){
							foreach($data['detail']->get() as $d){
							@endphp
							<tr>
								<td></td>
								<td>{{ $d->keterangan }}</td>	
								<td>{{ $d->nama_upah }}</td>
								<td>{{ $d->jumlah }}</td>
								<td>{{ rupiah2($d->upah)}}</td>
								<td></td>
							</tr>
							@php
							$total_upah += $d->upah;
							}
							}
							@endphp
						</tbody>
						<tfoot>
							<tr>
								<th></th>
								<th></th>
								<th></th>
								<th>Sub Total</th>
								<th class="text-right"><p id="sub_total_upah">{{ rupiah2($total_upah) }}</p><input type="hidden" id="total_upah_barang" value="{{$total_upah}}"></th>
								<th></th>
							</tr>
						</tfoot>
					</table>
				</div>

				<div class="col-sm-12 form-group">
					<h5>Lain-lain</h5>
					<div class="pull-right">
						<button type="button" id="btn_add_lain" class="btn btn-success"><i class="fa fa-plus"></i></button>
					</div>
					<table class="table table-striped" id="table_lain">
						<thead>
							<tr>
								<th>No</th>
								<!-- <th style="width: 30%">Akun</th> -->
								<th>keterangan</th>
								<th>Tipe</th>
								<th>Jenis Transaksi</th>
								<th>Jumlah</th>						
								<th></th>						
							</tr>
						</thead>
						<tbody>
							@php
							$jum_lain = 0;
							if($data['lainnya']->count() > 0){
								foreach($data['lainnya']->get() as $d){
							@endphp
							<tr>
								<td></td> <input type="hidden" name="store_id[]" value="{{ $d->id_ }}">
								{{-- <td>{{ $d->nama_perkiraan }}</td> <input type="hidden" name="akun_lain_[]" value="{{ $d->id_akun }}"> --}}
								<td>{{ $d->keterangan }}</td> <input type="hidden" name="keterangan_lain_[]" value="{{ $d->keterangan }}">
								<td>{{ ($d->tipe == "K") ? "Pengurangan (-)":"Penjumlahan (+)" }} <input type="hidden" class="tipelain" name="tipe_lain_[]" value="{{ $d->tipe }}"></td>
								<td>{{ ($d->jenis_transaksi == "KASBON") ? "POTONGAN KAS BON":"TAMBAHAN" }} <input type="hidden" class="jenis_transaksi" name="jenis_transaksi_lain_[]" value="{{ $d->jenis_transaksi }}"></td>
								<td>{{ ($d->jenis_transaksi == "KASBON") ? rupiah2($d->jumlah*-1) : rupiah2($d->jumlah)  }}<input type="hidden" class="form-control text-right jumlah_lain" name="jumlah_lain_[]" onkeypress="return isNumberKey(event)" onkeyup="hitungJumlahLain()" value="{{ $d->jumlah }}"></td>
								<td></td>
								
								
							</tr>
							@php
							if($d->tipe == "K"){
								$jum_lain -= $d->jumlah;
							}else if($d->tipe == "D"){
								$jum_lain += $d->jumlah;
							}
							
							}
							}

							$total = $total_upah + $jum_lain;
							@endphp
						</tbody>
						<tfoot>
							<tr>
								<th></th>
								<!-- <th></th> -->
								<th></th>
								<th></th>
								<th>Sub Total</th>
								<th class="text-right"><p id="sub_total_upah_lain">{{ $jum_lain }}</p><input type="hidden" id="total_upah_lain" value="{{$jum_lain}}"></th>
								<th></th>
							</tr>
						</tfoot>
					</table>
				</div>

				<div class="col-lg-6 pull-right">
					<div class="form-group">
						<label class="control-label col-sm-4">Total Upah</label>
						<div class="col-sm-8">
							<input class="form-control text-right" type="text" name="total_upah" value="{{ $total }}" id="total_upah" readonly />
						</div>
					</div>
					<div class="form-group">
						<label class="control-label col-sm-4">Akun Bayar</label>
						<div class="col-sm-8">
							
							<select class="form-control select-search" name="akun_bayar" id="akun_bayar" required>
								<option value="0">--- Pilih Akun Bayar ---</option>
								@foreach($data['akun_bayar'] as $key => $ab)
									<option value="{{$key}}">{{$data['akun_bayar'][$key]}}</option>
								@endforeach
							</select>
						</div>
					</div>
					<div class="form-group">
						<label class="control-label col-sm-4">Tanggal bayar</label>
						<div class="col-sm-8">
							<input class="form-control datepicker" type="text" name="tanggal_bayar" id="tanggal_bayar" value="{{date('d-m-Y')}}" />
						</div>
					</div>
				</div>

				<div class="col-sm-12">
					<a href="" class="btn bg-warning-400">Kembali</a>
					<div class="form-group pull-right">
						<button class="btn btn-primary" type="submit" id="btn_simpan">Simpan</button>
					</div>
				</div>
			</form>
		</div>
	</div>
</div>
<input type="hidden" name="store_setor" value="">
<input type="hidden" name="store_sisa" value="">
<script type="text/javascript">
	var table_hasil, table_lain, store_select;
	var no_count = parseInt(1000);
	$(document).ready(function(){

		table_hasil = $("#table_hasil").DataTable({
        	"paging": false,
        });
		table_hasil.on( 'order.dt search.dt', function () {
            table_hasil.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
                cell.innerHTML = i+1;
            } );
        } ).draw();

        table_hasil.on("draw.dt", function(){
        	$("[data-popup='popover']").popover();
        });

        table_lain = $("#table_lain").DataTable({
        	"paging": false,
        });
		table_lain.on( 'order.dt search.dt', function () {
            table_lain.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
                cell.innerHTML = i+1;
            } );
        } ).draw();

        table_lain.on("draw.dt", function(){
        	$("[data-popup='popover']").popover();
        });

	})

	$("#btn_get_upah").click(function(){
		var id_pegawai = $("#pegawai").val();
		var id_proses = $("#proses").val();
		var tgl_akhir = $("#tanggal_akhir").val();
		var id_lokasi = $("[name=lokasi]").val();

		if(id_pegawai != '' && id_proses != '' && tgl_akhir != ''){
			$.ajax({
				url: "{{ url('upah_produksitanpahasil/get_sisa') }}",
				type: 'get',
				data: { proses : id_proses, pegawai : id_pegawai, tgl_akhir : tgl_akhir, lokasi : id_lokasi },
				success: function(respon){
					table_hasil.clear().draw();
					

					if(respon.sisa.length > 0){
						var sisa = respon.sisa[0].sum_masuk-respon.sisa[0].bayar;
						$("[name=store_setor]").val(sisa);
						addHasil(sisa);
						$("[name=store_sisa]").val(0);
						
					}else{

					}

					if(respon.upah.length > 0){
						$("#jum_hasil"+(no_count-1)).html('');
						$("#jum_hasil"+(no_count-1)).append('<option value="" nama="" harga=""> -- Pilih Upah -- </option>');
						store_select = '';
						for(i in respon.upah){
							$("#jum_hasil"+(no_count-1)).append('<option value="'+respon.upah[i].id_upah_boronganlain+'" nama="'+respon.upah[i].nama+'" harga="'+respon.upah[i].harga+'">'+respon.upah[i].nama+'</option>');
							store_select += '<option value="'+respon.upah[i].id_upah_boronganlain+'" nama="'+respon.upah[i].nama+'" harga="'+respon.upah[i].harga+'">'+respon.upah[i].nama+'</option>';
						}
					}
					
				}
			})
		}
	})

	$("#btn_tambah_upah").click(function(){
		var sisa = $("[name=store_sisa]").val();
		
		if(sisa > 0){
			addHasil(sisa);
			$("#jum_hasil"+(no_count-1)).append('<option value="" nama="" harga=""> -- Pilih Upah -- </option>');
			$("#jum_hasil"+(no_count-1)).append(store_select);
		}

		hitungUpah();
	})

	function pilih_upah(this_){
		var value = $(this_).val();
		var nama = $('option:selected', this_).attr("nama");
		var harga = $('option:selected', this_).attr("harga");
		var jum = check_number(this_.parents('tr').find("input[name='jumlah_hasil[]']").val());
		var total_harga = parseFloat(harga)*parseFloat(jum);
		
		this_.parents('tr').find("input[name='keterangan_hasil[]']").val(nama);
		this_.parents('tr').find("input[name='store_harga[]']").val(harga);
		this_.parents('tr').find("input[name='store_total[]']").val(total_harga);
		this_.parents('tr').find("label[name=label_total]").text(to_rupiah(total_harga));
		
		hitungJumlahUpah();
		hitungUpah();
	}

	function addHasil(maksimal){
		table_hasil.row.add([
			'<tr><td><div></td></div>',
			'<td><div><input type="text" class="form-control" name="keterangan_hasil[]" id="input_keterangan'+no_count+'"></td></div>',
			'<td><div><select class="form-control select_" name="select-upah[]" onchange="pilih_upah($(this))" id="jum_hasil'+no_count+'""></select></td></div>',
			'<td><div><input type="text" class="form-control text-right jumlah_hasil dropdown_upah'+no_count+'" name="jumlah_hasil[]" onkeypress="return isNumberKey(event)" value="'+maksimal+'" min="0" max="'+maksimal+'" onkeyup="maksimal($(this)); get_maksimal($(this)); get_total($(this)); hitungJumlahUpah()"></td></div>'+
			'<input type="hidden" name="store_harga[]">'+
			'<input type="hidden" name="store_total[]">',
			'<td><div><label name="label_total" class="pull-right">0</label></td></div>',
			'<td><div class="text-center"><button type="button" onclick="hapus($(this))" class="btn btn-danger btn-xs"><i class="fa fa-times"></i></button></div><td></tr>']).draw(false);

		$(".select_").select2();
		no_count++;
	}

	$("#btn_add_lain").on("click", function(evt){
		evt.preventDefault();
		addLain();
	})

	// Ini yang tanpa akun
	function addLain()
	{
		table_lain.row.add([
			'<div></div>',
			'<div><input type="text" class="form-control keteranganlain" name="keterangan_lain_[]"><input type="hidden" name="store_id[]" value=""></div>',
			'<div><select class="form-control tipelain select-search" name="tipe_lain_[]" onchange="hitungJumlahLain()"><option value="D">Penjumlahan (+)</option><option value="K">Pengurangan (-)</option></select></div>',
			'<div><select class="form-control select-search jenis_transaksi" name="jenis_transaksi_lain_[]"><option value="TAMBAHAN">TAMBAHAN</option><option value="KASBON">POTONGAN KAS BON</option></select></div>',
			'<div><input type="text" class="form-control text-right jumlah_lain" name="jumlah_lain_[]" onkeypress="return isNumberKey(event)" onkeyup="hitungJumlahLain()"></div>',
			'<div class="text-center"><button type="button" onclick="removeLain($(this))" class="btn btn-danger btn-xs"><i class="fa fa-times"></i></button></div>'
			]).draw(false);
		$('.select-search').select2();
		$(".jenis_transaksi").on('change', function(){
			var $items = $('.jenis_transaksi');
		    var $newItem = $items.map(function(i, item) {
		      // console.log($(item).val())
		      // console.log($(".jenis_transaksi:eq("+i+")").val())
		      if ($(".jenis_transaksi:eq("+i+")").val() == "KASBON") {
		      	$(".tipelain:eq("+i+")").val("K").trigger("change");
		      }
		    }).get();
		    // console.log($newItem)
		})
	}

	// Ini yang ada akunnya
	// function addLain()
	// {
	// 	table_lain.row.add([
	// 		'<div></div>',
	// 		'<div><select class="form-control select-search akunlain" name="akun_lain_[]"><option value="0">--- Pilih Akun ---</option>@foreach($data['akun'] as $key => $ab)<option value="{{$key}}">{{$data['akun'][$key]}}</option>@endforeach</select></div>',
	// 		'<div><input type="text" class="form-control keteranganlain" name="keterangan_lain_[]"><input type="hidden" name="store_id[]" value=""></div>',
	// 		'<div><select class="form-control tipelain select-search" name="tipe_lain_[]" onchange="hitungJumlahLain()"><option value="D">Penjumlahan</option><option value="K">Pengurangan</option></select></div>',
	// 		'<div><select class="form-control select-search jenis_transaksi" name="jenis_transaksi_lain_[]"><option value="TAMBAHAN">TAMBAHAN</option><option value="KASBON">POTONGAN KAS BON</option></select></div>',
	// 		'<div><input type="text" class="form-control text-right jumlah_lain" name="jumlah_lain_[]" onkeypress="return isNumberKey(event)" onkeyup="hitungJumlahLain()"></div>',
	// 		'<div class="text-center"><button type="button" onclick="removeLain($(this))" class="btn btn-danger btn-xs"><i class="fa fa-times"></i></button></div>'
	// 		]).draw(false);
	// 	$('.select-search').select2();
	// 	$(".jenis_transaksi").on('change', function(){
	// 		var $items = $('.jenis_transaksi');
	// 	    var $newItem = $items.map(function(i, item) {
	// 	      // console.log($(item).val())
	// 	      // console.log($(".jenis_transaksi:eq("+i+")").val())
	// 	      if ($(".jenis_transaksi:eq("+i+")").val() == "KASBON") {
	// 	      	$(".tipelain:eq("+i+")").val("K").trigger("change");
	// 	      }
	// 	    }).get();
	// 	    // console.log($newItem)
	// 	})
	// }

	function removeLain(this_)
	{
		table_lain.row(this_.parents('tr')).remove().draw(false);
		hitungJumlahLain();
	}

	function hitungJumlahLain()
	{
		var sub_total_lain = 0;
		var jumlah_input = document.getElementsByClassName('jumlah_lain'),
                            jumlah_lain  = [].map.call(jumlah_input, function( input ) {
                            	if (input.value == "") {
                            		return 0;
                            	} else {
                            		return input.value;
                            	}
                            });

        var tipe_lain = document.getElementsByClassName('tipelain'),
                            tipe  = [].map.call(tipe_lain, function( input ) {
                            	if (input.value == "") {
                            		return "D";
                            	} else {
                            		return input.value;
                            	}
                            });

        for (var i = 0; i < jumlah_lain.length; i++){
        	if (tipe[i] == "D") {
        		sub_total_lain += parseFloat(jumlah_lain[i]);
        	} else {
        		sub_total_lain -= parseFloat(jumlah_lain[i]);
        	}
        }

        $("#sub_total_upah_lain").text(new Intl.NumberFormat('de-DE').format(sub_total_lain));
        $("#total_upah_lain").val(sub_total_lain);
        hitungUpah();
	}

	function hitungUpah()
	{
		var upah = parseFloat($("#total_upah_barang").val()) , lain = parseFloat($("#total_upah_lain").val());
		var total = upah + lain;
		$("#total_upah").val(new Intl.NumberFormat('de-DE').format(total))
	}

	function isNumberKey(evt) {
	    var charCode = (evt.which) ? evt.which : evt.keyCode;
	    if (charCode > 31 && (charCode < 48 || charCode > 57))
	        return false;
	    return true;
	}
	
	function get_maksimal(this_){
		var total = $("[name=store_setor]").val();
		var value = check_number($(this_).val());
		var jum = parseFloat(0);
		var sisa = parseFloat(0);
		$("[name='jumlah_hasil[]']").each(function(){
			if(isNaN($(this).val()) || $(this).val() == 0 || $(this).val() == ''){
				jum += parseFloat(0);
			}else{
				jum += parseFloat($(this).val());
			}
		})

		sisa = (parseFloat(total)-jum)+parseFloat(value);
		$(this_).attr("max", sisa);
		get_sisa((parseFloat(total)-jum));
	}

	function get_sisa(){
		var total = $("[name=store_setor]").val();
		var jum = parseFloat(0);
		var sisa = parseFloat(0);
		$("[name='jumlah_hasil[]']").each(function(){
			if(isNaN($(this).val()) || $(this).val() == 0 || $(this).val() == ''){
				jum += parseFloat(0);
			}else{
				jum += parseFloat($(this).val());
			}
		})

		sisa = (parseFloat(total)-jum);
		$("[name=store_sisa]").val(sisa);
	}

	function check_number(val){
		if(isNaN(val) || val == 0 || val == ''){
			nilai = 0;
		}else{
			nilai = val;
		}

		return nilai;
	}

	function get_total(this_){
		var jum = check_number($(this_).val());
		var upah = this_.parents('tr').find("input[name='store_harga[]']").val();
		var total_harga = jum*upah;

		this_.parents('tr').find("input[name='store_total[]']").val(total_harga);
		this_.parents('tr').find("label[name=label_total]").text(to_rupiah(total_harga));

		hitungUpah();
	}

	function hitungJumlahUpah(){
		var sub = 0;
		var jumlah_input = $('[name="store_total[]"]'),
                            store_total  = [].map.call(jumlah_input, function( input ) {
                            	if (input.value == "") {
                            		return 0;
                            	} else {
                            		return input.value;
                            	}
                            });
        for (var i = 0; i < store_total.length; i++){
        	sub += parseFloat(store_total[i]);
        }
	    
	    $("#sub_total_upah").text(to_rupiah(sub));
	    $("#total_upah_barang").val(sub);
	    hitungUpah();
	}

	function to_rupiah(val){
		return curr(val);
	}

	function hapus(this_)
	{
		table_hasil.row(this_.parents('tr')).remove().draw(false);
		hitungJumlahUpah();
		hitungUpah();
	}
	
</script>
@endsection