var YEAR_WISE_PENDING_ADDITIONAL_ADJUSTMENT_RESPONSE_ARRAY=[];

let reloadBtn=$(".employeeYearWisePendingAdditionalAdjustmentTabContent button.reloadBtn");

$("#employeeYearWisePendingAdditionalAdjustmentTabBtn").on('click', function(){
    if(YEAR_WISE_PENDING_ADDITIONAL_ADJUSTMENT_RESPONSE_ARRAY.length<=0){  // if already request done, skip re-request 
        getYearWiseAllPendingAdditionalAdjustments();  
    }
});

reloadBtn.on('click', function(){
    getYearWiseAllPendingAdditionalAdjustments();
});

function getYearWiseAllPendingAdditionalAdjustments(){
        reloadBtn.html(`Reload <i class="fas fa-spinner fa-spin"></i>`);
    if(!checkWheatherLogoutOrNot_InternetConnection()){
         alertNoInternet_connection();
         reloadBtn.html(`Reload <i class="fas fa-undo"></i>`);
    }else{
        let myPromise=postDataHttpRequest("DashBoard/php/YearWisePendingAdditionalAdjustments/getYearWisePendingAdditionalAdjustments.php", ``);
        myPromise.then((result)=>{
            // console.log("result",result);
            if(!result.error){
                YEAR_WISE_PENDING_ADDITIONAL_ADJUSTMENT_RESPONSE_ARRAY=result.responseArray;
                appendYearWiseAdditionalAdjustment_responseDataToTable(result.responseArray);
                reloadBtn.text(`Reload`);
            }else{
                reloadBtn.html(`Reload <i class="fas fa-undo"></i>`);
            }
        })
        .catch((error)=>{
            reloadBtn.html(`Reload <i class="fas fa-undo"></i>`);
            console.log("error", error);
        });
    }
}


function appendYearWiseAdditionalAdjustment_responseDataToTable(responseJson){
    if($.fn.DataTable.isDataTable("#employeeYearWisePendingAdditionalAdjustment_table")){
        $("#employeeYearWisePendingAdditionalAdjustment_table").DataTable().clear().destroy();
    }
    updateAdjustmentStatusInResponseJson(responseJson);
    let getAdjustmentStatusTitle=(currentLoopObj)=>{
        let returnValue;
        let adjustmentStatus=currentLoopObj.adjustmentStatus;
        switch(adjustmentStatus){
            case "successFullyAdvanceAdjusted":
                returnValue=`<span class="text-success font-weight-bold adjustmentStatusTag">Successfully advance adjusted </span>`;
            break;
            case "needToAdjustToNextYear":
                returnValue=`<span class="text-warning font-weight-bold adjustmentStatusTag" data-toggle="Abbrevation_tooltip" title="Need to adjust remaining amount at employee to next year">Need to adjust for next year</span>`;
            break;
            case "misMatchedAdjustment":
                returnValue=`<span class="text-danger font-weight-bold adjustmentStatusTag" data-toggle="Abbrevationa_tooltip" title="(Final payable value) not equal to (Transaction amount)">Mismatched Adjustment</span>`;
                break;
            case "noPendingAdjustment":
                returnValue=`<span class="adjustmentStatusTag" data-toggle="Abbrevationa_tooltip " title="">No Pending Additional Adjustment</span>`;
                break;
            case "pendingAdjustment":
                returnValue=`<span class="adjustmentStatusTag" data-toggle="Abbrevationa_tooltip" title="">Pending Additional Adjustment</span>`;
        }
        return returnValue
    }
    let getAdjustmentButton=(currentLoopObj, currentLoopIndex)=>{
        let btnTag='--';
        let adjustmentStatus = currentLoopObj.adjustmentStatus;
        if(adjustmentStatus=="misMatchedAdjustment" || adjustmentStatus=="successFullyAdvanceAdjusted"){
            btnTag=`<button class="btn btn-theme-type5 transactionStatemntsBtn my-1" data-index="${currentLoopIndex}" style="padding: 3px 10px;" data-toggle="modal" data-target="#commonModalPopup">View</button>`;
        }else if(adjustmentStatus == "needToAdjustToNextYear"){
            btnTag=`<button class="btn btn-theme-type1 adjustmentBtn my-1" data-index="${currentLoopIndex}" style="padding: 3px 10px;" data-toggle="modal" data-target="#commonModalPopup">Adjust Amount</button>`;
        }
        return btnTag;
    }
    let getFinalPayableAmount=(finalPayableValue, financialYear)=>{
        let returnValue=finalPayableValue;
        if(finalPayableValue < 0){
            returnValue=`<span class="text-success font-weight-bold" data-toggle="Abbrevation_tooltip" title="Remaining Advance At Engineer in this <br> Financial year <span style='font-size:6px'>(${financialYear})</span>" >${finalPayableValue}</span>`;
        }
        return returnValue
    }
    let tableHeading=[
            {data:"rowIndex", title:"S.No", 
                render:function(data, type, row, meta){
                    return meta.row+1
                }
            },
            {data:"priority", title:"hidden Column"},
            {data:"EMP_ID", title:"EmpId"},
            {data:"NAME", title:"EmpName"},
            {data:"FINANCIAL_YEAR", title:"Financial Year"},
            {data:"REMAINIG_AMOUNT",title:"Final Payable Amount", 
                render:function(data, type, row){
                    return getFinalPayableAmount(data, row.FINANCIAL_YEAR);
                }
            },
            {data:"TRANSACTION_AMOUNT", title:"Transaction Amount",
                render:function(data){
                    return `<span class="transactionAmountTag">${data}</span>`;
                }
            },
            {data:"", title:"Adjustment Status", 
                render:function(data, type, row){
                    return getAdjustmentStatusTitle(row);
                }
            },
            {data:"", title:"--",
                render:function(data, type, row, meta){
                   return  getAdjustmentButton(row, meta.row);
                }
            }
        ];
    let tempTable=$("#employeeYearWisePendingAdditionalAdjustment_table").DataTable({
                                                                                    columns:tableHeading,
                                                                                    data:responseJson,
                                                                                    columnDefs:[
                                                                                        {targets:[1], visible:false},
                                                                                        {targets:[8], className:"operationTd"}
                                                                                        ],
                                                                                    createdRow:function(row, data, dataIndex){
                                                                                         $(row).addClass(`trIndex_${dataIndex}`);
                                                                                    },
                                                                                    order:[[1, "asc"]],
                                                                                    dom:"lBfrtip",
                                                                                    buttons:['copy',{extend:'excelHtml5', title:'Pending Additional Adjustment'}, 'print'], 
                                                                                    scrollX: true,
                                                                                    autoWidth:false
    });                             
}
function updateAdjustmentStatusInResponseJson(json){
    
    json.forEach(function(currentLoopObj, currentLoopIndex){
        let finalPayableValue=Number(currentLoopObj.REMAINIG_AMOUNT);
        let advanceTransactionAmount= Number(currentLoopObj.TRANSACTION_AMOUNT);
        
        switch(true){
            case (advanceTransactionAmount > 0) && (finalPayableValue != -(advanceTransactionAmount)):
                    currentLoopObj.adjustmentStatus="misMatchedAdjustment";
                    currentLoopObj.priority=1;
                break;
            case finalPayableValue < 0 :
                if(advanceTransactionAmount == 0){
                    currentLoopObj.adjustmentStatus="needToAdjustToNextYear";
                    currentLoopObj.priority=2;
                }else if(finalPayableValue == -(advanceTransactionAmount)){
                    currentLoopObj.adjustmentStatus="successFullyAdvanceAdjusted"; //successfully advance amount adjusted to next year
                    currentLoopObj.priority=3;
                }
                break;
            case finalPayableValue ==0:
                currentLoopObj.adjustmentStatus="noPendingAdjustment";
                currentLoopObj.priority=4;
                break;
            case finalPayableValue > 0:
                currentLoopObj.adjustmentStatus="pendingAdjustment";
                currentLoopObj.priority=4;
                break 
        }
    });
}
// -----------------------------------View Transactio details-----------------------------------------
$("#employeeYearWisePendingAdditionalAdjustment_table").on('click','.transactionStatemntsBtn', function(){
    let dataIndex=$(this).attr("data-index");
    let currentRowItem= YEAR_WISE_PENDING_ADDITIONAL_ADJUSTMENT_RESPONSE_ARRAY[dataIndex]; 
    let getEditDeleteBtns=(transactionDoneBy, adjustmentStatus)=>{
        let returnBtns='--';
        let empIdOfTransactionDoneBy = transactionDoneBy.split(",")[0]; //eg: transactionDoneBy="170210, Bejugam Shiva Krishna"
            if(USER_EMPID==empIdOfTransactionDoneBy && adjustmentStatus == "misMatchedAdjustment"){ //USER_EMPID= logged in pereson empId
                returnBtns=`<p class="mb-0 d-flex align-items-center"><i class="fas fa-edit editBtn pr-3 cursor-pointer" data-index="${dataIndex}" data-toggle="modal" data-target="#subCommonModalPopup"></i> | 
                            <i class="fas fa-trash deleteBtn pl-3 cursor-pointer" data-index="${dataIndex}" data-toggle="modal" data-target="#subCommonModalPopup"></i></p>`; 
            }
        return returnBtns;
    }
    let modalPopupBody=`<div class="modal-content">
                            <div class="modal-head pt-3 pl-3"><h5 class="mb-0"><b>Transaction Details</b></h5></div>
                            <div class="modal-body pb-0"> 
                                <table id="remainingBalanceAdjustedToNextYearAsAdvanceTransactionDetails_table" class="table table-hover mb-0 text-center">
                                <thead>
                                    <tr>
                                        <th>S.No</th>
                                        <th>EmpId</th>
                                        <th>EmpName</th>
                                        <th>FortNight</th>
                                        <th>Transaction-Id</th>
                                        <th>TrasactionAmount</th>
                                        <th>Created By</th>
                                        <th>Created Date</th>
                                        <th>Operations</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>1</td>
                                        <td>${currentRowItem["EMP_ID"]}</td>
                                        <td>${currentRowItem["NAME"]}</td>
                                        <td>${currentRowItem["FORTNIGHT"]}</td>
                                        <td>${currentRowItem["TRANSACTION_ID"]}</td>
                                        <td class="transactionAmountTag">${currentRowItem["TRANSACTION_AMOUNT"]}</td>
                                        <td>${currentRowItem["CREATED_BY"]}</td>
                                        <td>${currentRowItem["CREATED_DATE"]}</td>
                                        <td class="opertationTag">${getEditDeleteBtns(currentRowItem["CREATED_BY"], currentRowItem["adjustmentStatus"])}</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <div class="modal-footer">
                            <button class="btn btn-theme-type5" data-dismiss="modal" style="width:16%">Close</button>
                        </div>
    </div>`;
    $("#commonModalPopup .modal-dialog").html(modalPopupBody);
});

$("#commonModalPopup").on('click','#remainingBalanceAdjustedToNextYearAsAdvanceTransactionDetails_table .editBtn', function(){
    let dataIndex=$(this).attr("data-index");
    let currentRowItem=YEAR_WISE_PENDING_ADDITIONAL_ADJUSTMENT_RESPONSE_ARRAY[dataIndex];
    let modalPopupUiContent=`
        <div class="modal-content">
            <form id="editNextYearAdjustedAdvanceTransactionDetails_form" data-Index=${dataIndex}>
                <div class="modal-head pt-3 pl-3">
                    <h5 class="mb-0"><b>Edit Transaction Details</b></h5>
                </div>
                <div class="modal-body">
                    <table>
                        <tr class="d-none">
                            <td><input type="number" name="finalPayableValue" value=${currentRowItem["REMAINIG_AMOUNT"]} readonly /></td>
                            <td><input type="text" class="form-control" value="${currentRowItem["TRANSACTION_ID"]}" name="transactionId"  readonly /></td
                        </tr>
                        <tr>
                            <th>EmpId</th>
                            <td><div class="d-flex"><span class="ml-2">:</span><span class="ml-2">${currentRowItem["EMP_ID"]}</span></div></td>
                        </tr>
                        <tr>
                            <th>EmpName</th>
                            <td><div class="d-flex"><span class="ml-2 align-self-center">:</span><span class="ml-2">${currentRowItem["NAME"]}</span></div></td>
                        </tr>
                        <tr>
                            <th>TransactionId</th>
                            <td> <div class="d-flex"><span class="ml-2 align-self-center">:</span><span class="ml-2">${currentRowItem["TRANSACTION_ID"]}</span></div></td>
                        </tr>
                        <tr>
                            <th>Transaction Amount</th>
                            <td>
                                <div class="d-flex">
                                    <span class="ml-2 align-self-center">: </span><input type="number" class="form-control w-50 ml-2" name="transactionAmount" value=${currentRowItem["TRANSACTION_AMOUNT"]} required /> 
                                </div>
                            </td>
                        </tr>
                    </table>
                </div>
                <div class="modal-footer">
                    <p class="mb-0 message mr-auto"></p>
                    <button type="submit" class="btn btn-theme-type1 submitBtn">Submit</button>
                    <button class="btn btn-theme-type3" data-dismiss="modal">Close</button>
                </div>
            </form>
        </div>
    `;
    $("#subCommonModalPopup .modal-dialog").html(modalPopupUiContent);
    
});
$("#commonModalPopup").on('click','#remainingBalanceAdjustedToNextYearAsAdvanceTransactionDetails_table .deleteBtn', function(){
     let dataIndex=$(this).attr("data-index");
     let currentRowItem=YEAR_WISE_PENDING_ADDITIONAL_ADJUSTMENT_RESPONSE_ARRAY[dataIndex];
     let modalPopupUiContent=`
        <div class="modal-content">
            <form id="deleteNextYearAdjustedAdvanceTransactionDetails_form" data-index=${dataIndex}>
                <div class="modal-head pt-3 pl-3">
                    <h5 class="mb-0"><b>Delete Transaction Details</b></h5>
                </div>
                <div class="modal-body">
                    <table>
                        <tr class="d-none">
                            <th>TransactionId</th><td><input type="text" name="transactionId" readonly value="${currentRowItem["TRANSACTION_ID"]}"/></td>
                        </tr>
                        <tr>
                            <th>Emp Id</th>
                            <td>: ${currentRowItem["EMP_ID"]}</td>
                        </tr>
                        <tr>
                            <th>Emp Name</th>
                            <td>: ${currentRowItem["NAME"]}</td>
                        </tr>
                        <tr>
                            <th>Transaction Id</th>
                            <td>: ${currentRowItem["TRANSACTION_ID"]}</td>
                        </tr>
                        <tr>
                            <th>Transaction Amount</th>
                            <td>: ${currentRowItem["TRANSACTION_AMOUNT"]}</td>
                        </tr>
                    </table>
                </div>
                <div class="modal-footer">
                    <p class="mb-0 message mr-auto"></p>
                    <button type="submit" class="btn btn-theme-type4-danger submitBtn">Delete</button>
                    <button class="btn btn-theme-type3" data-dismiss="modal">Close</button>
                </div>
            </form>
        </div>
     `;
     $("#subCommonModalPopup .modal-dialog").html(modalPopupUiContent);
});

$("#subCommonModalPopup").on('submit','#editNextYearAdjustedAdvanceTransactionDetails_form', function(e){
    e.preventDefault();
    let form=$(this);
    let dataIndex =form.attr("data-Index");
    let submitBtn=form.find("button.submitBtn");
    let messageTag =form.find("p.message");
    submitBtn.html(`Submit <i class="fas fa-spinner fa-spin"`);
    let obj=convertValuesToObject(form.serializeArray());
    obj.queryType="update";
    let postContent=JSON.stringify(obj);
    
    if(Number(obj.transactionAmount) == -Number(obj.finalPayableValue)){
        if(!checkWheatherLogoutOrNot_InternetConnection()){
            submitBtn.html(`Retry <i class="fas fa-undo"></i>`);
        }else{
            let promiseObj=postDataHttpRequest("DashBoard/php/YearWisePendingAdditionalAdjustments/update_deleteTransactionDetails.php", postContent);
            promiseObj.then((result)=>{
                if(result.error){
                    submitBtn.html(`Retry <i class="fa fa-undo"></i>`);
                    messageTag.html(`<span class="text-danger">${result.message}</span>`);
                }else{
                    submitBtn.hide();
                    messageTag.html(`<span class="text-success">Succesfully Updated.</span>`);
                    afterSuccesfullyUpdatedNextYearAdjustmentTransactionDetails(obj.transactionAmount, dataIndex);
                }
            })
            .catch((error)=>{
                console.log(error);
                submitBtn.html(`Retry <i class="fa fa-undo"></i>`);
                messageTag.html(`<span class="text-danger">${error.responseText + error.statusText}</span>`);
            })
        }
    }else{
        messageTag.html(`<span class="text-danger">Transaction Amount <span class="text-dark font-weight-bold">${obj.transactionAmount}</span> is not equal to final payable value <span class="text-dark font-weight-bold">${-Number(obj.finalPayableValue)}</span></span>`);
    }
});
function afterSuccesfullyUpdatedNextYearAdjustmentTransactionDetails(transactionAmount, dataIndex){
    let object={
        transactionAmount:transactionAmount,
        adjustmentStatus:"successFullyAdvanceAdjusted",
        adjustmentStatusUI:`<span class="text-success font-weight-bold adjustmentStatusTag">Successfully advance adjusted </span>`,
        operationTdButton:`<button class="btn btn-theme-type5 transactionStatemntsBtn my-1" data-index="${dataIndex}" style="padding: 3px 10px;" data-toggle="modal" data-target="#commonModalPopup">View</button>`
    };
    updateJsonAndUI_nextYearAdjustmentTransactionDetails(object, dataIndex);
}

$("#subCommonModalPopup").on('submit','#deleteNextYearAdjustedAdvanceTransactionDetails_form', function(e){
    e.preventDefault();
    let form= $(this);
    let dataIndex =form.attr("data-index");
    let submitBtn=form.find("button.submitBtn");
    let messageTag = form.find("p.message");
    submitBtn.html(`Delete <i class="fas fa-spinner fa-spin"></i>`);
    let obj=convertValuesToObject(form.serializeArray());
        obj.queryType="delete";
    let postContent=JSON.stringify(obj);
    if(!checkWheatherLogoutOrNot_InternetConnection()){
        submitBtn.html(`Retry <i class="fas fa-undo"></i>`);
    }else{
        let promiseObj= postDataHttpRequest("DashBoard/php/YearWisePendingAdditionalAdjustments/update_deleteTransactionDetails.php", postContent);
        promiseObj.then((result)=>{
             if(result.error){
                    submitBtn.html(`Retry <i class="fa fa-undo"></i>`);
                    messageTag.html(`<span class="text-danger">${result.message}</span>`);
                }else{
                    submitBtn.hide();
                    messageTag.html(`<span class="text-success">Succesfully Transaction Details Deleted.</span>`);
                    afterSuccesfullyDeletedNextYearAdjustmentTransactionDetails(dataIndex);
                }
        })
        .catch((error)=>{
            submitBtn.html(`Retry <i class="fas fa-undo"></i>`);
            messageTag.html(`<span class="text-danger">${error.responseText + error.statusText}</span>`);
        });
    }
});

function afterSuccesfullyDeletedNextYearAdjustmentTransactionDetails(dataIndex){
    let object={
        transactionAmount:0,
        adjustmentStatus:"needToAdjustToNextYear",
        adjustmentStatusUI:`<span class="text-warning font-weight-bold adjustmentStatusTag" data-toggle="Abbrevation_tooltip" title="Need to adjust remaining amount at employee to next year">Need to adjust for next year</span>`,
        operationTdButton:`<button class="btn btn-theme-type1 adjustmentBtn my-1" data-index="${dataIndex}" style="padding: 3px 10px;" data-toggle="modal" data-target="#commonModalPopup">Adjust Amount</button>`
    };
    updateJsonAndUI_nextYearAdjustmentTransactionDetails(object, dataIndex);
}



function updateJsonAndUI_nextYearAdjustmentTransactionDetails(object, dataIndex){
    let updateUI=()=>{
        //transaction amount
        $(`#employeeYearWisePendingAdditionalAdjustment_table .trIndex_${dataIndex} .transactionAmountTag`).text(object.transactionAmount);                 //mainTable
        $("#commonModalPopup #remainingBalanceAdjustedToNextYearAsAdvanceTransactionDetails_table .transactionAmountTag").text(object.transactionAmount);   //common modalPopup Table transaction Details
        //adjustmentStatus
        $(`#employeeYearWisePendingAdditionalAdjustment_table .trIndex_${dataIndex} .adjustmentStatusTag`).html(object.adjustmentStatusUI);                 //mainTable
        //operation     
         $("#commonModalPopup #remainingBalanceAdjustedToNextYearAsAdvanceTransactionDetails_table .opertationTag").text("--");                             //common modalPopup Table transaction Details
        $(`#employeeYearWisePendingAdditionalAdjustment_table .trIndex_${dataIndex} .operationTd`).html(object.operationTdButton)
        
    };
    let updateJson=()=>{
        let currentEditingObj=YEAR_WISE_PENDING_ADDITIONAL_ADJUSTMENT_RESPONSE_ARRAY[dataIndex];
        currentEditingObj["TRANSACTION_AMOUNT"]=object.transactionAmount;
        currentEditingObj["adjustmentStatus"]=object.adjustmentStatus;
    };
    updateUI();
    updateJson();
}
//---------------------------------------------------end----------------------------------------------------------------
// -------------------------------------------------------------Adjust remaining amount to next year as advance functionality-----------------------
$("#employeeYearWisePendingAdditionalAdjustment_table").on('click', "button.adjustmentBtn", function(){
    let dataIndex = $(this).attr("data-index");
    let currentRowItem=YEAR_WISE_PENDING_ADDITIONAL_ADJUSTMENT_RESPONSE_ARRAY[dataIndex];
    let clsObj= new Placeholder();
    let placeHolderTableBody=clsObj.tablePlaceHolderColumnsAndRows(1,3);// rows, columns
    let modalPopupUI=`
        <div class="modal-content w-50 m-auto">
            <div class="modal-head">
                <h5 class="mb-0 pt-3 pl-3 font-weight-bold">Adjust Remaining Amount To Next Year As Advance.</h5>
            </div>
            <div class="modal-body pb-0">
                <form id="adjustToThisFortNightAsAdvance_form" data-index=${dataIndex}>
                    <table id="remainingBalanceAdjustingToNextYearAsAdvance_table" class="table table-hover mb-0">
                        <thead>
                            <tr>
                                <th>Available Fortnight</th>
                                <th>Remaining Balance At Emp</th>
                                <th>Operations</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${placeHolderTableBody}
                        </tbody>
                    </table>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-theme-type3" data-dismiss="modal">Close</button>
            </div>
        </div>
        `;
    $("#commonModalPopup .modal-dialog").html(modalPopupUI);
    getAvailableFortNightToAdjustRemainingAmountInNextYear(currentRowItem);
});
function getAvailableFortNightToAdjustRemainingAmountInNextYear(currentTableRowObj){
    let financialYear=getNextFinancialYearFromToDates(currentTableRowObj["FINANCIAL_YEAR"]);
    let obj={
        fromDate:financialYear["nextYear_FromDate"],
        toDate:financialYear["nextYear_ToDate"],
        empId:currentTableRowObj["EMP_ID"]
    };
    let transactionAmount=-Number(currentTableRowObj["REMAINIG_AMOUNT"]);
    console.log("obj", obj);
    let postContent=JSON.stringify(obj);
    if(!checkWheatherLogoutOrNot_InternetConnection()){
        alertNoInternet_connection();
        $(".placeholder-glow").removeClass('placeholder-glow');
    }else{
        let promiseObj=postDataHttpRequest("DashBoard/php/YearWisePendingAdditionalAdjustments/getAvailableFortnightToAdjustRemainingAmountToNextYear.php", postContent);
        promiseObj.then((result)=>{
            console.log(result);
            if(result.error){
                 $(".placeholder-glow").removeClass('placeholder-glow');
            }else{
                appendAvailablefortNightToNextYearAdjustmentDetailsTable(result.response, transactionAmount);
            }
        })
        .catch((error)=>{
            console.log("error",error);
            $(".placeholder-glow").removeClass('placeholder-glow');
        });
    }
}

function appendAvailablefortNightToNextYearAdjustmentDetailsTable(responseObj, remainingBalanceAtEmp){
    let tableRow='';
    if(Object.keys(responseObj).length>0){
        tableRow=`<tr>  
                        <td><input type="text" class="form-control text-center" value="${responseObj.FORTNIGHT}" name="fortnight" readonly/></td>
                        <td>${remainingBalanceAtEmp}</td>
                        <td><button type="submit" class="btn btn-theme-type1 submitBtn">Adjust Here</button></td>
                    </tr>`;
    }else{
        tableRow=`<tr>
                <td class="text-danger">There are no fortnight's available to ajust remaining amount to next year as advance</td>
                <td> -- </td>
                <td> -- </td>
            </tr>`;
    }
    $("#commonModalPopup #remainingBalanceAdjustingToNextYearAsAdvance_table tbody").html(tableRow);
}

$("#commonModalPopup").on('submit', '#adjustToThisFortNightAsAdvance_form', function(e){
    e.preventDefault();
    let form =$(this);
    let dataIndex=form.attr("data-index");
    let submitBtnTag=form.find(`button.btn.submitBtn`);
    let messageTag=form.find(`p.messageTag`);
    submitBtnTag.html(`Adjust Here <i class="fas fa-spinner fa-spin"></i>`);
    let currentRowItem=YEAR_WISE_PENDING_ADDITIONAL_ADJUSTMENT_RESPONSE_ARRAY[dataIndex];
    let obj=convertValuesToObject(form.serializeArray());
    
    obj.empId=currentRowItem["EMP_ID"];
    obj.transactionId=currentRowItem["EMP_ID"]+"_"+currentRowItem["FINANCIAL_YEAR"]+"_yearAdjustment";
    obj.advanceAmount=-Number(currentRowItem["REMAINIG_AMOUNT"]); //advanceAmount= (-remaining)
    
    let postContent=JSON.stringify(obj);
    if(!checkWheatherLogoutOrNot_InternetConnection()){
        alertNoInternet_connection();
        submitBtnTag.html(`Adjust Here <i class="fas fa-spinner fa-spin"></i>`);
    }else{
        let promiseObj= postDataHttpRequest("DashBoard/php/YearWisePendingAdditionalAdjustments/insertAdvanceDetails.php",postContent);
        promiseObj.then((result)=>{
            console.log("result",result);
            if(result.error){
                submitBtnTag.html(`Retry <i class="fas fa-undo"></i>`);
                messageTag.html(`<span class="text-danger">${result.message}</span>`);
            }else{
                submitBtnTag.attr("disabled", "disabled").text(`Adjust Here`);
                messageTag.html(`<span class="text-success">${result.message}</span>`);
                obj.operationTdButton=`<button class="btn btn-theme-type5 transactionStatemntsBtn my-1" data-index="${dataIndex}" style="padding: 3px 10px;" data-toggle="modal" data-target="#commonModalPopup">View</button>`;
                obj.adjustmentStatusUI=`<span class="text-success font-weight-bold adjustmentStatusTag">Successfully advance adjusted </span>`;
                obj.adjustmentStatus="successFullyAdvanceAdjusted";
                afterAdjustingRemainingAmountAsAdvanceToNextYear(obj, dataIndex);
            }
        })
        .catch((error)=>{
            messageTag.html(`<span class="text-danger">${error.responseText +  error.statusText}</span>`);
            console.log(error);
        });
    }
});
function afterAdjustingRemainingAmountAsAdvanceToNextYear(object, dataIndex){
    //update json
     let updateUI=()=>{
        //transaction amount
        $(`#employeeYearWisePendingAdditionalAdjustment_table .trIndex_${dataIndex} .transactionAmountTag`).text(object.advanceAmount);                 //mainTable
        //adjustmentStatus
        $(`#employeeYearWisePendingAdditionalAdjustment_table .trIndex_${dataIndex} .adjustmentStatusTag`).html(object.adjustmentStatusUI);                 //mainTable
        //operation 
        $(`#employeeYearWisePendingAdditionalAdjustment_table .trIndex_${dataIndex} .operationTd`).html(object.operationTdButton);
    };
    let updateJson=()=>{
        let currentEditingObj=YEAR_WISE_PENDING_ADDITIONAL_ADJUSTMENT_RESPONSE_ARRAY[dataIndex];
        currentEditingObj["TRANSACTION_AMOUNT"]=object.advanceAmount;
        currentEditingObj["adjustmentStatus"]=object.adjustmentStatus;
        currentEditingObj["CREATED_BY"]=USER_EMPID+","+USER_NAME;
        currentEditingObj["FORTNIGHT"]=object.fortnight;
        currentEditingObj["TRANSACTION_ID"]=object.transactionId;
        currentEditingObj["CREATED_DATE"]=new Date().getFullYear()+"-"+(Number(new Date().getMonth())+1)+"-"+new Date().getDate();//currentDate
    };
    updateUI();
    updateJson();
}

function getNextFinancialYearFromToDates(financialYear){
    let returnArray=[];
    //eg: financialYear=2022-04-01_2023-03-31
    returnArray["nextYear_FromDate"]=`${new Date(financialYear.split("_")[0]).getFullYear()+1}-04-01`;
    returnArray["nextYear_ToDate"]=`${new Date(financialYear.split("_")[1]).getFullYear()+1}-03-31`;
    return returnArray;
}

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



















// -------------------------------------
/*
    1) Why Year wise Additional Adjustments implemented ?

    Reason: 
            In database table (fort_night_cliams) having trigger of (advance table) and (adjustments) on delete, update, insert will change values in (fort_night_cliams) with in financial year
            but if in last fortNight of any financial year advance remaining at emp not, move to next fortNight because it only with in financial year changes happens
    --------------------------------
    2) finalPayable value =?
        
        i)   if +Positive value (finalPayable greater > 0)         : it means amount need to adjust to employee  in (Employee Additional Adjustment) Tab in DashBoard.
        ii)  if  zero value (finalPayable value ==0)               : it means all additional adjustments , advance all settled , no need to adjust
        iii) if -Negative value (finalPayable  less < 0)           : it means after all adjustments (remaining amount) left at employee which need to move to next financial year as Advances because it wont move automatically.
                
                a)if Transaction Amount ==0                                                 :   means  the (remaining amount) left not till adjusted to next financial year as advance
                b)if Transaction Amount > 0  && Transaction Amount != finalPayableValue     :   means not properly adjusted to next financial year as advance mismatch happend 
                c)if Transaction Amount > 0  && Transaction Amount == finalPayableValue     :   means Properly adjusted to next financial year as advance.                  
                
                
    

*/




