let ALL_INVOICE_REPORTS_RESPONSE_MESSAGE;
let ALL_INVOICES_REPORTS_RESPONSE_JSON;
let PENDING_INVOICE_REPORTS_RESPONSE_MESSAGE;
let PENDING_INVOICES_REPORTS_RESPONSE_JSON_IN_OBJECT={};
// ---------------Excel upload---------------------
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 UPDATE_INVOICE_NO_IN_DB;

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);

$("#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();
    if(contentClassName=="pendingInvoicesReports"){
        if(!PENDING_INVOICE_REPORTS_RESPONSE_MESSAGE){                              // if already got response avoid re-request 
            $(`.pendingInvoicesReports form.invoiceReportForm.searchByDate button[type="submit"]`).trigger('click');
        }
    }
});

$(".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=20;
    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){
        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">${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="remainingBalanceTd">${obj.REMAINING_BALANCE_IF_ANY}</td>
                    <td class="paymentRemarkTd"><textarea rows="1" class="form-control" readonly>${obj.PAYMENT_REMARKS}</textarea></td>
                    <td>${obj.SITE_VISIT_STATUS}</td>
                    <td><i class="fas fa-edit editBtn cursor-pointer" data-rowIndex="${loopIndex}" data-toggle="modal" data-target="#commonModalPopup"></i></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,
                                                        stateSave: true,
                                                        autoWidth: false,
                                                        // 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 .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);
    $("#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 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){
    if($.fn.DataTable.isDataTable('#pendingInvoiceReportsDetailsTable')){
        $('#pendingInvoiceReportsDetailsTable').DataTable().clear().destroy();
    }
    let tableUI='';
    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": 200
                                                        
    });
    $("#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', 'Report Remarks',
                         'Invoice Date', 'InVoiceNo',	'Invoice Value',
                         'Payment Date', 'Payment Value',
                         'Payment Remarks', 'Balance\n1'];
   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();
});
function afterSuccessfullyExtractedJsonFromExcel(json){
    PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON=json;
    let sortBySite_empId_siteVisitDate=()=>{
        json.sort((a,b)=>{
            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,
                                                        autoWidth: false,
                                                        scrollX:true
    });
    // $('#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"]=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"]=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();
      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"]=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 spin ml-3"></i>`);
       let obj={
           siteAllocationArray:PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_SITE_ALLOCATION_ARRAY,
           invoiceDetailsArray:PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_INVOICE_DETAILS_ARRAY
       }
       let postContent=obj;
       updateSiteAllocationDetails_invoiceDetails_inServer(postContent,thisSubmitBtn);
   });
   function updateSiteAllocationDetails_invoiceDetails_inServer(postContent, thisSubmitBtn){
        let responseData=postDataHttpRequest('DashBoard/php/updateSiteAllocationDetails_insertInvoiceDetails.php', postContent);
        console.log(responseData);
        // responseData.then((result)=>{
        //     console.log(result);
        // })
        // .catch((error)=>{
        //     console.log(error);
        // });
   }
   
   $(".updateAndUploadInvoiceExcelDiv .submitBtnDiv .validate").click(function(){
       let thisValidateBtn=$(this);
       let isError=checkErrors();
       console.log("isError",isError);
        if(isError["error"]){// if error
            $(".updateAndUploadInvoiceExcelDiv .submitBtnDiv .viewErrorLocation").removeClass("d-none");
            $(".updateAndUploadInvoiceExcelDiv .submitBtnDiv .viewErrorLocation").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").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 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"],
                "invoiceValue":value["Invoice Value"],
                "paymentDate":value["Payment Date"],
                "paymentRemarks":value["Payment Remarks"],
                "paymentValue":value["Payment Value"],
                "reportDate":value["Report Date"],
                "reportRemarks":value["Report Remarks"],
                "remainingBalance":value["Balance"]
                }
                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 
            }
            $(".updateAndUploadInvoiceExcelDiv .submitBtnDiv .submit").show();
            $(".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){
            PENDING_INVOICE_REPORTS_UPLOADED_EXCEL_JSON.forEach(function(excelArrayObj){
                let mismatch=false;
                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"]){// invoice Date
                        let tableTd=$(`#pendingInvoiceUpdatedTableDiv_table .${uniqueId} .invoiceDate_Td`);
                        if(!tableTd.children(".warningMsg").length){
                            tableTd.append(`<span class=" warningMsg text-warning">${invoiceObj.INVOICE_RISED_ON}</span>`);
                        }
                        mismatch=true;
                    }
                    if(invoiceObj.INVOICE_VALUE != excelArrayObj["Invoice Value"]){  // invoice Value
                        let tableTd = $(`#pendingInvoiceUpda warningMsg table .${uniqueId} .invoiceValue_Td`);
                        if(!tableTd.children(".warningMsg").length){
                            tableTd.append(`<span class="warningMsg text-warning">${invoiceObj.INVOICE_VALUE}</span>`);
                        }
                        mismatch=true;
                    }
                    if(invoiceObj.PAYMENT_RECEIVED_ON != excelArrayObj["Payment Date"]){
                        let tableTd=$(`#pendingInvoiceUpdatedTableDiv_table .${uniqueId} .paymentDate_Td`);
                        if(!tableTd.children(".warningMsg").length){
                            tableTd.append(`<span class=" warningMsg text-warning">${invoiceObj.PAYMENT_RECEIVED_ON}</span>`);
                        }
                        mismatch=true;
                    }
                    if(invoiceObj.PAYMENT_RECEIVED_VALUE != excelArrayObj["Payment Value"]){
                        let tableTd=$(`#pendingInvoiceUpdatedTableDiv_table .${uniqueId} .paymentValue_Td`);
                        if(!tableTd.children(".warningMsg").length){
                            tableTd.append(`<span class=" warningMsg text-warning">${invoiceObj.PAYMENT_RECEIVED_VALUE}</span>`);  
                        }
                        mismatch=true;
                    }
                    if(invoiceObj.REMAINING_BALANCE_IF_ANY != excelArrayObj["Balance"]){
                        let tableTd=$(`#pendingInvoiceUpdatedTableDiv_table .${uniqueId} .remainingBalance_Td`);
                        if(!tableTd.children(".warningMsg").length){
                            tableTd.append(`<span class=" warningMsg text-warning">${invoiceObj.REMAINING_BALANCE_IF_ANY}</span>`);
                        }
                        mismatch=true;
                    }
                    if(invoiceObj.REPORT_SUBMITED_TO_CUSTOMER_ON != excelArrayObj["Report Date"]){
                        let tableTd=$(`#pendingInvoiceUpdatedTableDiv_table .${uniqueId} .reportSubmittedDate_Td`);
                        if(!tableTd.children(".warningMsg").length){
                            tableTd.append(`<span class=" warningMsg text-warning">${invoiceObj.REPORT_SUBMITED_TO_CUSTOMER_ON}</span>`);
                        }
                        mismatch=true;
                    }
                    if(mismatch){
                        $(".updateInvoiceBtn_Th, .updateInvoiceBtn_Td").removeClass('d-none');
                        $(`#pendingInvoiceUpdatedTableDiv_table .${uniqueId} .updateInvoiceBtn_Td`).html(`<button class="btn btn-theme-type1" 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").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"];
        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]];
                    if(result=="Error" || result==0){
                    returnArray["error"]=true;
                    returnArray["type"]=errorKeyArray[innerLoopIndex];
                    return returnArray
                    }
                }
            }
        return returnArray;
   }
   
   
   
   //---------------------------------end--------------------------
// ------------------------------------------------------------------------end-----------------------------------------------------------------
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;
    }
}

