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={};
let UPDATE_INVOICE_NO_IN_DB;
// ---------------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 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 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);

$("#invoiceReportsBtn.sideNavtab").click(function(){
    if(!ALL_INVOICE_REPORTS_RESPONSE_MESSAGE){                                    // if already got response avoid re-request 
        $("#AllRecentInvoiceReports").addClass('active');
        $(".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();
    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 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=21;
    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/getAll_InvoiceAndReportsDetails.php', postContent);
        responseData.then((result)=>{
            if(result.message=="SUCCESS"){
                ALL_INVOICE_REPORTS_RESPONSE_MESSAGE=result.message;
                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='--';
        }
        
        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="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> <span class="${(obj.SITE_VISIT_STATUS=="Visit Pending") ? "text-warning":" "}">${obj.SITE_VISIT_STATUS}</span></td>
                    <td>${editBtn}</td>
                 </tr>`;
    });
    $("#allInvoiceReportsDetailsTable tbody").html(tableUI);
    $("#allInvoiceReportsDetailsTable").DataTable({
                                                        dom:'lBfrtip',
                                                        buttons:['copy',{extend:'excelHtml5', title:'invoices and Report'},'print'],
                                                        aLengthMenu:[[10,50,100,500,-1],[10,50,100,500,'All']],
                                                        pageLength:10,
                                                        scrollX: true,
                                                        // "scrollY": 200
                                                        
    });
}
$("#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(" ","_");
    $(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/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>`);
                })
        }
        
});
 function appendValuesToInvoiceDetailsModalPopup_EditWindow(jsonData){
    $("#editPopUp_ReportSubmittedToCustomerOn").val(jsonData.REPORT_SUBMITED_TO_CUSTOMER_ON);
    $("#editPopUp_ReportRemark").val(jsonData.REPORT_REMARK);
    $("#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
    obj['updateInAllocationDB']=UPDATE_INVOICE_NO_IN_DB;
    if(!requiredConditions(obj)){
    let postContent=JSON.stringify(obj);
    let responseData=postDataHttpRequest('DashBoard/php/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');   
        }
    }
    validatePONumber();
    validateInvoiceNumber();
    setRequireConditionToPaymentDate_onPaymentReceivedValueUpdate();
    return error;
}

function onSuccesfullyUpdated_updateChangeInTable(index, currentUpdatedJsonObj){
    let updateTableUi=()=>{
        $(`#allInvoiceReportsDetailsTable .trIndex${index} .poNumberTd`).text(currentUpdatedJsonObj.poNumber);
        $(`#allInvoiceReportsDetailsTable .trIndex${index} .reportDateTd`).text(currentUpdatedJsonObj.reportDate);
        $(`#allInvoiceReportsDetailsTable .trIndex${index} .reportRemarkTd textarea`).val(currentUpdatedJsonObj.reportRemarks);
        $(`#allInvoiceReportsDetailsTable .trIndex${index} .invoiceRisedOnTd`).text(currentUpdatedJsonObj.invoiceRaiseOn);
        $(`#allInvoiceReportsDetailsTable .trIndex${index} .invoiceNumberTd`).text(currentUpdatedJsonObj.invoiceNumber);
        $(`#allInvoiceReportsDetailsTable .trIndex${index} .invoiceValueTd`).text(currentUpdatedJsonObj.invoiceValue);
        $(`#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 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;
        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].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;
    }
    updateTableUi();
    updateJson();
}
function getModalPopupUiContent(currentEditingJson, currentEditingJsonIndex){
    // console.log(currentEditingJson);
    let conditionForReadOnlyInvoice_input=(invoiceNo)=>{
        if(invoiceNo!=null && invoiceNo!='null'){
            UPDATE_INVOICE_NO_IN_DB=false;
            return 'readOnly';
        }else{
            UPDATE_INVOICE_NO_IN_DB=true;
        }
    }
    let conditionForReadPONo_input=(poNo)=>{
        if(poNo!="Not Available" && poNo!="0"){
            return 'readOnly';
        }
    }
    let 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>`}     
                                        </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" ${conditionForReadPONo_input(currentEditingJson.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 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>`;
    return 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 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_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/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 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();
    }
    Json.forEach(function(obj, index){
        PENDING_REPORTS_SUBMITION_DETAILS_RESPONSE_JSON_IN_OBJECT[obj.SITE_ID+"_"+obj.SITE_ASSIGNED_TO_EMPID+"_"+obj.SITE_ASSIGNED_DATE]=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,500,-1],[10,50,100,500,"ALL"]],
                                                        pageLength:10,
                                                        scrollY:tableHeight
    });
    $("#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,500,-1],[10,50,100,500,'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);
});


//-----------------------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/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(`Validate`);
    })
    .catch((error)=>{
         validateBtn.html(`Validate <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 And Reports--------------------------------------------------------------------------



$(".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 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/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 constructPendingInvoiceReportTable(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){
        PENDING_INVOICES_REPORTS_RESPONSE_JSON_IN_OBJECT[obj.SITE_ID+'_'+obj.SITE_ASSIGNED_TO_EMPID+'_'+obj.SITE_ASSIGNED_DATE]=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,500,-1],[10,50,100,500,'All']],
                                                        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);
}
$("#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){
    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(' ','_');
        thisInput.val(value);
      let refIndex=thisInput.parent("td").attr("data-index");
      let requiredError=thisInput.attr("error");
      if(!checkInvalidFormate(value)){                                          // return true if invalid formate.
            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 thisPaymentDateInput=$(`#pendingInvoiceUpdatedTableDiv_table tr.${siteId}_${empId}_${siteVisitDate} 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=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 input`).val(remainingBalance); //ui update
        currentEditingJsonObj["Balance"]=remainingBalance;  //json update
   }
   $(".updateAndUploadInvoiceExcelDiv .submitBtnDiv .submit").on('click',function(){
       let thisSubmitBtn=$(this);
       thisSubmitBtn.html(`Submit<i class="fa fa-spinner fa-spin ml-3"></i>`);
       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/updateSiteAllocationDetails_insertInvoiceDetails.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>`);
        })
   }
   
   $(".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:getAllInvoiceIds_and_divideExcelJsonInTwoArray_siteAllocations_InvoiceDetails()
            }
            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(){
        let invoicesArray=[];
        PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_INVOICE_DETAILS_ARRAY=[];// making empty every time
        PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_SITE_ALLOCATION_ARRAY=[];// making empty every time
        PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON.forEach(function(value){
            let insertInOnlyInvoiceNoArray=()=>{
                invoicesArray.push(value.InVoiceNo);
            }
            let insertInInvoiceDetailsArray=()=>{
                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=()=>{
                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);
            }
            
            insertInOnlyInvoiceNoArray();
            insertInSiteAllocationsArray();
            insertInInvoiceDetailsArray();
        });
        return invoicesArray;
    }
    function getAlreadyExistingInvoicesInServer(postContent, validateBtn){
        let responseData=postDataHttpRequest('DashBoard/php/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=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(`${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(`${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(`${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(`${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(`${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.REPORT_SUBMITED_TO_CUSTOMER_ON != excelArrayObj["Report Date(yyyy-mm-dd)"]){
                        let tableTd=$(`#pendingInvoiceUpdatedTableDiv_table .${uniqueId} .reportSubmittedDate_Td`);
                        tableTd.addClass(`${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="${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 errorKeyArray=["duplicateEntries","invalidEntries","invalidInvoiceDate","invalidInvoiceNo",
        "invalidInvoiceValue","invalidPONumber","invalidPaymentDate","invalidPaymentValue",
        "invalidReportDate","paymentRemarkExceedMaxLimit","reportRemarkExceedMaxLimit","requiredFieldMissingCount"];
        let returnArray=[];
        returnArray["error"]=false;
            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
                    }
                }
            }
        return returnArray;
   }
   
   $("#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 class="col-md-4">
                                    <label  class="form-label font-weight-bold">Report Submitted To Customer On:</label>
                                    <input type="date" value="${currentEditingJson.REPORT_SUBMITED_TO_CUSTOMER_ON}"  class="form-control reportDate" name="reportDate" required />
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label font-weight-bold">Report Remarks:</label>
                                    <textarea rows="1"  class="form-control reportRemarks" placeholder="Enter Report Remarks" name="reportRemarks">${currentEditingJson.REPORT_REMARK}</textarea>
                                </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/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 td.${tdInvoiceNoAsClassName}`;
        let updateTableValue=()=>{
           $(tableRow+".reportSubmittedDate_Td input").val(invoiceDetailsObj.reportDate);
           $(tableRow+".reportRemarks_Td textarea").val(invoiceDetailsObj.reportRemarks);
           $(tableRow+".invoiceDate_Td input").val(invoiceDetailsObj.invoiceRaiseOn);
           $(tableRow+".invoiceValue_Td input").val(invoiceDetailsObj.invoiceValue);
           $(tableRow+".paymentDate_Td input").val(invoiceDetailsObj.paymentReceivedOn);
           $(tableRow+".paymentValue_Td input").val(invoiceDetailsObj.paymentReceivedValue);
           $(tableRow+".paymentRemarks_Td textarea").val(invoiceDetailsObj.paymentRemarks);
           $(tableRow+".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 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/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 constructPendingPaymentDetailsTable(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,500,-1],[10,50,100,200,"All"]],
                                                    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>`)
    
}

$("#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,500,-1],[10,50,100,200,"All"]],
                                                     pageLength:-1,
                                                        
    });
    
}
//  ----------------------------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 .${invoiceNo} .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/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 availab le',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;
    }
}

