function sub_total()
{
	var totals=0;
	$('.li_prd_total').each(function(e){
		totals +=parseFloat($(this).text());
	});
	$('.li_srv_total').each(function(e){
		totals +=parseFloat($(this).text());
	});
	return totals;
}
function items_sub_total()
{
	var totals=0;
	$('.li_prd_total').each(function(e){
		totals +=parseFloat($(this).text());
	});
	if(isNaN(totals)){totals=0;}
	$('#item-subtotal').text(totals.toFixed(2));
}
function services_sub_total()
{
	var totals=0;
	$('.li_srv_total').each(function(e){
		totals +=parseFloat($(this).text());
	});
	if(isNaN(totals)){totals=0;}
	$('#service-subtotal').text(totals.toFixed(2));
}

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);
	});
	$('.datepicker').datepicker({dateFormat:'yy-mm-dd'});
	$('#salesStkItemsTable').DataTable({
    	 "sAjaxSource": base_url+'quotations/show_stock_items',
    	 "pageLength": 10,
    	 "order": [],
    	 "responsive":true
    });
	var abc = 0; 
	$("#prd_stk").autocomplete({
	   	  source: base_url+'quotations/search_prd',
	      minLength: 2,
	      autoFocus: true,
	      focus: function(event, ui) {
	      	     event.preventDefault();
	      	     if(abc==1)
	      	     {
		             $(this).val(ui.item.value);
		             $('#prd_stk_qty').focus();
		             $('#btn-add-prd-stk-atl').trigger('click');
		         }
		         
		   },
		   select:function(event,ui)
		   {
		   		if(abc!=1)
		   		{
		   			$('#prd_stk_qty').focus();
		   		}
		   }
    });

	$('#prd_stk_qty').on('focusin',function(e){
		abc=0;
	});

	$('#prd_stk_qty').on('keypress',function(e){
		var key = e.which;
		if(key==13)
		{
			$('#btn-add-prd-stk-atl').trigger('click');
		}
	});

	$("#prd_srv").autocomplete({
       source: base_url+'quotations/search_srv',
       minLength: 2
    });

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

	$('#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+'quotations/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><span class="li_prd_qty">'+prd_stk_qty+'</span></td><td class="li_prd_price">'+res[1]+'</td><td class="li_prd_total">'+eval(prd_stk_qty*res[1]).toFixed(3)+'</td><td><a href="#" class="tr-rmv"><i class="fa fa-close"></a></td></tr>'); 
						$('#subtotal').text(sub_total().toFixed(3));
						$('#purchase_total').text(purchase_total().toFixed(3));
						items_sub_total();
						grand_total();
						recalcId();
				}
				else
				{
					flag=1;
				}
			}
		});
		if(flag==1){return false;}
		$('#prd_stk').val("");
		$('#prd_stk_qty').val("");
		$('#prd_stk').focus();
	});


	$('#btn-add-srv-atl').on('click',function(){
		var prd_srv = $('#prd_srv').val();
		var srv_qty = $('#srv_qty').val();
		var flag=0;	
		if(prd_srv==""){return false;}
		if(srv_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_srv',prd_srv);
		form_data.append(token_name,token_value);
		$.ajax({
			url:base_url+'quotations/add_srv_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')
				{
					$('#srv_tbody').append('<tr><td></td><td class="li_prd_srv">'+prd_srv+'</td><td><span class="li_srv_qty">'+srv_qty+'</span></td><td class="li_srv_price">'+res[1]+'</td><td class="li_srv_total">'+eval(srv_qty*res[1])+'</td><td><a href="#" class="srv-tr-rmv"><i class="fa fa-close"></a></td></tr>'); 
						$('#subtotal').text(sub_total().toFixed(2));
						services_sub_total();
						grand_total();
						recalcId2();
				}
				else
				{
					flag=1;
				}
			}
		});
		if(flag==1){return false;}
		$('#prd_srv').val("");
		$('#srv_qty').val("");
		$('#prd_srv').focus();
	});


	

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

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

	
	$('#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+'quotations/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_email').val(res[2]);
					
				}
			});
		}
	});

	$('#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);
	});
	
	$('#btn-process-items').on('click',function(){
		var customer_contact = $('#customer_contact').val();
		var customer_name    = $('#customer_name').val();
		var customer_email   = $('#customer_email').val();
		var notes 			 = $('#notes').val();
		// var delivery_date    = $('#delivery_date').val();
		// var payment_type	 = $('#payment_type').val();
		var type ='CUSTOMER';
		
		if(type=='CUSTOMER' && customer_name=="")
		{
			swal('Customer Name Required','Please add customer name','info');
			return false;
		}
		if(type=='CUSTOMER' && customer_contact=="")
		{
			swal('Customer Contact Required','Please add customer 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 itm_subtotal   = parseFloat($('#item-subtotal').text());
		var srv_subtotal= parseFloat($('#service-subtotal').text());
		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(srv_subtotal!=0 && customer_contact=="")
		// {
		// 	swal('Customer Information Required','Please add customer name and contact number if using services','info');
		// 	return false;	
		// }

		// if(srv_subtotal!=0 && delivery_date=="")
		// {
		// 	swal('Delivery Date Required','Please enter delivery date when using services','info');
		// 	return false;	
		// }

		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(grandtotal==0)
		{
			swal('Add Some Items','Please add some items/services to continue','info');
			return false;
		}
		if(discount>subtotal)
		{
			swal('Discount Limit','Discount must be equals or less subtotal','warning');
			return false;
		}
		// if(payment_type=="")
		// {
		// 	swal('Payment Type','Please choose a payment type','info');
		// 	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 service_name=[];
		var service_price=[];
		var service_qty =[];
		var service_total=[];
		$('.li_prd_srv').each(function(){
			service_name.push($(this).text());
			service_price.push($(this).closest('tr').find('.li_srv_price').text());
			service_qty.push($(this).closest('tr').find('.li_srv_qty').text());
			service_total.push($(this).closest('tr').find('.li_srv_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('customer_email',customer_email);
		// form_data.append('delivery_date',delivery_date);
		form_data.append('purchases',purchases);
		form_data.append('itm_subtotal',itm_subtotal);
		form_data.append('srv_subtotal',srv_subtotal);
		form_data.append('subtotal',subtotal);
		// form_data.append('payment_type',payment_type);
		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('service_name',JSON.stringify(service_name));
		form_data.append('service_price',JSON.stringify(service_price));
		form_data.append('service_qty',JSON.stringify(service_qty));
		form_data.append('service_total',JSON.stringify(service_total));
		form_data.append('notes',notes);
		form_data.append(token_name,token_value);
		$.ajax({
			url:base_url+'quotations/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+'quotations/invoice/'+res[2]);
					$('#prd_stk_tbody').html("");
					$('#srv_tbody').html("");
					$('#purchase_total').text('');
					$('#customer_contact').val('');
					$('#customer_name').val('');
					// $('#delivery_date').val('');
					$('#customer_email').val('');
					$('#item-subtotal').text('0.00');
					$('#service-subtotal').text('0.00');
					$('#subtotal').text('0.00');
					// $('#payment_type').val('');
					$('#grandtotal').text('0.00');
					$('#discount').val('');
					$('#notes').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
