getId=(idname)=>{
    return document.getElementById(idname);
}
getQuery=(name)=>{
    return document.querySelectorAll(name);
}
let emptyWeight = getId("emptyWeightAdd");
    let loadWeight = getId("loadWeightAdd");
    let netWeight = getId("netWeightAdd");
    let netQty = getId("netQtyAdd");
    let netQtyOri = getId("netQtyOri");
    let unitConversion = getId("unitConversion");
    let totalAmtAdd = getId("totalAmtAdd");
    let priceAdd = getId("priceadd");
    let customer =getId("customerAdd");
    let product = getId("productAdd");
    let vehicle = getId("vehicleAdd");
    let chakka = getId("chakkaType");
    let requiredFeild = getQuery(".required");
    let billType = getId("billType");
let requiredInput = getQuery("input");
let einvoiceSection = getId('einvoiceSection');
let validateButton = getId("validationButton");
einvoiceSection.style.display = 'none';
billType.addEventListener("change",function(e){
    e.target.value == 'gst' ? (getId("form1").action = "insertsecondtrans.php",einvoiceSection.style.display = 'block')
                              : (getId("form1").action = "insertsecondtrans_est.php",einvoiceSection.style.display = 'none');
                              console.log(product.value,'product');
                              product.value != 0 ? handleProductRate() : ""; 
    if(e.target.value == 'est'){
        requiredFeild.forEach((data)=>{
            (data.dataset.gst=='true') ? (data.classList.remove("required"),data.classList.add("required-gst")) : data.classList.add("required");
            console.log('data',data);
        });
    }else{
        let requiredFeildGst = getQuery(".required-gst");
        requiredFeildGst.forEach((data)=>{
            (data.dataset.gst=='true') ? data.classList.add("required") : data.classList.add("required");
            console.log('data',data);
        });
    }

    });
handleVehicle=(vehicle)=>{
    $.ajax({
        type:'POST',
        url:'ajaxpath1/fetch_vehicle_second.php',
        data:{vehicle:vehicle},
        success:function(data){
        $("#vehicleAdd").html(data);
        console.log(data);
        }
       });  
};
handleCustomer=(customer,customername)=>{
    $.ajax({
        type:'POST',
        url:'ajaxpath1/fetch_customer_second.php',
        data:{customer:customer,customername:customername},
        success:function(data){
        $("#customerAdd").html(data);
        console.log(data);
        }
       });  
};
handleProduct=(product,productname)=>{
    $.ajax({
        type:'POST',
        url:'ajaxpath1/fetch_product_second.php',
        data:{product:product,productname:productname},
        success:function(data){
        $("#productAdd").html(data);
        console.log(data);
        }
       });  
};
handleChakka=(vehicle,chakka)=>{
    $.ajax({
        type:'POST',
        url:'ajaxpath1/fetch_chakka_type_second.php',
        data:{vehicleno:vehicle,chakka:chakka},
        success:function(data){
        $("#chakkaType").html(data);
        console.log(data);
        }
       });  
};
handleLoadType=(data)=>{
    let load_type = "";
    if(data=="Load")
    {
         load_type=`<option value='Load'>In</option>
         <option value='Empty'>Out</option>
         `;
    }
    if(data=="Empty")
    {
         load_type=` <option value='Empty'>Out</option>
         <option value='Load'>In</option>
         `;
    }
        getId("loadType").innerHTML=load_type;
};
handleCalculation=()=>{
    if(loadWeight.value!='' && emptyWeight.value!=''){
    if(Number(emptyWeight.value)>=Number(loadWeight.value))
    {
        netWeight.value=emptyWeight.value-loadWeight.value;
    }
    if(Number(emptyWeight.value)<= Number(loadWeight.value))
    {
        netWeight.value=loadWeight.value-emptyWeight.value;
    }
    netQty.value=(netWeight.value/unitConversion.value).toFixed(2);
    netQtyOri.value=(netWeight.value/unitConversion.value).toFixed(2);

    handleTotalAmt();
}
}
handleLimitValidation=()=>{
    if(getId("loadType").value=="Empty"){
        if(Number(totalAmtAdd.value)>Number(getId("limitValue").value))
        {
            console.log("yes");
            getId("creditButton").click();
        }
        }
        if(getId("loadType").value=="Load"){
            if(getId("advanceLimitValue").value!=0){
            if(Number(totalAmtAdd.value)>Number(getId("limitValue").value))
            {
                
                getId("alertAdvance").click();
            }
        }
            }
}
handleTotalAmt=()=>{
    totalAmtAdd.value = (netQty.value * priceAdd.value).toFixed(2);
    console.log(getId("loadType").value);
    console.log(getId("limitValue").value); 
}
emptyWeight.addEventListener("keyup",function(){
 handleCalculation();
});
loadWeight.addEventListener("keyup",function(){
 handleCalculation();
});
netWeight.addEventListener("keyup",function(){
handleCalculation();
 });
 priceAdd.addEventListener("keyup",function(){
 handleCalculation();
 });
 netQty.addEventListener("keyup",function(){
handleTotalAmt();
});
emptyWeight.addEventListener("blur",function(){
   handleLimitValidation();
   });
   loadWeight.addEventListener("blur",function(){
    handleLimitValidation();
   });
   netWeight.addEventListener("blur",function(){
    handleLimitValidation();
    });
    priceAdd.addEventListener("blur",function(){
        handleLimitValidation();
    });
    netQty.addEventListener("blur",function(){
        handleLimitValidation();
   });
handleProductRate=()=>{
    let customerAdd = getId("customerAdd").value;
    let productAdd = getId("productAdd").value;
	 let bill_jtype = getId("billType").value;
    $.ajax({
        type:'POST',
        url:'ajaxpath1/fetch_rate_second.php',
        data:{customer:customerAdd,product:productAdd},
        success:function(data){
        let output = data.split("||");
        console.log(data);
        $("#productnameadd").val(output[1]);
        $(".productdisplay").html(output[1]);
        $(".pricedisplay").html(billType.value == 'gst' ? output[0] : output[3]);
		 $(".bill_jtype").html(bill_jtype);
        $("#unitConversion").val(output[2]);
        $("#priceshowbutton").click();
         $("#priceadd").val(billType.value == 'gst' ? output[0] : output[3]);
        $("#priceaddori").val(billType.value == 'gst' ? output[0] : output[3]);
        handleCalculation();
        }
       });  
}
handleBlockDate=()=>{
    let customerAdd = getId("customerAdd").value;
  let loadType = getId("loadType").value;
  let dateOri = getId("dateOri").value;
  console.log(dateOri);
  console.log(customerAdd);
  if(customerAdd!=''){
    $.ajax({
        type:'POST',
        url:'ajaxpath1/fetch_block_date.php',
        data:{customer:customerAdd,loadtype:loadType},
        success:function(data){
            console.log(data);
            var output= data.split("||");
            console.log(output);
        $("#blockDate").val(output[0]);
    //blockDateValidation(output[0]);
        $("#limitValue").val(output[1]);
        $("#advanceLimitValue").val(output[2]);
        if(loadType=="Empty")
        {
            if(output[0].trim()!='-'){
        if(dateOri>=output[0])
        {
            console.log("hai");
            getId("blockButton").click();
            return;
        }
    }
    }
        handleProductRate();
        }
       });  
    }  
}
 getId("loadType").addEventListener("change",function(e){
     console.log(e.target.value);
    if(e.target.value=="Load"){
        getId("limitName").innerHTML="Advance Limit";
        handleBlockDate();
    }
    if(e.target.value=="Empty"){
        getId("limitName").innerHTML="Credit Limit";
        handleBlockDate();
    }
 });
 feildValidate=()=>{
    let validateFunction = true;
    console.log('query',);
    let requiredValueForm =  getQuery(".requiredvalue");
       if(getQuery(".requiredvalue").length > 0){
        requiredValueForm.forEach((data)=>{
            if(data.value==""){
                data.classList.remove("requiredvalue");
                data.classList.add("required");
                validateFunction=false;
                console.log(data);
            }
            else{
                data.classList.remove("requiredvalue");
                data.classList.add("required");
            }
        });
       }
    let formRequired = getQuery(".required") ;
    formRequired.forEach((data)=>{
            if(data.value==""){
                data.classList.remove("required");
                data.classList.add("requiredvalue");
                validateFunction=false;
                console.log(data);
            }
            else{
                data.classList.remove("requiredvalue");
                data.classList.add("required");
            }
        });
       
console.log(validateFunction);
return validateFunction;
}
// validateButton.addEventListener("mouseover",function(){
//     handleLimitValidation();
// });
validateButton.addEventListener("click",function(){
    if(!feildValidate())
    {
        return;
    }
    console.log("yes");
    getId("submitButton").click();
});
requiredInput.forEach((data)=>{
    data.addEventListener("focus",function(){
        data.classList.remove("requiredvalue");
        data.classList.add("required");
    })
    data.addEventListener("keyup",function(){
        data.classList.remove("requiredvalue");
        data.classList.add("required");
    })
    data.addEventListener("change",function(){
        data.classList.remove("requiredvalue");
        data.classList.add("required");
    })
});
$(document).ready(function(){
$("#ticketselect").on("change",function(){
    let ticket = $(this).val();
	let bill_jtype = $('#billType').val();
	
	
	
    $.ajax({
        type:'POST',
        url:'ajaxpath1/fetch_second_trans_details.php',
        data:{ticket:ticket},
        success:function(data){
            let output = data.split("||");
            console.log(output);
            handleVehicle(output[0]);
            handleChakka(output[0],output[1]);
            handleCustomer(output[2],output[12]);
            handleProduct(output[3],output[9]);
            $("#productadddori").val(output[3]);
            $("#customeraddori").val(output[2]);
            $("#priceadd").val(billType.value == "gst"? output[4] : output[17]);
            $("#priceaddori").val(billType.value == "gst"? output[4] : output[17]);
            $("#emptyWeightAdd").val(output[5]);
            $("#blockDate").val(output[6]);
            if(output[8]=="Empty"){
                $("#limitName").html("Credit-Limit");
				if(bill_jtype == "gst"){
					$(".bill_jtype").html("GST-SALE");
            $(".bill_jtype").css("background-color", "#FFFFFF");//green
			$(".bill_jtype").css("color", "#00CC00");//green
			$(".bill_jtype").css("font-size", "56px");//green
        }
		
		if(bill_jtype == "est"){
			$(".bill_jtype").html("QUOTATIN-SALE");
            $(".bill_jtype").css("background-color", "#FFFFFF");//green
			$(".bill_jtype").css("color", "#0080FF");//green
			$(".bill_jtype").css("font-size", "56px");//green
        }
				
            }
            if(output[8]=="Load"){
                $("#limitName").html("Advance-Limit");
				$(".bill_jtype").html("Purchase");
				$(".bill_jtype").css("background-color", "#FFFFFF");//green
			$(".bill_jtype").css("color", "#FF0000");//green
			$(".bill_jtype").css("font-size", "56px");//green
            }
            $("#limitValue").val(output[7]);
            $("#advanceLimitValue").val(output[16]);
            handleLoadType(output[8]);
            $("#productnameadd").val(output[9]);
            $(".productdisplay").html(output[9]);
            $(".pricedisplay").html(billType.value == "gst"? output[4] : output[17]);
			 
            $("#unitConversion").val(output[13]);
            $("#cft").val(Number(output[10]).toFixed(2));
            $(".deliveryOri").val(output[14]);
            $("#dateOri").val(output[15]);
			 // $("#modeTrans").html(output[18]);
			  
			 // $("#modeTrans").append("<option>"+output[18]+"</option>");
			 // $("#upi_number").val(output[19]);
			  
            $("#priceshowbutton").click();
        }
       });  
});
$("#vehicleAdd").on('change',function(){
    let vehicleNo = $(this).val();
    $.ajax({
        type:'POST',
        url:'ajaxpath1/fetch_chakka_type.php',
        data:{vehicleno:vehicleNo},
        success:function(data){
        $("#chakkaType").html(data);
        }
       });  
});
$("#customerAdd").on('change',function(){
handleBlockDate();
});
$("#productAdd").on('change',function(){
    handleBlockDate();
    });
    $(".reloadPage").click(function(){
        location.reload();
        });
});
secondTranactionTable=()=>{
    var print = $("#print").html();
      var edit = $("#edit").html();
      let tableFilter = [];
      var toShow = $("#toShow").val();
      let filteredArray=[]
      var purchasedetails = "purchasedetails";
        $.ajax({
          type: "POST",
          dataType: "json",
          url: "ajaxpath/tktfetch.php",
          success: function (data) {
              data.map((list)=>{
                tableFilter.push(list)
              });
            $("#totalRow").html(data.length);
            tableCount = data.splice(0,toShow);
              $("#currentRow").html(tableCount.length);
              var tablerow="";
          //  console.log(typeof data);
            console.log(data);
            $("#tableTbody").html("");
            tableCount.map((data) => {
              tablerow += `<tr ><td>${data.editdate}</td>
                <td>${data.edittime}</td>
                <td style="background-color :${data.einvoicegenerated == '0' ? 'white' : '#8be996'};font-weight : 'bold'">${data.ticket}</td>
                <td style="background-color :${data.einvoicegenerated == '0' ? 'white' : '#8be996'};font-weight : 'bold'">${data.salescode}</td>
            <td>${data.productname}</td>
            <td>${data.cusname}</td>
            <td>${data.netweight}</td>
            <td>${data.totalamount}</td>
            ${
              print == 1
                ? `<td><a href="salesbillslip.php?print=${
                    data.salescode
                  } && table=${
                    data.tablename
                  }" target="_blank"><i class="fas fa-print"></i></a></td><?php }?>
            <?php if($per['dataprint'] =='1'){?> <td><a href="salesbillall.php?print=${
              data.salescode
            } && table=${data.tablename}" target="_blank">${
                    data.tablename != purchasedetails
                      ? '<i class="fas fa-print"></i>'
                      : ""
                  }</a></td>`
                : ""
            }
            ${
                print == 1 && data.tablename == 'second_transaction' && data.einvoicegenerated == '0'
                  ? `<td><a href="einvoice_json.php?print=${
                      data.salescode
                    } && table=${
                      data.tablename
                    }" target="_blank"><i class="fas fa-file"></i></a></td><?php }?></td>`
                  : print == 1 && data.tablename == 'second_transaction' && data.einvoicegenerated == '1' ? `<td><a href="https://my.gstzen.in${data.einvoiceid}"><i class="fas fa-file"></i></a></td>` :
                  `<td><a href="#"><i class="fas fa-file"></i></a></td>`
              }
            ${
              edit == 1
                ? `<td><a href="secondtransactionedit.php?edi=${data.ticket}&&table=${data.tablename}"><i class="fas fa-edit edit"></i></a></td></tr>`
                : ""
            }    `;
            });
            //console.log(tablerow);
            $("#tableTbody").append(tablerow);
            //console.log(tableFilter);
          },
        });
        $("#ticketFetch").keyup(function(){
            var searchValue = $("#ticketFetch").val();
            console.log(tableFilter);
          filtererArray =   tableFilter.filter((list)=>{
              return  list.cusname.toLowerCase().includes(searchValue)||list.ticket.toLowerCase().includes(searchValue)||list.editdate.toLowerCase().includes(searchValue) || list.salescode.toLowerCase().includes(searchValue)
            });
            console.log(filtererArray);
            tableCount = filtererArray.splice(0,toShow);
              $("#currentRow").html(tableCount.length);
              var tablerow="";
          //  console.log(typeof data);
           // console.log(data);
            $("#tableTbody").html("");
            tableCount.map((data) => {
              tablerow += `<tr><td>${data.editdate}</td>
                <td>${data.edittime}</td>
                <td style="background-color :${data.einvoicegenerated == '0' ? 'white' : '#8be996'};font-weight : 'bold'">${data.ticket}</td>
                <td style="background-color :${data.einvoicegenerated == '0' ? 'white' : '#8be996'};font-weight : 'bold'">${data.salescode}</td>
            <td>${data.cusname}</td>
            <td>${data.productname}</td>
            <td>${data.netweight}</td>
            <td>${data.totalamount}</td>
            ${
              print == 1
                ? `<td><a href="salesbillslip.php?print=${
                    data.salescode
                  } && table=${
                    data.tablename
                  }" target="_blank"><i class="fas fa-print"></i></a></td><?php }?>
            <?php if($per['dataprint'] =='1'){?> <td><a href="salesbillall.php?print=${
              data.salescode
            } && table=${data.tablename}" target="_blank">${
                    data.tablename != purchasedetails
                      ? '<i class="fas fa-print"></i>'
                      : ""
                  }</a></td>`
                : ""
            }
             ${
                print == 1 && data.tablename == 'second_transaction' && data.einvoicegenerated == '0'
                  ? `<td><a href="einvoice_json.php?print=${
                      data.salescode
                    } && table=${
                      data.tablename
                    }" target="_blank"><i class="fas fa-file"></i></a></td><?php }?></td>`
                  : `<td><a href="#"><i class="fas fa-file"></i></a></td>`
              }
            ${
              edit == 1
                ? `<td><a href="secondtransactionedit.php?edi=${data.ticket}&&table=${data.tablename}"><i class="fas fa-edit edit"></i></a></td></tr>`
                : ""
            }    `;
            });
            //console.log(tablerow);
            $("#tableTbody").append(tablerow);
           
        })
}
$(document).ready(function () {
    secondTranactionTable();
        $("#toShow").on('change',function(){
            secondTranactionTable();
        });
        
  });
  $("#getweightbutton").click(function(){
    $.ajax({
     type:'POST',
     url:'ajaxpath/search1.php',
     //data:{chakka:chakkaType,vehicleno:vehicleNo},
     success:function(data){
     $("#loadWeightAdd").val(data);
   //  $("#cftValueOri").val(data);
   handleCalculation();
   handleLimitValidation();
     }
    });  
});