function sub_total()
{
	var totals=0;
	$('.li_prd_total').each(function(e){
		totals +=parseFloat($(this).text());
	});
	return totals;
}
function rtn_sub_total()
{
	var totals=0;
	$('.rtn_li_prd_total').each(function(e){
		totals +=parseFloat($(this).text());
	});
	return totals;
}
function grand_total()
{
	var subtotal = parseFloat($('#subtotal').text());
	if(isNaN(subtotal)){subtotal=0;}
	var discount = parseFloat($('#discount').val());
	if(isNaN(discount)){discount=0;}
	$('#grandtotal').text((subtotal-discount).toFixed(2));
}
function purchase_total()
{
	var totals=0;
	$('.li_prd_pprice').each(function(e){
		totals +=parseFloat($(this).text());
	});
	return totals;	
}

$(document).ready(function(){

	$(document).on('keypress','.isnumber',function(e){
 	 return isNumber(e, this);
	});

	$('#salesStkItemsTable').DataTable({
    	 "sAjaxSource": base_url+'sales/show_stock_items',
    	 "pageLength": 10,
    	 "order": [],
    	 "responsive":true
    });

	$("#prd_stk").autocomplete({
       source: base_url+'sales/search_prd',
       minLength: 2
    });

	$("#rtn_prd_stk").autocomplete({
       source: base_url+'sales/search_prd',
       minLength: 2
    });

	$(document).on('keyup','.li_prd_price',function(e){
		var qty    = parseFloat($(this).closest('tr').find('.li_prd_qty').text());
		var uprice = parseFloat($(this).val());
		if(isNaN(qty)){qty=0;}
		if(isNaN(uprice)){uprice=0;}
		var total_price = qty*uprice;
		$(this).closest('tr').find('.li_prd_total').text(total_price);
		$('#subtotal').text(sub_total().toFixed(2));
		grand_total();
	});
	$('#btn-add-prd-stk-atl').on('click',function(){
		var prd_stk 	= $('#prd_stk').val();
		var prd_stk_qty = $('#prd_stk_qty').val();
		var flag=0;	
		if(prd_stk==""){return false;}
		if(prd_stk_qty==""){return false;}
		var token_name   = "<?php echo $this->security->get_csrf_token_name();?>";
		var token_value  = $('#my_csrf').val();
		var form_data = new FormData();
		form_data.append('prd_stk',prd_stk);
		form_data.append(token_name,token_value);
		$.ajax({
			url:base_url+'sales/add_items_to_list',
			type:'POST',
			processData:false,
			contentType: false,
			data:form_data,
			success:function(response)
			{
				var res = $.parseJSON(response)
				$('#my_csrf').val(res[0]);
				if(res[1]!='no')
				{
					$('#prd_stk_tbody').append('<tr><td></td><td class="li_prd_stk">'+prd_stk+'</td><td class="li_prd_pprice">'+res[3]+'</td><td><span class="li_prd_qty">'+prd_stk_qty+'</span></td><td><input type="text" class="form-control li_prd_price isnumber" value="'+res[1]+'"></td><td class="li_prd_total">'+eval(prd_stk_qty*res[1])+'</td><td><a href="#" class="tr-rmv"><i class="fa fa-close"></a></td></tr>'); 
						$('#subtotal').text(sub_total().toFixed(2));
						$('#purchase_total').text(purchase_total().toFixed(2));
						grand_total();
						recalcId();
				}
				else
				{
					flag=1;
				}
			}
		});
		if(flag==1){return false;}
		$('#prd_stk').val("");
		$('#prd_stk_qty').val("");
		$('#prd_stk').focus();
	});

	$('#btn-add-rtn-prd-stk-atl').on('click',function(){
		var prd_stk 	= $('#rtn_prd_stk').val();
		var prd_stk_qty = $('#rtn_prd_stk_qty').val();
		var flag=0;	
		if(prd_stk==""){return false;}
		if(prd_stk_qty==""){return false;}
		var token_name   = "<?php echo $this->security->get_csrf_token_name();?>";
		var token_value  = $('#my_csrf').val();
		var form_data = new FormData();
		form_data.append('prd_stk',prd_stk);
		form_data.append(token_name,token_value);
		$.ajax({
			url:base_url+'sales/add_items_to_list',
			type:'POST',
			processData:false,
			contentType: false,
			data:form_data,
			success:function(response)
			{
				var res = $.parseJSON(response)
				$('#my_csrf').val(res[0]);
				if(res[1]!='no')
				{
					$('#rtn_prd_stk_tbody').append('<tr><td></td><td class="rtn_li_prd_stk">'+prd_stk+'</td><td>'+res[3]+'</td><td><span class="rtn_li_prd_qty">'+prd_stk_qty+'</span></td><td class="rtn_li_prd_price">'+res[1]+'</td><td class="rtn_li_prd_total">'+eval(prd_stk_qty*res[1])+'</td><td><a href="#" class="rtn-tr-rmv"><i class="fa fa-close"></a></td></tr>'); 
						$('#rtn_subtotal').text(rtn_sub_total().toFixed(2));
						recalcId2();
				}
				else
				{
					flag=1;
				}
			}
		});
		if(flag==1){return false;}
		$('#rtn_prd_stk').val("");
		$('#rtn_prd_stk_qty').val("");
		$('#rtn_prd_stk').focus();
	});

	$(document).on('click','.tr-rmv',function(e){
		e.preventDefault();
		$(this).closest('tr').remove();
		$('#subtotal').text(sub_total().toFixed(2));
		$('#purchase_total').text(purchase_total().toFixed(2));
		recalcId();
		grand_total();
	});

	$(document).on('click','.rtn-tr-rmv',function(e){
		$(this).closest('tr').remove();
		$('#rtn_subtotal').text(rtn_sub_total().toFixed(2));
		recalcId2();
	});

	$('#customer_contact').on('keypress',function(e){
		var key = e.which;
		if(key===13)
		{
			var token_name   = "<?php echo $this->security->get_csrf_token_name();?>";
			var token_value  = $('#my_csrf').val();
			var form_data = new FormData();
			form_data.append('customer_contact',$(this).val());
			form_data.append(token_name,token_value);
			$.ajax({
				url:base_url+'sales/get_customer',
				type:'POST',
				processData:false,
				contentType: false,
				data:form_data,
				success:function(response)
				{
					var res = $.parseJSON(response)
					$('#my_csrf').val(res[0]);
					$('#customer_name').val(res[1]);
					
				}
			});
		}
	});

	$('#customer_contact').on('blur',function(e){
		if($(this).val()!="")
		{
			$('#advance').removeAttr('readonly');
		}
		else
		{
			$('#advance').attr('readonly','readonly');	
		}
	});

	$('#discount').on('keyup',function(e){
		var sub_total = parseFloat($('#subtotal').text());
		var discount  = parseFloat($(this).val());

		if(isNaN(sub_total)){sub_total=0;}
		if(isNaN(discount)){discount=0;}
		var grandtotal  = (sub_total-discount).toFixed(2);
		$('#grandtotal').text(grandtotal);
	});

	$('#payments').on('keyup',function(e){
		var grandtotal = parseFloat($('#grandtotal').text());
		var payments  = parseFloat($(this).val());

		if(isNaN(grandtotal)){grandtotal=0;}
		if(isNaN(payments)){payments=0;}
		var change    = (grandtotal-payments).toFixed(2);
		$('#change').text(change);
	});

	$('#btn-process-items').on('click',function(){
		var customer_contact = $('#customer_contact').val();
		var customer_name    = $('#customer_name').val();
		var type ='CASH';
		if(customer_contact!="")
		{
			type='CUSTOMER';
		}
		if(type=='CUSTOMER' && customer_name=="")
		{
			swal('Customer Name Required','Please add customer name if using contact','info');
			return false;
		}

		var purchases  = 0;
		$('.li_prd_pprice').each(function(e){
			var p=parseFloat($(this).text());
			var q=parseFloat($(this).closest('tr').find('.li_prd_qty').text());
			purchases +=(p*q);
		});
		
		var subtotal   = parseFloat($('#subtotal').text());
		var discount   = parseFloat($('#discount').val());
		var grandtotal = parseFloat($('#grandtotal').text());
		var advance    = parseFloat($('#advance').val());
		var payments   = parseFloat($('#payments').val());
		var change     = parseFloat($('#change').text());
		
		if(isNaN(purchases)){purchases=0;}
		if(isNaN(subtotal)){subtotal=0;}
		if(isNaN(discount)){discount=0;}
		if(isNaN(grandtotal)){grandtotal=0;}
		if(isNaN(change)){change=0;}
		if(isNaN(payments)){payments=0;}
		if(subtotal==0)
		{
			swal('Add Some Items','Please add some items to continue','info');
			return false;
		}
		if(discount>subtotal)
		{
			swal('Discount Limit','Discount must be equals or less subtotal','warning');
			return false;
		}	
		if(payments<grandtotal && customer_contact=="")
		{
			swal('Warning','Payment must be equals to grand total','warning');
			return false;
		}

		var item_name=[];
		var item_pprice=[];
		var item_price=[];
		var item_qty =[];
		var item_total=[];
		$('.li_prd_stk').each(function(){
			item_name.push($(this).text());
			item_pprice.push($(this).closest('tr').find('.li_prd_pprice').text());
			item_price.push($(this).closest('tr').find('.li_prd_price').text());
			item_qty.push($(this).closest('tr').find('.li_prd_qty').text());
			item_total.push($(this).closest('tr').find('.li_prd_total').text());
		});
		var token_name   = "<?php echo $this->security->get_csrf_token_name();?>";
		var token_value  = $('#my_csrf').val();
		var form_data = new FormData();
		form_data.append('type',type);
		form_data.append('customer_contact',customer_contact);
		form_data.append('customer_name',customer_name);
		form_data.append('purchases',purchases);
		form_data.append('subtotal',subtotal);
		form_data.append('discount',discount);
		form_data.append('grandtotal',grandtotal);
		form_data.append('advance',advance);
		form_data.append('payments',payments);
		form_data.append('change',change);
		form_data.append('item_name',JSON.stringify(item_name));
		form_data.append('item_pprice',JSON.stringify(item_pprice));
		form_data.append('item_price',JSON.stringify(item_price));
		form_data.append('item_qty',JSON.stringify(item_qty));
		form_data.append('item_total',JSON.stringify(item_total));
		form_data.append(token_name,token_value);
		$.ajax({
			url:base_url+'sales/process_items',
			type:'POST',
			processData:false,
			contentType: false,
			async:false,
			data:form_data,
			success:function(response)
			{
				var res = $.parseJSON(response)
				$('#my_csrf').val(res[0]);
				if(res[1]==1)
				{
					$('#ifnotify-success').text(' Processed');
					$('#ifnotify-success').trigger('click');
					window.open(base_url+'sales/invoice/'+res[2]);
					$('#prd_stk_tbody').html("");
					$('#purchase_total').text('');
					$('#customer_contact').val('');
					$('#customer_name').val('');
					$('#subtotal').text('0.00');
					$('#grandtotal').text('0.00');
					$('#discount').val('');
					$('#advance').val('');
					$('#advance').attr('readonly','readonly');
					$('#payments').val('');
					$('#change').text('0.00');
				}
				else
				{
					$('#ifnotify-error').text(' Error try again');
					$('#ifnotify-error').trigger('click');
				}
			}
		});
	});

	$('#btn-rtn-items').on('click',function(){
		var rtn_invoice = $('#rtn_invoice').val();
		var subtotal   = parseFloat($('#rtn_subtotal').text());
		if(isNaN(subtotal)){subtotal=0;}
		if(isNaN(subtotal) || subtotal==0)
		{
			swal('No Items','Please add items','info');
			return false;
		}
		
		var item_name=[];
		var item_price=[];
		var item_qty =[];
		var item_total=[];
		$('.rtn_li_prd_stk').each(function(){
			item_name.push($(this).text());
			item_price.push($(this).closest('tr').find('.rtn_li_prd_price').text());
			item_qty.push($(this).closest('tr').find('.rtn_li_prd_qty').text());
			item_total.push($(this).closest('tr').find('.rtn_li_prd_total').text());
		});
		var token_name   = "<?php echo $this->security->get_csrf_token_name();?>";
		var token_value  = $('#my_csrf').val();
		var form_data = new FormData();
		form_data.append('rtn_invoice',rtn_invoice);
		form_data.append('subtotal',subtotal);
		form_data.append('item_name',JSON.stringify(item_name));
		form_data.append('item_price',JSON.stringify(item_price));
		form_data.append('item_qty',JSON.stringify(item_qty));
		form_data.append('item_total',JSON.stringify(item_total));
		form_data.append(token_name,token_value);
		$.ajax({
			url:base_url+'sales/process_return_items',
			type:'POST',
			processData:false,
			contentType: false,
			data:form_data,
			success:function(response)
			{
				var res = $.parseJSON(response)
				$('#my_csrf').val(res[0]);
				if(res[1]==1)
				{
					$('#ifnotify-success').text(' Processed');
					$('#ifnotify-success').trigger('click');
					$('#rtn_invoice').val("");
					$('#rtn_prd_stk_tbody').html("");
					$('#rtn_subtotal').text('0.00');
				}
				else
				{
					$('#ifnotify-error').text(' Error try again');
					$('#ifnotify-error').trigger('click');
				}
			}
		});
	});

	$('#rtn_invoice').on('keypress',function(e){
		var key = e.which;
		if(key===13)
		{
			var invnumber=$(this).val();
			var invoice = 'INVOICE-'+invnumber;
			$('#return-inovice-modal').modal('toggle');
			$('#inv-iframe').attr('src',base_url+'sales/invoice/'+invoice);
		}
	});


	$('#btn-process-quotation').on('click',function(){
		var customer_contact = $('#customer_contact').val();
		var customer_name    = $('#customer_name').val();
		var type ='CUSTOMER';
		if(customer_name=="")
		{
			swal('Customer Name Required','Please add customer name if using contact','info');
			return false;
		}
		if(customer_contact=="")
		{
			swal('Customer Contact Required','Please add customer contact','warning');	
			return false;
		}

		var purchases  = 0;
		$('.li_prd_pprice').each(function(e){
			var p=parseFloat($(this).text());
			var q=parseFloat($(this).closest('tr').find('.li_prd_qty').text());
			purchases +=(p*q);
		});
		
		var subtotal   = parseFloat($('#subtotal').text());
		var discount   = parseFloat($('#discount').val());
		var grandtotal = parseFloat($('#grandtotal').text());
		var advance    = parseFloat($('#advance').val());
		var payments   = parseFloat($('#payments').val());
		var change     = parseFloat($('#change').text());
		
		if(isNaN(purchases)){purchases=0;}
		if(isNaN(subtotal)){subtotal=0;}
		if(isNaN(discount)){discount=0;}
		if(isNaN(grandtotal)){grandtotal=0;}
		if(isNaN(change)){change=0;}
		if(isNaN(payments)){payments=0;}
		if(subtotal==0)
		{
			swal('Add Some Items','Please add some items to continue','info');
			return false;
		}
		if(discount>subtotal)
		{
			swal('Discount Limit','Discount must be equals or less subtotal','warning');
			return false;
		}	
		
		var item_name=[];
		var item_pprice=[];
		var item_price=[];
		var item_qty =[];
		var item_total=[];
		$('.li_prd_stk').each(function(){
			item_name.push($(this).text());
			item_pprice.push($(this).closest('tr').find('.li_prd_pprice').text());
			item_price.push($(this).closest('tr').find('.li_prd_price').val());
			item_qty.push($(this).closest('tr').find('.li_prd_qty').text());
			item_total.push($(this).closest('tr').find('.li_prd_total').text());
		});
		var token_name   = "<?php echo $this->security->get_csrf_token_name();?>";
		var token_value  = $('#my_csrf').val();
		var form_data = new FormData();
		form_data.append('type',type);
		form_data.append('customer_contact',customer_contact);
		form_data.append('customer_name',customer_name);
		form_data.append('purchases',purchases);
		form_data.append('subtotal',subtotal);
		form_data.append('discount',discount);
		form_data.append('grandtotal',grandtotal);
		form_data.append('advance',advance);
		form_data.append('payments',payments);
		form_data.append('change',change);
		form_data.append('item_name',JSON.stringify(item_name));
		form_data.append('item_pprice',JSON.stringify(item_pprice));
		form_data.append('item_price',JSON.stringify(item_price));
		form_data.append('item_qty',JSON.stringify(item_qty));
		form_data.append('item_total',JSON.stringify(item_total));
		form_data.append(token_name,token_value);
		$.ajax({
			url:base_url+'sales/process_quotation',
			type:'POST',
			processData:false,
			contentType: false,
			async:false,
			data:form_data,
			success:function(response)
			{
				var res = $.parseJSON(response)
				$('#my_csrf').val(res[0]);
				if(res[1]==1)
				{
					$('#ifnotify-success').text(' Processed');
					$('#ifnotify-success').trigger('click');
					window.open(base_url+'sales/qinvoice/'+res[2]);
					$('#prd_stk_tbody').html("");
					$('#purchase_total').text('');
					$('#customer_contact').val('');
					$('#customer_name').val('');
					$('#subtotal').text('0.00');
					$('#grandtotal').text('0.00');
					$('#discount').val('');
					$('#advance').val('');
					$('#advance').attr('readonly','readonly');
					$('#payments').val('');
					$('#change').text('0.00');
				}
				else
				{
					$('#ifnotify-error').text(' Error try again');
					$('#ifnotify-error').trigger('click');
				}
			}
		});
	});


	$('#show-stock-modal').on('show.bs.modal',function(e){
		$('#salesStkItemsTable').DataTable().ajax.reload();
	});

});// End Ready Function
