@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/simpan') }}" autocomplete="off">
				<input type="hidden" name="_token" value="{{ csrf_token() }}">
				<input type="hidden" name="id_upahproduksi" value="{{ $data['data']['id_upahproduksi'] }}">
				<div class="col-sm-6">
					<div class="form-group">
						<label class="control-label col-sm-4">Pegawai</label>
						<div class="col-sm-8">       				
							<select class="form-control select-search" name="pegawai" id="pegawai" required="">
								<option value="">--- Pilih Pegawai ---</option>
								@foreach($data['pegawai'] as $p)
								<option value="{{ $p->id_pegawai}}" {{ ($p->id_pegawai == $data['data']['id_pegawai']) ? "selected":""}}>{{ $p->nomor_pegawai." - ".$p->nama_pegawai }}</option>
								@endforeach
							</select>
						</div>
					</div>
					<div class="form-group">
						<label class="control-label col-sm-4">Proses</label>
						<div class="col-sm-8">       				
							<select class="form-control select-search" name="proses" id="proses" required="">
								<option value="">--- Pilih Proses ---</option>
								@foreach($data['proses'] as $p)
								<option value="{{ $p->id_proses}}" {{ ($p->id_proses == $data['data']['id_proses']) ? "selected":""}}>{{ $p->nama_proses }}</option>
								@endforeach
							</select>
						</div>
					</div>
					<div class="form-group">
						<label class="control-label col-sm-4">Tanggal Upah</label>
						<div class="col-sm-8">
							@php
								if ($data['data']['tanggal_upah'] == '') {
									$tgl_upah = date('d-m-Y');
								} else {
									$tgl_upah = $data['data']['tanggal_upah'];
								}
							@endphp
							<input class="form-control datepicker" type="text" name="tanggal" placeholder="Tanggal" value="{{ $tgl_upah }}" required/>
						</div>
					</div>

					@if($data['edit'])
					<div class="form-group">
						<label class="control-label col-sm-4">Nomor</label>
						<div class="col-sm-8">
							<input class="form-control" type="text" name="nomor" placeholder="" value="{{$nomor = $data['data']['nomor']}}" id="nomor" readonly required />
						</div>
					</div>
					@endif
					<div class="form-group">
						<label class="control-label col-sm-4">Lap. Hasil</label>
						<div class="col-sm-8">
							@php
								if ($data['data']['tanggal_hasil'] == '') {
									$tgl_hasil = date('d-m-Y');
								} else {
									$tgl_hasil = $data['data']['tanggal_hasil'];
								}
							@endphp
	                        {{-- <input id="tanggal_awal" name="tanggal_awal" type="text" class="form-control datepicker" placeholder="Tanggal Awal" />
	                        <span class="input-group-addon bgrange">-</span> --}}
	                        <input id="tanggal_akhir" name="tanggal_akhir" type="text" class="form-control datepicker" placeholder="Tanggal Akhir" value="{{$tgl_hasil}}" />
	                    </div>
					</div>
					<div class="form-group pull-right">
						
					</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">       				
							<select class="form-control select-search" name="rekanan" id="rekanan" required="">
								<option value="">--- Pilih Rekanan ---</option>
								@foreach($data['rekanan'] as $p)
								<option value="{{ $p->id_rekanan}}" {{ ($p->id_rekanan == $data['data']['id_rekanan']) ? "selected":""}}>{{ $p->nama." - ".$p->nama_kelompok }}</option>
								@endforeach
							</select>
						</div>
					</div>
					<div class="form-group">
						<label class="control-label col-sm-4">Lokasi</label>
						<div class="col-sm-8">
							<select class="form-control select-search" name="lokasi">
								@foreach($data['lokasi'] as $d)
								<option value="{{ $d->id_lokasi }}" {{ ($d->id_lokasi == $data['data']['id_lokasi']) ? "selected":"" }}> {{ $d->nama_lokasi }} </option>
								@endforeach
							</select>
						</div>
					</div>
					<input class="form-control" type="hidden" name="akun_upah" placeholder="" value="{{$data['id_akun_upah']}}" id="akun_upah" />
				</div>

				<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>

						</tbody>
						<tfoot>
							<tr>
								<th></th>
								<th></th>
								<th></th>
								<th>Sub Total</th>
								<th class="text-right"><p id="sub_total_upah"></p><input type="hidden" id="total_upah_barang" value="0"></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>

						</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">0</p><input type="hidden" id="total_upah_lain" value="0"></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="0" id="total_upah" readonly />
						</div>
					</div>
					{{-- <div class="form-group" style="display: none">
						<label class="control-label col-sm-4">Akun Bayar</label>
						<div class="col-sm-8">
							<!-- {{ Form::select("id_akun_bayar", $data['akun_bayar'], '', ['class'=>'form-control set_seleted']) }} -->
							<select class="form-control select-search" name="akun_bayar" id="akun_bayar">
								<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" style="display: none">
						<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" />
						</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();
        });

        // ===============================================
        // let id = "{{$data['data']['id_upahproduksi']}}";
	})

	$("#pegawai").change(function(){
		var id = $(this).val();
		if(id != ''){
			disabled("#rekanan", true);
		}else{
			disabled("#rekanan", false);
		}
	})

	$("#rekanan").change(function(){
		var id = $(this).val();
		if(id != ''){
			disabled("#pegawai", true);
		}else{
			disabled("#pegawai", false);
		}
	})

	

	$("#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="" satuan=""> -- Pilih Upah -- </option>');
			$("#jum_hasil"+(no_count-1)).append(store_select);
		// }

		hitungUpah();
		// get_sisa();
	})

	function pilih_upah(this_){
		var value = $(this_).val();
		var nama = $('option:selected', this_).attr("nama");
		var harga = $('option:selected', this_).attr("harga");
		var satuan = $('option:selected', this_).attr("satuan");
		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("input[name='store_satuan[]']").val(satuan);
		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_satuan[]">'+
			'<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 tanpa akun
	function addLain()
	{
		table_lain.row.add([
			'<div></div>',
			'<div><input type="text" class="form-control keteranganlain" name="keterangan_lain_[]"></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">UPAH LAINNYA</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();
		// get_sisa();
	}

	$("[name=proses]").change(function(){
		var id_proses = $(this).val();

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

					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+'" satuan="'+respon.upah[i].id_satuan+'">'+respon.upah[i].nama+'</option>';
						}
					}else{
						store_select = '';
					}
					
				}
			})
		} else {
			alert('Pilih proses & masukkan tanggal Lap. Hasil!');
		}
	})
	
</script>
@endsection