function getTotalValue(array,toSum){
  let total = 0;
  if(array.length > 0){
    array.map((list)=>{
      total+=Number(list[toSum]);
    });
  }
  return total;
}
$(document).ready(function () {
    var reportValue=[];
    var tbodyValue = '';
    let fromd;
    let tod;
    let shift;
    $("#calender").click(function () {
      $(".spindis").show();
      fromd= $("#input_from").val();
      tod= $("#input_to").val();
      shift= $("#shift").val();
      //var timeFrom = $("#timefrom").val();
      //var timeTo = $("#timeto").val();
      //var tktFrom = $("#tktfrom").val();
        var vehicle = $("#vehicle").val();
        var modeTrans = $("#modeTrans").val();
        $.ajax({
          type: "GET",
          url: "ajaxreport1/fetch_transaction_report.php",
          dataType:"json",
          data: { tod: tod, fromd: fromd, shift:shift},
          success: function (data) {
            console.log(data);
            data.load.map((list)=>{
                reportValue.push(list);
           });
           tbodyValue = `<h3>Overall Report for (${fromd} to ${tod})</h3>`;
          let limitedReport= data.load;
          let transactionReport = {};
          let productCount = {};
          let cashHandlingDatas = {};
		  let productCount_tonn = {};
      let productCount_single_tonn = {};
      let productCount_single_unit = {};
          limitedReport.map((list)=>{
            if(productCount[list.productname]){
              productCount[list.productname] = (Number(list.netqty) + Number(productCount[list.productname])).toFixed(2);
            }else{productCount_single_tonn
              productCount[list.productname] = Number(list.netqty).toFixed(2);
            }
			
			if(productCount_tonn[list.productname]){
              productCount_tonn[list.productname] = (Number(list.tonn) + Number(productCount_tonn[list.productname])).toFixed(2);
            }else{
              productCount_tonn[list.productname] = Number(list.tonn).toFixed(2);
            }
			
			
            transactionReport[list.mode] = limitedReport.filter((listpro)=>{return listpro.mode == list.mode})
          })
          if(data.load_single.length > 0) {

            data.load_single.map((list)=>{
              if(productCount_single_tonn[list.product]){
                productCount_single_tonn[list.product] = (Number(list.tonn) + Number(productCount_single_tonn[list.product])).toFixed(2);
              }else{
                productCount_single_tonn[list.product] = Number(list.tonn).toFixed(2);
              }
              if(productCount_single_unit[list.product]){
                productCount_single_unit[list.product] = (Number(list.tonn) + Number(productCount_single_unit[list.product])).toFixed(2);
              }else{
                productCount_single_unit[list.product] = Number(list.tonn).toFixed(2);
              }
            })
          }
         console.log(limitedReport,transactionReport);
         console.log(data.load_single);
         let hideFields = ['customer','entrytime','exittime','exitdate','adjedqty','priceori','gst','adjustment','adjkg','remark','drivername'];
         let sumFields = ['totalamount','driveramount'];
         if(data.load.length > 0) {
          Object.entries(transactionReport).map(([key,value])=>{
            tbodyValue += createTableWithJson(key,value,sumFields,hideFields);
         })
         }
        sumFields = ['amount'];
        hideFields = [];
        if(data.collection.length > 0){
          tbodyValue+= createTableWithJson('Collection',data.collection,sumFields,hideFields);
        }
		
		 sumFields = ['given_amount'];
        hideFields = [];
        if(data.cashhandling.length > 0){
          tbodyValue+= createTableWithJson('CASH HANDLING DETAILS',data.cashhandling,sumFields,hideFields);
          data.cashhandling.map((list)=>{
            console.log(list);
            if(cashHandlingDatas[list.givento]) {
              let existingRecord =  cashHandlingDatas[list.givento];
              existingRecord.push(list);
              cashHandlingDatas[list.givento] = existingRecord;
            }else{
              cashHandlingDatas[list.givento] = [list];
            }
          })
        }
        console.log(cashHandlingDatas);
        if(Object.keys(productCount).length > 0){
          let total = 0;
          Object.values(productCount).map((list)=>{total+=Number(list)});
          productCount['total'] = total.toFixed(2);
          tbodyValue+= createTableWithJson('Products',[productCount],[],[]);
        }
		
		if(Object.keys(productCount_tonn).length > 0){
           let total = 0;
           Object.values(productCount_tonn).map((list)=>{total+=Number(list)});
           productCount_tonn['total'] = total.toFixed(2);
          tbodyValue+= createTableWithJson('Products Tonn',[productCount_tonn],[],[]);
        }
        if(Object.keys(productCount_single_tonn).length > 0){
          let total = 0;
          Object.values(productCount_single_tonn).map((list)=>{total+=Number(list)});
          productCount_single_tonn['total'] = total.toFixed(2);
          tbodyValue+= createTableWithJson('Products Single Tonn',[productCount_single_tonn],[],[]);
        }
        if(Object.keys(productCount_single_unit).length > 0){
          let total = 0;
          Object.values(productCount_single_unit).map((list)=>{total+=Number(list)});
          productCount_single_unit['total'] = total.toFixed(2);
          tbodyValue+= createTableWithJson('Products Single Unit',[productCount_single_unit],[],[]);
        }
		
		 tbodyValue+=`<table><tr><th>Overall Sales</th><td>${getTotalValue(limitedReport,'totalamount')}</td></tr>`;
        tbodyValue+=Object.entries(transactionReport).map(([key,value])=>`<tr><th>${key}</th><td>${getTotalValue(value,'totalamount')}</td></tr>`);
        tbodyValue+=`<tr><th>Bank collection</th><td>${getTotalValue( data.collection,'otheramount')}</td></tr><tr><th>Cash collection</th><td>${getTotalValue( data.collection,'amount')}</td></tr><tr><th>Driver Bata</th><td>${getTotalValue(limitedReport,'driveramount')}</td></tr>${Object.entries(cashHandlingDatas).map(([key,value])=>`<tr><th>${key}</th><td>${getTotalValue(value,'given_amount')}</td></tr>`)}<tr></tr><tr><th>Amount In Hand</th><td>${getTotalValue(data.collection,'amount')-(getTotalValue( data.cashhandling,'given_amount')+getTotalValue(limitedReport,'driveramount'))}</td></tr></table>`;
		
       /* tbodyValue+=`<table><tr><th>Overall Sales</th><td>${getTotalValue(limitedReport,'totalamount')}</td></tr>`;
        tbodyValue+=Object.entries(transactionReport).map(([key,value])=>`<tr><th>${key}</th><td>${getTotalValue(value,'totalamount')}</td></tr>`);
        tbodyValue+=`<tr><th>Bank collection</th><td>${getTotalValue( data.collection,'otheramount')}</td></tr><tr><th>Cash collection</th><td>${getTotalValue( data.collection,'amount')}</td></tr><tr><th>Sales Pending</th><td>${getTotalValue(limitedReport,'totalamount') - getTotalValue( data.collection,'amount')}</td></tr><tr><th>Driver Bata</th><td>${getTotalValue(limitedReport,'driveramount')}</td></tr>${Object.entries(cashHandlingDatas).map(([key,value])=>`<tr><th>${key}</th><td>${getTotalValue(value,'given_amount')}</td></tr>`)}<tr></tr><tr><th>Amount In Hand</th><td>${(getTotalValue( data.cashcollectiongst,'gsttotalsales')+getTotalValue(data.collection,'amount'))-(getTotalValue( data.cashhandling,'given_amount')+getTotalValue(limitedReport,'driveramount'))}</td></tr></table>`;*/
         console.log(tbodyValue,$("#tbodyReport").html());
           setTimeout(()=>{$("#tbodyReport").html(tbodyValue);
           $(".spindiv").hide();
           $("#input_from").val("");
           $("#input_to").val("");},2000)
          },
        });
        $("#modaldis").click();
        console.log(reportValue);
    });
    $("#excel").click(function(){
      let tableValue = document.getElementById("tbodyReport");
    let stringedTable =tableValue.innerHTML;
    let borderedTable1 = stringedTable.replaceAll(`<th style="`,`<th style="border:1px solid black;`);
    let borderedTable = borderedTable1.replaceAll(`<table>`,`<table style="border-collapse:collapse">`);
    let borderedTh = borderedTable.replaceAll(`<th>`,`<th style="border:1px solid black">`);
    let borderedTd = borderedTh.replaceAll(`<td>`,`<td style="border:1px solid black">`);
    console.log('stringedTable',borderedTd);
            var uri = 'data:text/csv;charset=utf-8,' + escape(borderedTd);
    
      // Now the little tricky part.
      // you can use either>> window.open(uri);
      // but this will not work in some browsers
      // or you will not get the correct file extension    
      
      //this trick will generate a temp <a /> tag
      var link = document.createElement("a");    
      link.href = uri;
      
      //set the visibility hidden so it will not effect on your web-layout
      link.style = "visibility:hidden";
      link.download = 'Overall Report for -(' + fromd + ' to ' + tod + ") .xls";
      
      //this part will append the anchor tag and remove it after automatic click
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
       });
  });
  