@extends('layout')


@section('content')

<style type="text/css">
	 .table-form>tbody>tr>th, .table-form>tfoot>tr>th, .table-form>thead>tr>td, .table-form>tbody>tr>td, .table-form>tfoot>tr>td{
		    padding: 5px;
		   -- vertical-align: middle;
		}
		table.table-form tbody>tr.selected, table.table-form tbody>tr.selected td, table.table-form tbody>tr>.selected{
		    color: white !important;
		    background-color: #49b6d6 !important;
		}

	 table, th, td, input, textarea, select {
            color:  black !important; 
        }
        .help-block {
 
    margin-top: 0px!important;
    margin-bottom: 0px!important;
}
</style>

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

<div class="content">
	<div class="panel panel-flat">
		<div class="panel-heading">
			<h5 class="panel-title">Form Retur Penjualan</h5>
			<div class="heading-elements">
				<ul class="icons-list">
		      		<li><a href="{{ url('penjualan/retur_penjualan') }}" 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_retur_penjualan" method="POST" action="{{ $url_submit }}" autocomplete="off" >
	    		{{ csrf_field() }}
	    		{{ method_field($method) }}
	    		@if(isset($data))
	    		{{ Form::hidden('id', $data->id) }}
	    		@endif

        	<div class="col-sm-6">
	    		<div class="form-group">
	    			{{ Form::label("Label CV", "", ['class'=>'control-label col-sm-4']) }}
	    			<div class="col-sm-8">
	    				<div class="checkbox">
	    					<label>
		    					{{ Form::checkbox("cv", '1', true, ['class'=>'styled']) }}
	    					</label>
	    				</div>
	    			</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($lokasi as $key=>$value)
        					<option value="{{ $value->id_lokasi }}">{{ $value->nama_lokasi}}</option>
        					@endforeach
        				</select>
        			</div>
        		</div>
        		<div class="form-group">
        			<label class="control-label col-sm-4">Pelanggan</label>
        			<div class="col-sm-8">
        				<select class="form-control select-search" name="pelanggan" onchange="get_data_penjualan()">
        					@foreach($pelanggan as $value)

        					<option value="{{ $value->id_pelanggan }}">{{ $value->pic.' - '.$value->nama }}</option>

        					@endforeach
        				</select>
        			</div>
        		</div>
        		<div class="form-group">
        			<label class="control-label col-sm-4">Tanggal Input</label>
        			<div class="col-sm-8">
        				<input class="form-control datepicker" type="text" name="tanggal" placeholder="Tanggal" value="{{ date('d-m-Y') }}" required/>
        			</div>
        		</div>
        		<div class="form-group">
        			<label class="control-label col-sm-4">Tanggal Retur</label>
        			<div class="col-sm-8">
        				<input class="form-control datepicker" type="text" name="tanggal_retur" placeholder="Tanggal Retur" value="{{ date('d-m-Y') }}" onchange="get_nomor($(this))" required/>
        			</div>
        		</div>
        		<div class="form-group">
        			<label class="control-label col-sm-4">No. Retur</label>
        			<div class="col-sm-3 col-md-3">
        				{{ Form::text('no_retur', 0, ['class'=>'form-control text-right', 'placeholder'=>'Nomor']) }}
        			</div>
        			<div class="col-sm-5 col-md-5">
        				{{ Form::text("sufix_no_retur", 0, ['class'=>'form-control text-uppercase']) }}
        			</div>
        		</div>
        		<div class="form-group">
        			<label class="control-label col-sm-4">Keterangan</label>
        			<div class="col-sm-8">
        				<textarea class="form-control" name="keterangan" rows="2"></textarea>
        			</div>
        		</div>
        		<div class="form-group">
        			<label class="control-label col-sm-4">Mata Uang</label>
        			<div class="col-sm-6 col-md-6">
        				<select class="form-control select-search" name="currency" id="currency">
        					@foreach($mata_uang as $key => $value)
        						<option value="{{ $value->id_matauang }}" data-inisial="{{ $value->inisial }}">{{ $value->nama_matauang }} - {{ $value->inisial }}</option>
        					@endforeach
        				</select>
        			</div>
        		</div>
        		<div class="form-group" id="field_kurs">
        			<label class="control-label col-sm-4">Kurs (IDR/USD)</label>
        			<div class="col-sm-8">
        				{{ Form::label("Kurs IDR/USD", "", ["class"=>"control-label"]) }}
	    				{{ Form::number("kurs", 1, ["class"=>"form-control","min"=>"0","id"=>"kurs","step"=>0.01]) }}
	    				<span class="help-block text-right" style="font-weight: bold;" id="nominal_kurs">Rp0</span>
        			</div>
        		</div>
        	</div>

        	<div class="col-sm-6">
        	</div>

        	<div class="row col-sm-12">
			    <h5 class="panel-title">Detail Barang</h5>
	        	<div class="col-sm-6">
		        	<div class="form-group">
		        		<label class="control-label col-sm-4">No. Faktur Penjualan</label>
		        		<div class="col-sm-8">
			        		<select name="id_penjualan" class="form-control select-search" onchange="get_barang_penjualan()">
			        			
			        		</select>
			        	</div>
		        	</div>
		        </div>
	        </div>

        	<div class="col-ms-12">

        	<div class="responsive">
	        	<table class="table table-stripped" id="table_barang">
			    	<thead>
						<tr>
							<th width="15%">Kode Barang</th>
							<th>Nama Barang</th>
							<th width="5%">Jml. Faktur</th>
							<th width="5%">Jml. Retur</th>
							<th width="15%">Harga Satuan</th>
							<th width="15%">Potongan</th>
							<th width="15%">Nominal</th>
						</tr>
					</thead>
					<tbody>

					</tbody>
					<tfoot>

					</tfoot>
			    </table>
			</div>

        	</div>

        	<hr>

            <div class=" col-md-6 col-sm-12 m-l-5">
             
              <div class="table-responsive">
	    	
		           <table class="table table-bordered table-form">
			    	<tbody>
			    		<tr class="active">
		             		<td colspan="2">Total Penjualan</td>
		             	</tr>
		             	<tr>
							<td>Sub Total</td>
		                    <td><input type="hidden" name="td_total" value="0" readonly="">
		                    	<p class="help-block currency pull-right" id="td_total">Rp 0</p>
		                    </td>
						</tr>
						
		                {{-- <tr>
							<td>Potongan</td>
		                    <td><input type="text" name="td_potongan" class="form-control number-only text-right" value="0">
		                    	<p class="help-block currency pull-right" id="help_popup_potongan">Rp 0</p>
		                    </td>
						</tr> --}}
		               
						<tr>
							<td>PPN</td>
		                    <td>
		                    	<select class="form-control select-search" name="pajak">
		        					<option value="0" >Tidak</option>
		        					<option value="1" >Iya</option>
		        				</select>
		                    	<input type="hidden" name="td_pajak" class="form-control number-only text-right" value="0">
		                    	<p class="help-block currency pull-right" id="help_popup_pajak">Rp 0</p>
		                    </td>
						</tr>
		                <tr>
							<td>Nilai Retur</td>
		                    <td><p class="help-block currency pull-right" id="td_netto">Rp 0</p></td>
						</tr>
					</tbody>
			    </table>
             </div>
             </div>


             <div class="col-md-6 col-sm-12">
             	<div class="table-responsive">
             		
             	</div>
             </div>

	    </div>

	    <div class="panel-footer">
	    	<div class="col-sm-12 col-md-12">
	            <div class="form-group pull-right">
	            	<a href="{{ url('penjualan/retur_penjualan') }}" class="btn btn-default">Batal</a>
	             	<button class="hidden" type="submit" id="btn-submit">Simpan</button>
	             	<button class="btn btn-success" type="submit" id="simpan_retur_penjualan">Simpan</button>
	            </div>

	    	</div>

	    </div>

	    </form>
	</div>
</div>


<script type="text/javascript">
var stok_barang_selected = 0;
var tabel;

$(document).ready(function(){
	// init element
	$(".set_select2").select2();
	tabel = $("#table_barang").DataTable({
		filter : false,
		paging : false,
		deferRender : true,
		columns : [
			{data:'kode_barang', name:'kode_barang'},
			{data:'nama_barang', name:'nama_barang'},
			{data:'jml_barang', name:'jml_barang'},
			{data:'jml_retur', name:'jml_retur'},
			{data:'harga_satuan', name:'harga_satuan'},
			{data:'potongan', name:'potongan'},
			{data:'total', name:'total'},
		],
		createdRow : function(row, data, index){
			// $("td", row).eq(4).addClass("text-right").html(accounting.formatMoney(data.harga_satuan));
			// $("td", row).eq(5).addClass("text-right").html(accounting.formatMoney(data.potongan));
			// $("td", row).eq(6).addClass("text-right").html(accounting.formatMoney(data.total));
		},
	});

	// action element
	$("select[name=pajak]").change(function(){
        if($(this).val()==1){
    		$("input[name=td_pajak]").val(0);    	
    		// $("input[name=td_pajak]").removeAttr('readonly');
        }else{
        	$("input[name=td_pajak]").val(0);    	
        	// $("input[name=td_pajak]").attr('readonly','readonly');
        }
        netto();
    });


	$("#simpan_retur_penjualan").on("click", function(evt){
		if ($("#currency").val() != "1") {
			if ($("#kurs").val() == "" || $("#kurs").val() == "0" || $("#kurs").val() == 0 || $("#kurs").val() == "1" || $("#kurs").val() == 1) {
				$("#kurs").focus();
				alert('Masukkan jumlah kurs (IDR/USD) saat ini');
			} else {
				$("#form_retur_penjualan#btn-submit").trigger("click");
			}
		} else {
			$("#form_retur_penjualan#btn-submit").trigger("click");
		}
	})

	$("#form_retur_penjualan").submit(function(){
		$("#simpan_retur_penjualan").addClass("disabled");
	})

	// trigger data
	$("#form_retur_penjualan input[name=tanggal_retur]").trigger("change");
	get_data_penjualan();
	@if(isset($data))
	edit_data_retur();
	@endif

    setCurrency($("#currency").val());
	checkKurs();
	if ($("#currency").val() == "1") {
		$("#field_kurs").hide('slow');
		$("#kurs").val(1);
	} else {
		$("#field_kurs").show('slow');
		$("#kurs").val(1);
	}

});

$("#currency").on("change", function(evt){
	evt.preventDefault();
	if ($(this).val() == 1) {
		$("#field_kurs").hide('slow');
		$("#kurs").val(1);
		$("#kurs").trigger('keyup');
	} else {
		$("#field_kurs").show('slow');
		$("#kurs").val(1);
		$("#kurs").trigger('keyup');
	}
	setCurrency($(this).val());
})

$("#kurs").on("keyup", function(evt){
	evt.preventDefault();
	setKurs($(this));
})

function checkKurs(){
	if ($("#kurs").val() != "") {
		setKurs($("#kurs"));
	}
}

function setKurs(this_){
	accounting.settings = {
		currency: {
			symbol : "Rp",   // default currency symbol is '$'
			format: { pos : "%s%v", neg : "( %s%v )", zero : "%s%v"}, // controls output: %s = symbol, %v = value/number (can be object: see below)
			decimal : ",",  // decimal point separator
			thousand: ".",  // thousands separator
			precision : 2   // decimal places
		},
		number: {
			precision : 2,  // default precision on numbers is 0
			thousand: ".",
			decimal : ","
		}
	}

	var data = this_.val();
	if(data==""){
		data = 0;
	}

	$("#nominal_kurs").html(accounting.formatMoney(data));
}

function setCurrency(curr){
	accounting.settings = {
		currency: {
			symbol : (curr == "1") ? "Rp" : "$",   // default currency symbol is '$'
			format: { pos : "%s%v", neg : "( %s%v )", zero : "%s%v"}, // controls output: %s = symbol, %v = value/number (can be object: see below)
			decimal : ",",  // decimal point separator
			thousand: ".",  // thousands separator
			precision : 2   // decimal places
		},
		number: {
			precision : 2,  // default precision on numbers is 0
			thousand: ".",
			decimal : ","
		}
	}

	$(".currency").html(accounting.formatMoney());
	$("input[name='barang[harga_satuan][]'], input[name='barang[potongan][]']").trigger("keyup");
}

@if(isset($data))
function edit_data_retur(){
	$("#form_retur_penjualan [name=lokasi]").val('{{$data->lokasi}}').attr("disabled", "").trigger("change");
	@if($data->cv==1)
		$("#form_retur_penjualan [name=cv]").prop("checked", true).attr("disabled", "").trigger("change");
	@else
		$("#form_retur_penjualan [name=cv]").prop("checked", false).attr("disabled", "").trigger("change");
	@endif
	$("#form_retur_penjualan [name=pelanggan]").val('{{$data->id_pelanggan}}').attr("disabled", "").trigger("change");
	$("#form_retur_penjualan [name=tanggal]").val('{{date_db($data->tanggal, true, 2)}}').attr("disabled", "").removeClass("datepicker").trigger("change");
	$("#form_retur_penjualan [name=tanggal_retur]").val('{{date_db($data->tanggal_retur, true, 2)}}').trigger("change");
}
@endif

function get_data_penjualan(){
	var lokasi = $("#form_retur_penjualan select[name=lokasi]").val();
	var id_pelanggan = $("#form_retur_penjualan select[name=pelanggan]").val();

	$.ajax({
		type : "GET",
		url : "{{ url('penjualan/retur_penjualan/get_data_penjualan') }}",
		data : { lokasi:lokasi, id_pelanggan:id_pelanggan },
		dataType : "json",
		success : function(result){

		},
		complete : function(result){
			if (result.responseJSON.length == 0) {
				alert("Tidak ada transaksi untuk pelanggan ini!");
				$("#form_retur_penjualan select[name=id_penjualan]").html("");
				tabel.clear().draw();
			} else {
				var data = result.responseJSON;
				$("#form_retur_penjualan select[name=id_penjualan]").html("");
				$.each(data, function(id, item){
					if(item.sisa_barang==0) return;
					var no_faktur = item.no_faktur+""+item.sufix_no_faktur;
					var option = new Option(no_faktur, item.id_penjualan);
					$("#form_retur_penjualan select[name=id_penjualan]").append(option);
				});
				@if(isset($data))
				$("#form_retur_penjualan select[name=id_penjualan]").val("{{$data->id_penjualan}}").attr("disabled", "").trigger("change");
				@else
				$("#form_retur_penjualan select[name=id_penjualan]").trigger("change");
				@endif
			}
		}
	});
}

function get_barang_penjualan(){
	var id_penjualan = $("#form_retur_penjualan select[name=id_penjualan]").val();
	var url_detail = "{{ url('penjualan/retur_penjualan/get_detail_penjualan') }}";
	var param = new Object();
	param.id_penjualan = id_penjualan;
	@if(isset($data))
	url_detail = "{{ url('penjualan/retur_penjualan/get_detail_retur') }}";
	param.id = $("#form_retur_penjualan [name=id]").val();
	@endif

	$.ajax({
		type : "GET",
		url : url_detail,
		data : param,
		dataType : "json",
		success : function(result){},
		complete : function(result){
			var data = result.responseJSON;

			// pengolahan data penjualan utk kurs
			var penjualan = data.penjualan;
			$("#currency").val(penjualan.mata_uang).trigger("change");
			@if(isset($data))
			$("#currency").attr("disabled", "");
			@endif
			$("#kurs").val(penjualan.kurs_jual).trigger("keyup");

			// pengolahan baris data utk barang
			var penjualanBarang = data.penjualanBarang;
			tabel.clear();
			$.each(penjualanBarang, function(id, item){
				var id_retur_barang = item.id_retur_barang || "";
				var jml_retur = parseInt(item.jml_retur) || 0;
				var sisa_barang = item.jml_barang-item.total_barang_retur+jml_retur;
				if(sisa_barang == 0) return;
				var subTotal = jml_retur*(item.harga_satuan-item.potongan);

				tabel.rows.add([{
						"kode_barang"	: item.kode_barang+
											"<input type='hidden' name='barang[id_retur_barang][]' value='"+id_retur_barang+"'>"+
											"<input type='hidden' name='barang[id_penjualan_barang][]' value='"+item.id_jual_barang+"'>",
						"nama_barang"	: item.nama_barang,
						"jml_barang"	: item.jml_barang+
											" <i class='fa fa-lg fa-info-circle' data-popup='tooltip' title='Jml bisa retur : "+sisa_barang+"' data-placement='bottom'></i>",
						"jml_retur"		: "<input type='number' name='barang[jml_retur][]' class='form-control text-right' value='"+jml_retur+"' min='0' max='"+sisa_barang+"' onkeyup='setNominal($(this))'>",
						"harga_satuan"	: "<input type='hidden' name='barang[harga_satuan][]' value='"+item.harga_satuan+"' onkeyup='setFormatMoney($(this), \"td\"), setNominal($(this))'>"+
											"<span class='help-block currency text-right'></span>",
						"potongan"		: "<input type='hidden' name='barang[potongan][]' value='"+item.potongan+"' onkeyup='setFormatMoney($(this), \"td\"), setNominal($(this))'>"+
											"<span class='help-block currency text-right'></span>",
						"total" 		: "<input type='hidden' name='barang[total][]' value='"+subTotal+"' onkeyup='setFormatMoney($(this), \"td\")'>"+
											"<span class='help-block currency text-right'></span>",
					}]).draw();

				$("[data-popup=tooltip]").tooltip();
			});

			$("input[name='barang[harga_satuan][]'], input[name='barang[potongan][]']").trigger("keyup");
		}
	});
}

function get_nomor(this_){
	var id_retur = $("#form_retur_penjualan [name=id]").val()||'';
	var date = this_.val();
	var s_date = date.split("-");
	var sufix_no_retur = "/RE";
	$.ajax({
		url : "{{ url('penjualan/retur_penjualan/get_nomor') }}",
		type : "get",
		data : {id_retur:id_retur, tanggal:date},
		dataType : "json",
		success : function(result){
			if(id_retur!=""){
				sufix_no_retur = result.sufix_no_retur;
			}
			
			$("input[name=no_retur]").val(result.no_retur);
			$("input[name=sufix_no_retur]").val(sufix_no_retur);
		}
	});
}

function subtotal() {
	var jumlah = 0;
	$("input[name^='barang[total][]']").each(function(id, item) {
		jumlah += parseFloat(item.value);
	});

	$("#td_total").text(accounting.formatMoney(jumlah));
	$("[name=td_total]").val(jumlah);

	netto();
}

function netto(){
	var total = parseFloat($("[name=td_total]").val());
	// var potongan = parseFloat($("[name=td_potongan]").val());
	var potongan = 0;
	var ppn = parseFloat($("[name=td_pajak]").val());

	total = isNaN(total) ? 0 : total;
	potongan = isNaN(potongan) ? 0 : potongan;
	ppn = isNaN(ppn) ? 0 : ppn;

	var netto = parseFloat(0);
	var ppn = parseFloat(0);

	if($('select[name=pajak]').val()==1){
		ppn = parseFloat((total-potongan)*(10/100));
	}
		
	netto = total-potongan+ppn; //+bunga
	// $("[name=td_potongan]").val(potongan);
	// $("#help_popup_potongan").text(accounting.formatMoney(potongan));

	$("[name=td_pajak]").val(ppn);
	$("#help_popup_pajak").text(accounting.formatMoney(ppn));

	$("#td_netto").text(accounting.formatMoney(netto));
	$("[name=td_netto]").val(netto);
}

function setNominal(this_) {
	var row = this_.parents("tr");
	var jml_retur = row.find($("input[name='barang[jml_retur][]']")).val();
	var harga_satuan = row.find($("input[name='barang[harga_satuan][]']")).val();
	var potongan = row.find($("input[name='barang[potongan][]']")).val();
	var inputTotal = row.find($("input[name='barang[total][]']"));

	jml_retur = isNaN(jml_retur) ? 0 : jml_retur;
	harga_satuan = isNaN(harga_satuan) ? 0 : harga_satuan;
	potongan = isNaN(potongan) ? 0 : potongan;
	var totalvalue = (jml_retur*harga_satuan)-(jml_retur*potongan);
	inputTotal.val(totalvalue).trigger("keyup");

	subtotal();

}

function setFormatMoney(this_, p) {
	var div = this_.parents(p);
	var data = this_.val();
	if(data==""){
		data = 0;
	}

	accounting.settings = {
		currency: {
			symbol : ($("#currency").val() == "1") ? "Rp" : "$",   // default currency symbol is '$'
			format: { pos : "%s%v", neg : "( %s%v )", zero : "%s%v"}, // controls output: %s = symbol, %v = value/number (can be object: see below)
			decimal : ",",  // decimal point separator
			thousand: ".",  // thousands separator
			precision : 2   // decimal places
		},
		number: {
			precision : 2,  // default precision on numbers is 0
			thousand: ".",
			decimal : ","
		}
	}

	div.find(".currency").html(accounting.formatMoney(data));
}

</script>

@endsection