 var saleModule = (function () { 

$('.addProduct-sale').on('click',function(){

    var productID = $('#product-select-box').val();
    var checkCustomer = $('.customerName-select').val();
    if(checkCustomer) {  
    $.ajax({
        url: base_url+'fetchAjaxData/fetchSaleDetailProductName.php?pid='+productID,
        dataType: "json",
        type: 'GET',        
        success: function(data) {
         //console.log(data[0]); 
         
            var trlength = $('#saleDetailsAdd tbody tr:last').length;
            if(trlength == 0) {

                trlength = 1;

            } else {

                trlength = $('#saleDetailsAdd tbody tr:last').attr('id');
                
                trlength = parseInt(trlength)+parseInt(1);

            }

            var saleDetails = '<td class="product_name">'+data[0].productname+'<input class="form-control productid" name="productID[]"  value="'+productID+'" type="hidden"></td>'
			
			
            
            saleDetails +='<td>'+$(".eqty-input").val()+'<input class="form-control eqtyinput" name="eqtyinput[]" type="hidden" value="'+$(".eqty-input").val()+'" ></td>';
            
            saleDetails +='<td>'+$("#prate").val()+'<input class="form-control prateinput" name="prateinput[]" type="hidden" value="'+$("#prate").val()+'" ></td>';
            
           
            saleDetails +='<td>'+$("#netamt").val()+'<input class="form-control salenetamt" name="salenetamt[]" type="hidden" value="'+$("#netamt").val()+'" ></td>';

            saleDetails +='<td><input type="button" class="btn btn-default removeProductDetails" id="removeProductDetails" value="-"></td>';

            $("#saleDetailsAdd tbody").append("<tr id='"+trlength+"'></tr>");
            $("#saleDetailsAdd tbody tr:last").append(saleDetails);

           $('#product-select-box').val('');
			$('#product-select-box select option:selected').removeAttr('selected');
            //$('#product-select-box option[value="'+productID+'"],option:not([value])').remove();

            $('#product-select-box option[value="'+productID+'"],option:not([value])').attr("disabled","disabled");


           

            var saleTNetAmt =(parseFloat($(".saleT-NetAmt").html())+parseFloat($("#netamt").val())).toFixed(2);
            $(".saleT-NetAmt").html(saleTNetAmt+'<input class="form-control saleT-NetAmt" name="totalNetamt" type="hidden" value="'+saleTNetAmt+'">');
            

            $("#prate").val('');
            
            $(".eqty-input").val('');
            
            $("#netamt").val('');
            //$('#product-select-box option').attr('disabled',false);
            
            
        },
        error: function() {
            console.log('An error has occurred: Please check this file fetchSaleDetailProductName.php');
        }        
     }); 

    } else {
        alert("Please Select Customer & Remove the saledetails values....!");
        $('#product-select-box').val('');
        $("#prate").val('');
       
        $(".eqty-input").val('');
       
        $("#netamt").val('');

    }

    

});

$('body').on('click', 'input.removeProductDetails', function(){

    console.log("test:"+$(this).closest('tr').attr('id'));
    var removeTRID = $(this).closest('tr').attr('id');  
    $("#"+removeTRID).next().val();
    var salenetamt = $(this).closest('td').prev().find('.salenetamt').val();

    var sgstinput = $(this).closest('td').prev().prev().find('.sgstinput').val();

    var cgstinput = $(this).closest('td').prev().prev().find('.cgstinput').val();

    var amtinput = $(this).closest('td').prev().prev().prev().find('.amtinput').val();


    var saleTAmount =(parseFloat($(".saleT-Amount").html())-parseFloat(amtinput)).toFixed(2);
    $(".saleT-Amount").html(saleTAmount+'<input class="form-control saleT-Amount" name="totalamt" type="hidden" value="'+saleTAmount+'">');

    var saleTGST =(parseFloat($(".saleT-GST").html())-( parseFloat(sgstinput)+parseFloat(cgstinput)    ) ).toFixed(2);
    $(".saleT-GST").html(saleTGST+'<input class="form-control saleT-GST" name="totalGSTamt" type="hidden" value="'+saleTGST+'">');

    var saleTNetAmt =(parseFloat($(".saleT-NetAmt").html())-parseFloat(salenetamt)).toFixed(2);
    $(".saleT-NetAmt").html(saleTNetAmt+'<input class="form-control saleT-NetAmt" name="totalNetamt" type="hidden" value="'+saleTNetAmt+'">');


 
    

    //var gstinput = $(this).closest('td').prev().prev().prev().prev().find('.gstinput').val();

    //var prateinput = $(this).closest('td').prev().prev().prev().prev().prev().find('.prateinput').val();

    //var eqtyinput =$(this).closest('td').prev().prev().prev().prev().prev().prev().find('.eqtyinput').val();

    var productid = $(this).closest('td').prev().prev().prev().prev().prev().prev().prev().find('.productid').val();


    $('#product-select-box option[value="'+productid+'"],option:not([value])').removeAttr("disabled");

    $("#"+removeTRID).remove(); 

});

function removeProduct(current_id) {
    //$("#"+current_id+"_saledetails").remove();
    $("#"+current_id).remove();
}


$('.customerName-select').on('change',function(){

    var CID = $(this).val();
	
	//alert(CID);
	
console.log(CID+"  ---          ---"+$("#saleDetailsAdd tbody tr").length);
    if(CID) {
        
        
          $.ajax({
            url: base_url+'fetchAjaxData/fetchCustomerAddress.php?cid='+CID,
            dataType: "json",
            type: 'GET',        
            success: function(data) {
               
               $("#caddress").val(data[0].caddress);
			    //$("#area").val(data[0].area);
		$("#area_tamil").val(data[0].area_tamil);
               $("#del_address").val(data[0].caddress);
               
            },
            error: function() {
                console.log('An error has occurred');
            },
            
         });
       
    } else {
    
            alert("Please Select Customer...!");
            $("#caddress").val('');
    }
});


$('.customerName-select').on('change',function(){

    var cid = $(this).val();
	var tray_product=$("#tray_product").val();
	
	
	  $.ajax({  
                     url:"fetchAjaxData/fetch_pending_amount.php",  
                     method:"POST",  
                     data:{cid:cid,pid:tray_product},
                     success:function(data)  
                     {  
					      //alert(data);
						  var data2 = data.split("||");
                          $('#pending_tamount').val("");  
                          $('#pending_tamount').val(data2[0]);
						  
						 
                  $("#pending_tray").val(data2[1]);
						  
						 
                    //$('#availqty').html(data2[2]);
                         
                         
                     }  
                });  
	

});



$('#area').on('change',function(){
								
	var query=$(this).val();
	$("#area_tamil").val("");
	  let purchaseString = '';
	 //alert(query);
	             $.ajax({  
                     url:"pick_customer.php",  
                     method:"POST",  
                     data:{query:query},
                     success:function(data)  
                     {  
					      //alert(data);
						  var data2 = data.split("||");
						    
						  
                          purchaseString = '<option value="">--Select Customer --</option>'; 
                          JSON.parse(data2[0]).map((list)=>{
                            purchaseString += `<option value=${JSON.stringify(list.cid)}>${list.cname}</option>`;
                          });
						  $('.customerName-select').html(purchaseString);
						 
                     }  
					
                });  							
											  
});											  

$('#product-select-box').on('change',function(){

    var CID = $('.customerName-select').val(); 
    if(CID) {
    var str = $(this).val();
    if(str) {
        $("#prate").val('');
       
        $(".eqty-input").val('');
        
      
        $("#netamt").val('');    

      $.ajax({
        url: base_url+'fetchAjaxData/fetchSaleDetail.php?pid='+str+'&cid='+CID,
        dataType: "json",
        type: 'GET',        
        success: function(data) {
           
           $("#prate").val(data[0].purchase_rate);
          $("#availqty").html("Available QTY:" + data[0].availqty);
           
        },
        error: function() {
            console.log('An error has occurred');
        },
        
     });
    }
    else {
        console.log("please atlest one product");
    }

    } else {

        alert("Please Select Customer...!");
        $('#product-select-box').val('');

    }
});

$(".eqty-input").on("blur",function() {


     

       
    var eqty    = $(this).val();

    var productID = $("#product-select-box").val();
    if(productID>0){

    if(eqty>0) {
   
    var prate   = $("#prate").val();

    
    //var temp_amt = parseFloat(eqty)+parseFloat((parseInt(eqty)*parseInt(pgst))/100).toFixed(3);

    var temp_amt = parseFloat(eqty)*parseFloat(prate);

    

    var temp_netamount  = parseFloat(parseFloat(temp_amt)).toFixed(2);

    
    $("#netamt").val(temp_netamount);

    }
    else {
        alert("Please enter Vaild Number");
    }
    }
    else {
        alert("Please select product");
    }
    
});

/*$(".eqty-input").keypress(function (e) {
    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
        return false;
    }
});*/

$(".productrate").on("blur",function() {

    var prate    = $(this).val();
    if(prate>0) {
    var productID = $("#product-select-box").val();
    if(productID>0){
        var eqty    = $("#eqty").val(); 
    if(eqty>0) {

        
        var pgst='',temp_amt ='', temp_gst ='', temp_cgst ='',temp_netamount  ='';
        pgst    = $("#gst").val();
        //var prate   = $(this).val();
        var temp_amt = parseFloat(eqty)*parseFloat(prate);

       

        var temp_netamount  = parseFloat(parseFloat(temp_amt)).toFixed(2);

       
        $("#netamt").val(temp_netamount);

    }
    else {
        alert("Please enter Vaild Number");
    }
    }
    else {
        alert("Please select product");
    }
    }
    else {

        
        $("#netamt").val('');

    }
    
});









})();
