function sub_total()
{
	var totals=0;
	if($('.li_prd_total').length>0){
		$('.li_prd_total').each(function(e){
			totals +=parseFloat($(this).text());
		});
	}
	return totals;
}
function pedit_gtotal()
{
	var totals=0;
	$('.epur-total').each(function(e){
		totals +=parseFloat($(this).text());
	});
	$('#epur-gtotal').text(totals.toFixed(3));
}
$(document).ready(function(){
	
	$('#purchaseTable').DataTable({
		ajax: {
            url:  base_url+'purchases/show',
            type: "GET", // or 'POST' if needed
        },
        language: {
            lengthMenu: "_MENU_",
        },
        pageLength: 100,
        order: [],
        responsive: true,
    });

	$('#pinvoice-details').on('show.bs.modal',function(e){
		var invoice = e.relatedTarget.id;
		$('#invoice_number').text(invoice);
		var form_data = new FormData();
		form_data.append('invoice',invoice);
		$.ajax({
			url:base_url+'purchases/invoice-details',
			type:'POST',
			processData:false,
			contentType: false,
			data:form_data,
			success:function(response)
			{
				var res = $.parseJSON(response)
				$('#pinvoice-mbody').html('');
				$('#pinvoice-mbody').html(res[0]);
			}
		});
	});


	$('#purchase-edit-modal').on('show.bs.modal',function(e){
		var invoice = e.relatedTarget.id;
		$('#pedit_invoice_number').text(invoice);
		var form_data = new FormData();
		form_data.append('invoice',invoice);
		$.ajax({
			url:base_url+'purchases/invoice-edit-details',
			type:'POST',
			processData:false,
			contentType: false,
			data:form_data,
			success:function(response)
			{
				var res = $.parseJSON(response)
				$('#pedit-mbody').html('');
				$('#pedit-mbody').html(res[0]);
			}
		});
	});
	
	$(document).on('keyup','.epur-price',function(e){
		var price = parseFloat($(this).val());
		var qty   = parseFloat($(this).closest('tr').find('.epur-qty').val());
		if(isNaN(price)){price=0;}
		if(isNaN(qty)){qty=0;}
		var total = price*qty;
		$(this).closest('tr').find('.epur-total').text(total.toFixed(3));
		pedit_gtotal();
	});

	$(document).on('keyup','.epur-qty',function(e){
		var price = parseFloat($(this).closest('tr').find('.epur-price').val());
		var qty   = parseFloat($(this).val());
		if(isNaN(price)){price=0;}	
		if(isNaN(qty)){qty=0;}
		var total = price*qty;
		$(this).closest('tr').find('.epur-total').text(total.toFixed(3));
		pedit_gtotal();
	});

	$('#btn-update-purchase').on('click',function(e){
		var invoice    = $('#pedit_invoice_number').text();
		var sub_total  = $('#epur-gtotal').text();
		var item_name  = [];
		var item_price = [];
		var item_qty   = [];
		$('.epur-item').each(function(e){
			item_name.push($(this).text());
			item_price.push($(this).closest('tr').find('.epur-price').val());
			item_qty.push($(this).closest('tr').find('.epur-qty').val());
		});
		var form_data = new FormData();
		form_data.append('invoice',invoice);
		form_data.append('sub_total',sub_total);
		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));
		$.ajax({
			url:base_url+'purchases/update',
			type:'POST',
			processData:false,
			contentType: false,
			data:form_data,
			success:function(response)
			{
				var res = $.parseJSON(response)
				if(res[0]==1)
				{
					notify('success','Purchase updated');
				}
				else
				{
					notify('success','Error updating purchases')
				}
				$('#purchaseTable').DataTable().ajax.reload();
			}
		});
	});

	$('#purchaseTable').on('click','.ifdel',function(e){
	  e.preventDefault();
	  var href = $(this).attr('href');
	  if(typeof(href) != "undefined" && href !== null)
	  {
		  swal({
		      title:"Are you sure?",
		      text: "You will not be able to recover this data!",
		      type: "warning",
		      showCancelButton: true,
		      confirmButtonClass: 'btn-danger btn-md waves-effect waves-light',
		      confirmButtonColor: "#DD6B55",
		      confirmButtonText: "Yes, delete it!",
		      cancelButtonText: "No, cancel it!",
		      closeOnConfirm: true,
		      closeOnCancel: true
		  }, function (isConfirm) {
		      if (isConfirm) 
		      {
		    	window.location=href;
		      } 
		      else 
		      {
		          return false;
		      }
		  });
	  }
	});

	$("#prd_stk").autocomplete({
       source: base_url+'purchases/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 prd_price   = $('#prd_price').val();
		var flag=0;	
		if(prd_stk==""){return false;}
		if(prd_stk_qty==""){return false;}
		if(prd_price==""){return false;}

		var form_data = new FormData();
		form_data.append('prd_stk',prd_stk);
		$.ajax({
			url:base_url+'purchases/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">'+prd_price+'</td><td class="li_prd_total">'+eval(prd_stk_qty*prd_price)+'</td><td><a href="#" class="tr-rmv"><i class="fa fa-close"></a></td></tr>');
						$('#spl_hid').val($('#prd_spl').val());
						$('#prd_spl').prop('disabled',true); 
						$('#sub_total').text(sub_total().toFixed(2));
						recalcId();
				}
				else
				{
					flag=1;
				}
			}
		});
		if(flag==1){return false;}
		$('#prd_stk').val("");
		$('#prd_stk_qty').val("");
		$('#prd_price').val("");
		$('#prd_stk').focus();
	});

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

	$('#btn-process-items').on('click',function(){
		var spl =$('#spl_hid').val();
		var subtotal = parseFloat(sub_total().toFixed(2));
	
		var purchase_date=$('#purchase_date').val();
		var advance = $('#prd_advance').val();
		var ptype	= $('#prd_ptype').val();
		var pcheque = $('#prd_cheque').val();
		var pnotes  = $('#pnotes').val();
		if(isNaN(subtotal)){subtotal=0;}
		if(isNaN(advance)){advance=0;}
		var item_name=[];
		var item_price=[];
		var item_qty =[];
		var item_total=[];
		$('.li_prd_stk').each(function(){
			item_name.push($(this).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());
		});
		if(item_name.length==0)
		{
			swal('Add Some Items','Please add some items to continue','info');
			return false;
		}
		if(advance>0 && ptype=="")
		{
			swal('Payment Type','Payment type required when paying advance','info');
			return false;	
		}
		if(ptype=='cheque' && pcheque=="")
		{
			swal('Cheque Number','Cheque Number required when using cheque','info');
			return false;		
		}
		if(advance>subtotal)
		{
			swal('Incorrect Advance','Advance cannot be more than the total','info');
			return false;	
		}
		
		var form_data = new FormData();
		form_data.append('spl',spl);
		form_data.append('subtotal',subtotal);
		form_data.append('purchase_date',purchase_date);
		form_data.append('advance',advance);
		form_data.append('ptype',ptype);
		form_data.append('pcheque',pcheque);
		form_data.append('pnotes',pnotes);
		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));
		
		$.ajax({
			url:base_url+'purchases/process-items',
			type:'POST',
			processData:false,
			contentType: false,
			data:form_data,
			success:function(response)
			{
				var res = $.parseJSON(response)
				$('#my_csrf').val(res[0]);
				if(res['msg']==1)
				{
					notify('success','Purchase Processed Successfully');
					$('#prd_stk_tbody').html("");
					$('#subtotal').text(0);
					$('#prd_spl').prop('disabled',false);
					$('#prd_spl').val("");
					$('#sub_total').text("");
					$('#purchase_date').val("");
					$('#prd_advance').val("");
					$('#prd_ptype').val("");
					$('#prd_cheque').val("");
					window.open(base_url+'purchases/invoice/'+res['invoice']);
				}
				else
				{
					notify('error','Error Processing Purchase');
				}
			}
		});
	});

	 $("#purchaseTable").on("click", ".ifdel", function (e) {
        e.preventDefault();
        invoice = $(this).attr("data-uid");
        swal(
            {
                title: "Are you sure?",
                text: "You will not be able to recover this data!",
                type: "warning",
                showCancelButton: true,
                confirmButtonClass:
                    "btn-danger btn-md waves-effect waves-light",
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "Yes, delete it!",
                cancelButtonText: "No, cancel it!",
                closeOnConfirm: true,
                closeOnCancel: true,
            },
            function (isConfirm) {
                if(isConfirm){
                    $.ajax({
                        url: base_url + "purchases/delete",
                        type: "POST",
                        data: { invoice: invoice },
                        success: function (response) {
                            if (response == 1) {
                                notify("success", "Deleted");
                            } else {
                                notify("error", "Error deleting please try again");
                            }
                        },
                        error: function (msg) {
                            let res_errors = "";
                            $.each(msg.responseJSON.errors, function (key, value) {
                                res_errors += value + "<br>";
                            });
                            notify("warning", res_errors);
                        },
                    }); //End of Ajax Request
                    $("#purchaseTable").DataTable().ajax.reload();
                }

            }
        ); 	
    });
});// End Ready Function
