$(document).ready(function(){
let urlString = window.location.search;
	let paramString = urlString.split('?')[1];
let queryString = new URLSearchParams(paramString);

for (let pair of queryString.entries()) {
	var value = pair[1];
}
if(value){
	$("#myModal").modal("show");
}
//getParty();
 getProduct();

   ///----------------for getting variable from link---------------------

  $.urlParam = function(name){
    var results   =   new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results==null) {
            return null;
    }
    return decodeURI(results[1]) || 0;
  }

  $('#addButton').on('click',function(){
     $("#addButton").prop('disabled', true);
     var pid                      =     $('#pid').val();
      var purchase_date            =     $('#purchase_date').val();
      var purchase_party           =     $('#purchase_party').val();
      var purchase_product         =     $('#purchase_product').val();
      var drum_qty   =     $('#drum_qty').val();
      var total_drum_qty    =     $('#total_drum_qty').val();
      var purchase_rate     =     $('#purchase_rate').val();
      var purchase_condition            =     $('#purchase_condition').val();
      var purchase_dalal         =     $('#purchase_dalal').val();
      var purchase_remarks         =     $('#purchase_remarks').val();
      var returnvalue=0;
      if(purchase_date == ''){
           $("#error_message_modal").show();
          $("#purchase_date").focus();
          $('#error_message_modal').html("Please fill compulsory fields!");
          setTimeout(function(){  
                     $('#error_message_modal').fadeOut("Slow");  
                }, 2000);
          return false;
      }
      if(purchase_product == 0){
           $("#error_message_modal").show();
          $("#purchase_product").focus();
          $('#error_message_modal').html("Please fill compulsory fields!");
          setTimeout(function(){  
                     $('#error_message_modal').fadeOut("Slow");  
                }, 2000);
          return false;
      }
      if(purchase_party == 0){
           $("#error_message_modal").show();
          $("#purchase_party").focus();
          $('#error_message_modal').html("Please fill compulsory fields!");
          setTimeout(function(){  
                     $('#error_message_modal').fadeOut("Slow");  
                }, 2000);
          return false;
      }
      if(purchase_rate == 0 || purchase_rate==''){
           $("#error_message_modal").show();
          $("#purchase_rate").focus();
          $('#error_message_modal').html("Please fill compulsory fields!");
          setTimeout(function(){  
                     $('#error_message_modal').fadeOut("Slow");  
                }, 2000);
          return false;
      }
      else{
      
        $.ajax({
          url : DOMAIN+"/includes/purchasePageProcess.php",
          method : "POST",
          data : {addFunctionRequest:1,
                    pid,
                    purchase_date,
                    purchase_party,
                    purchase_product,
                    drum_qty,
                    total_drum_qty,
                    purchase_rate,
                    purchase_condition,
                    purchase_dalal,
                    purchase_remarks,
                    tokenSecretUser
                },
          //dataType : "json",
          async: false,
          beforeSend: function() { 
              //$("#addButton").prop('disabled', true); // disable button
            },
          success : function(data){
             //console.log(data);
             data= data.trim() ;
             data= data.toString() ;
             if (data) {
              manageListFunction(1);
              $("#success_message_modal").show();
                if(pid == 0){
                  $('#success_message_modal').fadeIn().html("Added Successfully..!");  
                }else{
                  $('#success_message_modal').fadeIn().html("Updated Successfully..!");
                }
                
                  setTimeout(function(){  
                      $("#addButton").prop('disabled', false);
                     $('#success_message_modal').fadeOut("Slow");  
                     $('#myModal').modal('toggle');
                     
                    
                }, 2000);
             } else {
               $("#error_message_modal").show();
                $('#error_message_modal').html("Server not responding..Please try again"); 
                 setTimeout(function(){  
                     $('#error_message_modal').fadeOut("Slow");  
                }, 2000);
             }  
          }
        })
      }
  });

  function getParty(){    
    $.ajax({
      url : DOMAIN+"/includes/purchasePageProcess.php",
      method : "get",
      
      async: false,
      data : {getParty:1},
      success : function(data){
       // console.log(data);
          var option = "<option value='0'>Choose</option>"
          $('#party_list').html(data);
        
        }
    })
  }
  function getProduct(){    
    $.ajax({
      url : DOMAIN+"/includes/purchasePageProcess.php",
      method : "get",
      
      async: false,
      data : {getProduct:1},
      success : function(data){
       // console.log(data);
          var option = "<option value='0'>Choose</option>"
          $('#purchase_product').html(option+data);
        
        }
    })
  }
 
 $("body").delegate(".editButton","click",function(){
    var eid     =     $(this).attr("eid");
    fillFormFunction(eid)
  })
  function fillFormFunction(rid){    
    $.ajax({
      url : DOMAIN+"/includes/purchasePageProcess.php",
      method : "get",
      dataType : "json",
      async: false,
      data : {fillFormRequest:1,id:rid},
      success : function(data){

        $('#pid').val(data["int_sauda_id"]);
        $('#purchase_date').val(data["dat_sauda"]);
        $('#purchase_party').val(data["party_name"]);
        $('#purchase_product').val(data["int_product_id"])
        $('#drum_qty').val(data["int_drums"]);
        $('#total_drum_qty').val(data["dec_quantity"]);;
        $('#purchase_rate').val(data["dec_rate"]);
        $('#purchase_condition').val(data["txt_condition"]);
        $('#purchase_dalal').val(data["txt_dalal"]);
        $('#purchase_remarks').val(data["txt_remark"]);
        }
    })
  }

  $("#drum_qty").blur(function(){
	 var drum_qty   =     $('#drum_qty').val();
           $('#total_drum_qty').val(drum_qty*180);
	  
	});

  $('#dltAllRecordsid').on('click',function(){
   var records = [];

    // Get checked checkboxes
    $('#myTable input[type=checkbox]').each(function() {
      if (jQuery(this).is(":checked")) {
        var id = this.id;
        var splitid = id.split('_');
        var postid = splitid[1];
        records.push(postid);
        
      }
    });
   
   if(records.length > 0){ 
  
         $.ajax({
           url : DOMAIN+"/includes/purchasePageProcess.php",
           method : "get",
           data : {deleteSelectedRequest:1,records:records},
           async: false,
           success : function(data){
            if (data!=0) {
              $('#myModalAllDelete').modal('toggle');
               $("#success_message").show();
              $('#success_message').fadeIn().html(" Deleted Successfully..!");  
                setTimeout(function(){  
                     $('#success_message').fadeOut("Slow");  
                }, 2000);
              manageListFunction(1);
              manageCardFunction(1);
            }else{
              $('#myModalAllDelete').modal('toggle');
              $("#error_message").show();
              $('#error_message').html("Cannot be Deleted"); 
               setTimeout(function(){  
                     $('#error_message').fadeOut("Slow");  
                }, 2000);
            }
               
           }
         })
       
     }
  });

   
  $("body").delegate("#deleteButton","click",function(){
    var did       =       $("#did").val();
   
      $.ajax({
        url : DOMAIN+"/includes/purchasePageProcess.php",
        method : "get",
       // dataType : "json",
        data : {deleteRequest:1,id:did},
        success : function(data){
        //console.log(data);
          if (data!=0) {
            $('#myModalDelete').modal('toggle');
            $("#success_message").show();
            $('#success_message').fadeIn().html(" Deleted Successfully..!");  
              setTimeout(function(){  
                   $('#success_message').fadeOut("Slow");  
              }, 2000);
            manageListFunction(1);
            manageCardFunction(1);
          }else{
            $('#myModalDelete').modal('toggle');
            $("#error_message").show();
            $('#error_message').html("Cannot be Deleted!! This record is used in other files."); 
             setTimeout(function(){  
                   $('#error_message').fadeOut("Slow");  
              }, 2000);
          }
            
        }
      })
    
  });

  manageListFunction(1);
  function manageListFunction(pn){
     search_option=$('#search_option').val();
    $.ajax({
      url : DOMAIN+"/includes/purchasePageProcess.php",
      method : "get",
      data : {manageListRequest:1,search_option:search_option,pageno:pn},
      async: false,
      success : function(data){
        $("#get_list").html(data); 
          
      }
    })
    //countRowsToAdjustHeight();
  }
  $("#search_option").keyup(function(){
      manageListFunction(1);
  });
  $('#search').on('click',function(){
	  manageListFunction(1);
  });
  manageCardFunction(1);
  function manageCardFunction(pn){
   search_option=$('#search_option').val();
    $.ajax({
      url : DOMAIN+"/includes/purchasePageProcess.php",
      method : "get",
      data : {manageCardRequest:1,search_option:search_option,pageno:pn},
      async: false,
      success : function(data){
        $("#get_card").html(data);   
      }
    })
  }
  $("body").delegate(".page-link","click",function(){
    var pn      =       $(this).attr("pn");
    manageListFunction(pn);
    manageCardFunction(pn);
  })
   function searchShowListFunction(option){
      var option      =   $('#search_option').val();
      $.ajax({
        url : DOMAIN+"/includes/purchasePageProcess.php",
        method : "get",
        data : {manageListRequest:1,search_option:option,pageno:1},
        async: false,
        success : function(data){
          $("#get_list").html(data);  

        }
      })
  }
  function searchShowCardFunction(option){
      var option      =   $('#search_option').val();
      $.ajax({
        url : DOMAIN+"/includes/purchasePageProcess.php",
        method : "get",
        data : {manageCardRequest:1,search_option:option,pageno:1},
        async: false,
        success : function(data){
          $("#get_card").html(data);  

        }
      })
  }

    $("body").delegate("#filterAllRecordsid","click",function(){ 
        
        searchShowListFunction();
        searchShowCardFunction();
  });
  function searchBox(search_option1,search_option2,search_option3){
    $.ajax({
      url : DOMAIN+"/includes/purchasePageProcess.php",
      method : "get",
      data : {manageListSearchRequest:1,
              search_option1:search_option1,
              search_option2:search_option2,
              search_option3:search_option3,
              pageno:1
           },
      async: false,
      success : function(data){
        $("#get_list").html(data);  

      }
    })
  }
  function searchBoxCards(search_option1,search_option2,search_option3){
    $.ajax({
      url : DOMAIN+"/includes/purchasePageProcess.php",
      method : "get",
      data : {manageCardSearchRequest:1,
              search_option1:search_option1,
              search_option2:search_option2,
              search_option3:search_option3,
              pageno:1
           },
      async: false,
      success : function(data){
        $("#get_card").html(data);  

      }
    })
  }
  $("body").delegate("#btnSearch"," click",function(){  
      var search_option1         =   $('#search_option1').val();
      var search_option2       =   $('#search_option2').val();
      var search_option3           =   $('#search_option3').val();
      searchBox(search_option1,search_option2,search_option3);
      searchBoxCards(search_option1,search_option2,search_option3);
  });
  $('#btnReset').on('click',function(){
      $(' input:text').val("");
      manageListFunction(1);
      manageCardFunction(1);
  })
  $('#myModal').on('hidden.bs.modal', function(e) {
       $('#pid').val('0');
        $("#myForm").trigger( "reset" );
        $("#myForm").removeData();
        $("#myFormDrums").trigger( "reset" );
        $("#myFormDrums").removeData();
  });

  
  $('.pdf_download').click(function(){	
	  var report_type				=		'Un';
	  var product_id				=		'Un';
	  var page_name 				=	'Sauda'
	  var year            			=     'Un';
      var month           			=     'Un';
      var gst_type        			=     	'Un';
      var gst_type_2      			=     	'Un';
      var party_id			=		'Un';
      var dt_from             		=      'Un';
      var dt_to              		=       'Un';
	  window.open(DOMAIN+"/includes/pdfDownload.php?page_name="+page_name+"&report_type="+report_type+"&product_id="+product_id+"&year="+year+"&month="+month+"&gst_type="+gst_type+"&gst_type_2="+gst_type_2+"&party_id="+party_id+"&dt_from="+dt_from+"&dt_to="+dt_to,  '_blank');
	   
	  })

	///----------------for getting variable from link---------------------

	$.urlParam = function(name){
    var results 	= 	new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results==null) {
       			return null;
    }
    return decodeURI(results[1]) || 0;
	}
})