@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;
}

	.input-group-addon:hover:after { 
        content: "Tambah pelanggan biasa"; 
        font-family: Arial;
        font-size: 18px;
        position: absolute;
        padding: 5px;   
        background-color: black;
        color: white;
    }
</style>

<div class="page-header page-header-default">
	<div class="breadcrumb-line">
		<ul class="breadcrumb">
			<li><a href="index.html"><i class="icon-home2 position-left"></i> Penjualan</a></li>
			<li class="active">Surat Jalan</li>
		</ul>
	</div>
</div>

<div class="content">
	<div class="panel panel-flat">
		<div class="panel-heading">
			<h5 class="panel-title">Form Input Surat Jalan</h5>
			<div class="heading-elements">
				<ul class="icons-list">
		      		<li><a href="{{ url('surat_jalan') }}" class="text-warning"><i class="icon-circle-left2 warning"></i> Kembali</a></li>
		      	</ul>
	       	</div>
	    </div>
	    <div class="panel-body">
	    	<form class="form-horizontal" method="post" action="{{ url('surat_jalan').($data['data']['id_penjualan'] != '' ? '/'.$data['data']['id_penjualan'] : '') }}" autocomplete="off">
	    	{{ csrf_field() }}
	    	{{ method_field($data['method']) }}

        	<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', $data['data']['cv'], ['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($data['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 input-group">
        				<select class="form-control select-search" name="pelanggan">
        					@php foreach($data['pelanggan'] as $s){ @endphp

        					<option value="@php echo $s->id_pelanggan @endphp">
        						{{ format_tampil_data_pelanggan($s) }}
        					</option>

        					@php } @endphp
        				</select>
        				<span class="input-group-addon" id="btn_tambah_pelanggan" style="cursor: pointer;">
	        				<i class="fa fa-plus"></i>
	        			</span>
        			</div>
        		</div>
        		<div class="form-group">
        			<label class="control-label col-sm-4">Tgl Surat Jalan</label>
        			<div class="col-sm-8">
        				<input class="form-control set_datepicker" type="text" name="tanggal_surat_jalan" onchange="get_nomor($(this))" placeholder="Tanggal" value="{{ ($data['data']['tanggal_surat'] == '') ? date('d-m-Y'):$data['data']['tanggal_surat'] }}" required/>
        			</div>
        		</div>
        		<div class="form-group">
        			<label class="control-label col-sm-4">No. Surat Jalan</label>
        			<div class="col-sm-3 col-md-3">
        				{{ Form::text('no_surat', $data['data']['no_surat'], ['class'=>'form-control text-right', 'placeholder'=>'Nomor']) }}
        			</div>
        			<div class="col-sm-5 col-md-5">
        				{{ Form::text("sufix_no_surat", $data['data']['sufix_no_surat'], ['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">{{ $data['data']['keterangan_surat'] }}</textarea>
        			</div>
        		</div>
        	</div>

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

        	
        	<div class="col-sm-12 form-group">
	        	<h5 class="panel-title">Detail Barang</h5>
	        </div>

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

        	<div class="responsive">
	        	<table class="table table-stripped" id="table_barang">
			    	<thead>
						<tr>
							<th width="35%">Kode Barang</th>
							<th>Nama Barang</th>
							<th width="15%">Jumlah</th>
							<!-- <th>Jumlah Konversi</th> -->
							<th width="5%" class="text-center">Aksi</th>
						</tr>
					</thead>
					<tbody>
						<tr class="row-barang">
							
						</tr>
					</tbody>
					<tfoot>
						<tr>
							<td colspan="4">
								<button type="button" class="btn btn-sm btn-primary" onclick="tambahRowBarang($(this))" id="btn_tambah_barang"><i class="fa fa-plus"></i> Tambah</button>
							</td>
						</tr>
					</tfoot>
			    </table>
			</div>

        	</div>

            <div class=" col-md-6 col-sm-12 m-l-5">
             
            <div class="table-responsive">

            </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('surat_jalan') }}" class="btn btn-default">Batal</a>
	             	<button class="btn btn-success" type="submit">Simpan</button>
	            </div>

	    	</div>

	    </div>

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

<div class="modal fade" id="add_pelanggan" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
	<div class="modal-dialog modal-lg" role="document">
	    <div class="modal-content">
	    	<div class="modal-header">
	    		<h5 class="modal-title" id="exampleModalLabel">Data Pelanggan</h5>
	    		<button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span></button>
	      	</div>
	      	<div class="modal-body">
	      		<form class="" autocomplete="off">
	      			<div class="row">
	      				<div class="col-sm-6 col-md-6">
			      			<div class="form-group">
			      				<label class="control-label">Nama Pelanggan</label>
			      				<input type="text" name="popup_nama" class="form-control">
			      			</div>

			      			<div class="form-group">
			      				<label class="control-label">Kota</label>
		      					<select class="form-control selectize" name="popup_kota" >
		      						<option value="">--- Pilih Kota ---</option>
		      						@foreach($data['kabupaten']->get() as $kabupaten)
		      						<option value="{{ $kabupaten->nama}}">{{ $kabupaten->nama}}</option>
		      						@endforeach
		      					</select>
			      			</div>
	      			
			      			<div class="form-group">
			      				<label class="control-label">Alamat</label>
			      				<textarea class="form-control" name="popup_alamat" rows="4"></textarea>
			      			</div>
	      			
		      			</div>
			      		<div class="col-sm-6 col-md-6">
			      			<div class="form-group">
			      				<label class="control-label">NPWP</label>
			      				<!-- <div class="col-sm-8"> -->
			      					<input type="text" name="popup_npwp" class="form-control">
			      				<!-- </div> -->
			      			</div>
			      			<div class="form-group">
			      				<label class="control-label">Email</label>
			      				<!-- <div class="col-sm-8"> -->
			      					<input type="text" name="popup_email" class="form-control">
			      				<!-- </div> -->
			      			</div>
			      			<div class="form-group">
			      				<label class="control-label">Telepon</label>
			      				<!-- <div class="col-sm-8"> -->
			      					<input type="text" name="popup_telepon" class="form-control">
			      				<!-- </div> -->
			      			</div>
			      			<div class="form-group">
			      				<label class="control-label">No.Rek</label>
			      				<input type="text" name="popup_norek" class="form-control">
			      			</div>
			      		</div>
		      		</div> <!-- end .row -->

					<hr />
					<div class="row">
					
						<div class="col-sm-6 col-md-6">
							<div class="form-group">
								{{ Form::label("Akun Piutang", "", ['class'=>'control-label']) }}
								{{ Form::select("popup_id_akun_piutang", $data['akun'], [], ['class'=>'control-label select-search']) }}
							</div>
						</div>

					</div> <!-- end .row -->
	      			
	      		</form>
	      	</div>
	      	<div class="modal-footer">
	        	<button type="button" class="btn btn-primary" id="btn_popup_simpan">Simpan</button>
	      	</div>
	    </div>
	</div>
</div>


<script type="text/javascript">
var stok_barang_selected = 0;
var tb_no = parseInt(10000);
var store_select = '';

var id_gudang = '{{ $data['gudang'] }}';
var id_proses = '{{ $data['proses'] }}';

$(document).ready(function(){
	$(".set_select2").select2();

	$("select[name='barang[id_barang][]']").val("").trigger("change");
	get_nomor($("input[name=tanggal_surat_jalan]"));

	$("#btn_tambah_pelanggan").click(function(){
		$("[name=popup_nama]").val('');
		$("[name=popup_npwp]").val('');
		$("[name=popup_email]").val('');
		$("[name=popup_telepon]").val('');
		$("[name=popup_alamat]").val('');
		$("[name=popup_kota]").selectize()[0].selectize.setValue('');
		$("[name=popup_norek]").val('');
		$("select[name=popup_id_akun_piutang]").val('').change();

		$("#add_pelanggan").modal({
		    backdrop: 'static',
		    keyboard: false
		});
	})

	get_barang(id_gudang, id_proses);
});

$("#btn_popup_simpan").click(function(){
	var nama = $("[name=popup_nama]").val();
	var npwp = $("[name=popup_npwp]").val();
	var email = $("[name=popup_email]").val();
	var telp = $("[name=popup_telepon]").val();
	var norek = $("[name=popup_norek]").val();
	var alamat = $("[name=popup_alamat]").val();
	var kota = $("[name=popup_kota]").val();
	var id_akun_piutang = $("select[name=popup_id_akun_piutang]").val();

	if(nama != ''){
		$.ajax({
			url: "{{ url('surat_jalan/pelanggan/simpan')}} ",
			type: 'post',
			data: {nama : nama, npwp:npwp, email:email, telp:telp, norek:norek, alamat:alamat, kota:kota, id_akun_piutang:id_akun_piutang},
			headers : {
				'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
			},
			success: function(response){
				if (response.status == "success") {
					$("#add_pelanggan").modal('hide');
					Swal.fire(
					  'Berhasil!',
					  'Data berhasil disimpan.',
					  'success'
					);
					getPelanggan();
				} else {
					Swal.fire(
					  'Gagal!',
					  'Data gagal disimpan.',
					  'error'
					)
				}
			}
		})
	}
})

function getPelanggan(){
	var row = "", pelanggan = "";
	$.ajax({
		url : "{{ url('surat_jalan/pelanggan-get') }}",
		type : "get",
		success : function(result){
			$("[name='pelanggan'] option").remove();

			$.each(result, function( index, value ) {
			  // alert( index + ": " + value.id_pelanggan );

			  row += "<option value='"+value.id_pelanggan+"'>"+format_tampil_data_pelanggan(value)+"</option>";
			});

			$("[name='pelanggan']").append(row);
		}
	});
}

function format_tampil_data_pelanggan(data, sparator=" - ")
{
	if(Array.isArray(data)){
		if (data.pic == "") {
			return data.nama;
		} else {
			return data.nama+sparator+data.pic;
		}
	}else{
		if(data != null){
			if (data.pic == "") {
				return data.nama;
			} else {
				return data.nama+sparator+data.pic;
			}
		}
	}
	return "None";
}

function get_nomor(this_){
	var id_penjualan = "{{ $data['data']['id_penjualan'] }}";
	var date = this_.val();
	var s_date = date.split("/");
	var sufix_no_surat = "/SJ";
	$.ajax({
		url : "{{ url('surat_jalan/get_nomor_surat') }}",
		type : "get",
		data : {id_penjualan:id_penjualan, tanggal_surat:date},
		dataType : "json",
		success : function(result){
			if(id_penjualan!=""){
				sufix_no_surat = result.sufix_no_surat;
			}
			
			$("input[name=no_surat]").val(result.no_surat);
			$("input[name=sufix_no_surat]").val(sufix_no_surat);
		}
	});
}

function pilih_barang(this_) {
	var opt_selected = this_.find("option:selected");
	var opt_text = opt_selected.text();
	if(opt_text!=""){
		var text = opt_text.split(" - ");
		var nama_barang = text[1].trim();
		this_.parents("tr").find("input[name='barang[nama_barang][]']").val(nama_barang);
		this_.parents("td").find("input[name='barang[id_gudang][]']").val(opt_selected.data("gudang"));
		this_.parents("td").find("input[name='barang[id_satuan][]']").val(opt_selected.data("satuan"));
		this_.parents("td").find("input[name='barang[proses][]']").val(opt_selected.data("proses"));
		this_.parents("td").find("input[name='barang[id_motif][]']").val(opt_selected.data("motif"));
		get_stok_barang(opt_selected.val(), opt_selected.data("gudang"), opt_selected.data("proses"), opt_selected.data("motif"), this_);
	}
}

function get_stok_barang(id_barang, id_gudang, id_proses, id_motif, this_) {
	$.ajax({
		url : "{{ url('penjualan/get_barang') }}",
		type : "post",
		dataType : "json",
		data : {id : id_gudang, id_barang : id_barang, id_proses : id_proses, id_motif : id_motif},
		headers : {
			'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
		},
		success : function(result){
			var stok = 0;
			var max = 0;
			var jum = parseInt(0);
			var total = parseFloat(0);
			var id_satuan = '0';
			var id_motif = '0';
			if(result.length > 0){
				stok = max = result[0].stok;
				id_satuan = result[0].id_satuan;
				id_motif = result[0].id_motif;

				var id_b = result[0].id_barang;
				$('input[id^="jum_barang"]').each(function() {
	              // alert($(this).val());
	            var val = ($(this).attr('id'));
				val = val.replace('jum_barang', '');
				// console.log($("#id_barang"+val).val()+" "+ id_b);
				if($("#id_barang"+val).val() == id_b){
					var jum = $("#jum_barang"+val).val();
					total += parseFloat(jum);
				}

	            });
			}

			max = stok - total;
			stok = stok - total;

			// this_.parents("td").find("input[name='barang[id_satuan][]']").val(id_satuan);
			// this_.parents("td").find("input[name='barang[id_motif][]']").val(id_motif);
			this_.parents("tr").find("input[name='barang[jumlah][]']").attr("min", 1);
			// this_.parents("tr").find("input[name='barang[jumlah][]']").attr("max", max); //
			this_.parents("tr").find("span.this_stok").html("Stok : "+stok);
		}
	})
}

function tambahRowBarang(this_) {
	var rows = '<tr class="row-barang">'+
				'<td>'+
					'<select class="form-control set_select2" name="barang[id_barang][]" onchange="pilih_barang($(this))" id="id_barang'+tb_no+'">'+store_select+
					// 	'<?php foreach($data['produk'] AS $key=>$value): ?>'+
					// 	'<option value="{{ $value->id }}" data-gudang="{{ $data['gudang'] }}" data-satuan="{{ $value->id_satuan }}" data-proses="{{ $data['proses'] }}">{{ format_tampil_data_barang($value) }}</option>'+
					// 	'<?php endforeach; ?>'+
					// '</select>'+
					'<input type="hidden" name="barang[id_gudang][]">'+
					'<input type="hidden" name="barang[id_satuan][]">'+
					'<input type="hidden" name="barang[proses][]">'+
					'<input type="hidden" name="barang[id_motif][]">'+
				'</td>'+
				'<td>'+
					'<input type="text" name="barang[nama_barang][]" class="form-control" value="-">'+
				'</td>'+
				'<td>'+
					'<input type="number" name="barang[jumlah][]" step="1" class="form-control text-right" value="0" id="jum_barang'+tb_no+'">'+
					'<span class="help-block this_stok">Stok : 0</span>'+
				'</td>'+
				'<td>'+
					'<button type="button" class="btn btn-link text-danger"><i class="icon-trash" onclick="hapusRowBarang($(this))"></i></button>'+
				'</td>'+
			'</tr>';
			tb_no++;
			// console.log(store_select);
	$("table#table_barang > tbody").append(rows);
	$(".set_select2").select2();
}

function hapusRowBarang(this_){
	var rowBarang = this_.parents("tr");
	rowBarang.remove();
}

function get_barang(id_gudang, id_proses){
	if(id_gudang != '' && id_proses != ''){
		$.ajax({
			url : "{{ url('penjualan/get_barang') }}",
			type : "POST",
			dataType : "json",
			data : {id : id_gudang, id_proses : id_proses},
			headers : {
				'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
			},
			success : function(response){
				if(response.length > 0){
					store_select = '<option value=""> -- Pilih -- </option>';
					for(i in response){
						store_select += '<option value="'+response[i].id_barang+'" data-gudang="'+response[i].id_gudang+'" data-satuan="'+response[i].id_satuan+'" data-proses="'+response[i].id_proses+'" data-motif="'+response[i].id_motif+'">'+response[i].kode_barang+' - '+response[i].nama_barang+'</option>';
					}
					$("#btn_tambah_barang").click();
				}else{
					store_select = '';
					alert("Gagal mengambil data");
				}
			}
		})
	}else{
		store_select = '';
		alert("Gagal mengambil data");
	}
}
</script>

@endsection