/*
Product Name: Windz App
Author: KodingStudio
Website: https://kodingstudio.com/
Contact: contact@kodingstudio.com
File: Agent Js File
*/


let idField = document.getElementById("id-field"),
    inputDeleteId = document.getElementById("input-delete-id"),
    statusField = document.getElementById("status-field"),
    inputGroupName = document.getElementById("input-group-name"),
    addBtn = document.getElementById("add-btn"),
    editBtn = document.getElementById("edit-btn"),
    deleteRecordBtn = document.getElementById('delete-record');

let inputSpendingLimit = document.getElementById('input-spending-limit'),
    switchSpendingFilter = document.getElementById('switch-spending-filter');

let inputDistanceLimit = document.getElementById('input-distance-limit'),
    switchDistanceFilter = document.getElementById('switch-distance-filter');

let selectFilterType = document.getElementById('choice-filter-type'),
    switchTimeFilter = document.getElementById('switch-time-filter'),
    choiceFilterType = new Choices(selectFilterType, {
        searchEnabled: false,
        choices: [
            {
            value: 0,
            label: '24/7 access'
        },
            {
                value: 1,
                label: 'Custom time'
            }]
    }),
    divTime = document.getElementById('div-time'),
    fieldFromTime = document.getElementById('field-from-time')
    fieldToTime = document.getElementById('field-to-time');

choiceFilterType.disable();

let choiceBusiness = new Choices('#choice-business', {
    searchEnabled: true
});
let statusVal = new Choices(statusField);

// list js
let checkAll = document.getElementById("checkAll");
if (checkAll) {
    checkAll.onclick = function () {
        var checkboxes = document.querySelectorAll('.form-check-all input[type="checkbox"]');
        if (checkAll.checked == true) {
            Array.from(checkboxes).forEach(function (checkbox) {
                checkbox.checked = true;
                checkbox.closest("tr").classList.add("table-active");
            });
        } else {
            Array.from(checkboxes).forEach(function (checkbox) {
                checkbox.checked = false;
                checkbox.closest("tr").classList.remove("table-active");
            });
        }
    };
}

let perPage = 8;

//Table
let options = {
    valueNames: [
        "id",
        "business_id",
        "business_name",
        "group_name",

        "spending_filter",
        "spending_amount",

        "distance_filter",
        "allowed_distance",

        "time_filter",
        "time_filter_type",
        "from_time",
        "to_time",

        "time_access",

        "date",
        "status",
    ],
    page: perPage,
    pagination: true,
    plugins: [
        ListPagination({
            left: 2,
            right: 2
        })
    ]
};

// Init list
let customerList = new List("customerList", options).on("updated", function (list) {
    list.matchingItems.length == 0 ?
        (document.getElementsByClassName("noresult")[0].style.display = "block") :
        (document.getElementsByClassName("noresult")[0].style.display = "none");
    var isFirst = list.i == 1;
    var isLast = list.i > list.matchingItems.length - list.page;
    // make the Prev and Nex buttons disabled on first and last pages accordingly
    (document.querySelector(".pagination-prev.disabled")) ? document.querySelector(".pagination-prev.disabled").classList.remove("disabled") : '';
    (document.querySelector(".pagination-next.disabled")) ? document.querySelector(".pagination-next.disabled").classList.remove("disabled") : '';

    if (isFirst) {
        document.querySelector(".pagination-prev").classList.add("disabled");
    }
    if (isLast) {
        document.querySelector(".pagination-next").classList.add("disabled");
    }

    if (list.matchingItems.length <= perPage) {
        document.querySelector(".pagination-wrap").style.display = "none";
    } else {
        document.querySelector(".pagination-wrap").style.display = "flex";
    }

    if (list.matchingItems.length == perPage) {
        document.querySelector(".pagination.listjs-pagination").firstElementChild.children[0].click()
    }

    if (list.matchingItems.length > 0) {
        document.getElementsByClassName("noresult")[0].style.display = "none";
    } else {
        document.getElementsByClassName("noresult")[0].style.display = "block";
    }
});

document.querySelector("#customerList").addEventListener("click", function () {
    refreshCallbacks();
    //ischeckboxcheck();
});


/* fetch all category endpoint */
function fetchAllActiveBusinessEndpoint(url = baseUrl + 'v1/web/business/active') {
    return new Promise(function (resolve, reject) {

        const xhttp = new XMLHttpRequest();
        xhttp.onload = function () {

            var status = xhttp.status;
            if (status === 200 || status === 201 || 204) {
                resolve({code: status, data: this.responseText});
            } else {
                reject({code: status, data: this.responseText});
            }

        };
        xhttp.open("GET", url, true);
        for (let i = 0; i < listOfHeaders.length; i++) {
            xhttp.setRequestHeader(listOfHeaders[i]['key'], listOfHeaders[i]['value']);
        }

        xhttp.send();

    });

}

/* fetch all endpoint */
function fetchAllEndpoint(url = baseUrl + 'v1/web/group/all') {
    return new Promise(function (resolve, reject) {

        const xhttp = new XMLHttpRequest();
        xhttp.onload = function () {

            var status = xhttp.status;
            if (status === 200 || status === 201) {
                resolve({code: status, data: this.responseText});
            } else {
                reject({code: status, data: this.responseText});
            }

        };
        xhttp.open("GET", url, true);
        for (let i = 0; i < listOfHeaders.length; i++) {
            xhttp.setRequestHeader(listOfHeaders[i]['key'], listOfHeaders[i]['value']);
        }

        xhttp.send();

    });

}

/* add endpoint */
function addEndpoint(jsonParam, url = baseUrl + 'v1/web/group/add') {
    return new Promise(function (resolve, reject) {

        const xhttp = new XMLHttpRequest();
        xhttp.onload = function () {

            var status = xhttp.status;
            if (status === 200 || status === 201) {
                resolve({code: status, data: this.responseText});
            } else {
                reject({code: status, data: this.responseText});
            }

        };
        xhttp.open("POST", url, true);
        for (let i = 0; i < listOfHeaders.length; i++) {
            xhttp.setRequestHeader(listOfHeaders[i]['key'], listOfHeaders[i]['value']);
        }

        xhttp.send(JSON.stringify(jsonParam));

    });

}

/* update endpoint */
function updateEndpoint(jsonParam, url) {
    return new Promise(function (resolve, reject) {

        const xhttp = new XMLHttpRequest();
        xhttp.onload = function () {

            var status = xhttp.status;
            if (status === 200 || status === 201) {
                resolve({code: status, data: this.responseText});
            } else {
                reject({code: status, data: this.responseText});
            }

        };
        xhttp.open("POST", url, true);
        for (let i = 0; i < listOfHeaders.length; i++) {
            xhttp.setRequestHeader(listOfHeaders[i]['key'], listOfHeaders[i]['value']);
        }

        xhttp.send(JSON.stringify(jsonParam));

    });

}

/* delete endpoint */
function deleteEndpoint(url) {
    return new Promise(function (resolve, reject) {

        const xhttp = new XMLHttpRequest();
        xhttp.onload = function () {

            var status = xhttp.status;
            if (status === 200 || status === 201) {
                resolve({code: status, data: this.responseText});
            } else {
                reject({code: status, data: this.responseText});
            }

        };
        xhttp.open("GET", url, true);
        for (let i = 0; i < listOfHeaders.length; i++) {
            xhttp.setRequestHeader(listOfHeaders[i]['key'], listOfHeaders[i]['value']);
        }

        xhttp.send();

    });

}

let id = 0;
let menuName = null;

fetchAllActiveBusinessEndpoint()
    .then(response => JSON.parse(response.data))
    .then(data => {

        let dataList = [];
        Array.from(data.data).forEach(raw => {

            const param = {
                label: raw.name,
                value: raw.id
            };
            dataList.push(param);

        });

        choiceBusiness.setChoices(
            dataList,
            'value',
            'label',
            false,
        );


    })
    .catch(error => {

        let data = JSON.parse(error.data);
        Swal.fire({
            position: 'center',
            icon: 'error',
            title: data.message,
            showConfirmButton: false,
            timer: 2000,
            showCloseButton: true
        });
        customerList.remove("id", '<a href="javascript:void(0);" class="fw-medium link-primary">#VZ2101</a>');

    });

fetchAllEndpoint()
    .then(response => JSON.parse(response.data))
    .then(data => {

        if (data.data.length <= 0)
            customerList.remove("id", '<a href="javascript:void(0);" class="fw-medium link-primary">#VZ2101</a>');

        Array.from(data.data).forEach(raw => {

            let dateCreated = moment(raw.created_at, "YYYY-MM-DD hh:mm:ss").format("DD MMM, YYYY");
            menuName = raw.menu_name;
            customerList.add({
                id: '<a href="javascript:void(0);" class="fw-medium link-primary">#VZ' + raw.id + "</a>",
                business_id: raw.business_id,
                group_name: raw.name,
                business_name: raw.business_name,


                spending_filter: raw.spending_filter,
                distance_filter: raw.distance_filter,
                time_filter: raw.time_filter,
                time_filter_type: raw.access_24h === 1 ? 0 : 1,
                from_time: raw.from_time,
                to_time: raw.to_time,

                spending_amount: raw.spending_filter === 1 ? raw.spending_amount : 'Not Activated',
                allowed_distance: raw.distance_filter === 1 ? raw.allowed_distance : 'Not Activated',
                time_access: raw.time_filter === 1 ? (raw.access_24h === 1 ? '24 Hr Access' : raw.from_time + ' to '+raw.to_time) : 'Not Activated',

                date: dateCreated,
                status: isStatus(raw.enable)
            });

        });

        customerList.remove("id", '<a href="javascript:void(0);" class="fw-medium link-primary">#VZ2101</a>');
        customerList.sort('id', {order: "desc"});
        addActiveClassToCheckbox();
        refreshCallbacks();


    })
    .catch(error => {

        let data = JSON.parse(error.data);
        Swal.fire({
            position: 'center',
            icon: 'error',
            title: data.message,
            showConfirmButton: false,
            timer: 2000,
            showCloseButton: true
        });
        customerList.remove("id", '<a href="javascript:void(0);" class="fw-medium link-primary">#VZ2101</a>');

    });

addBtn.addEventListener("click", function (e) {

    if (inputGroupName.value !== null &&
        choiceBusiness.getValue(true) !== "" &&
        statusVal.getValue(true) !== "") {

        console.log("Filters( Spending = "+switchSpendingFilter.checked
            +", Time = "+switchTimeFilter.checked
            +", Distance = "+switchDistanceFilter.checked);

        var dtObject = {
            business_id: choiceBusiness.getValue(true),
            name: inputGroupName.value
        };

        if (switchSpendingFilter.checked === true){
            dtObject.spending_filter = switchSpendingFilter.checked;
            dtObject.spending_amount = inputSpendingLimit.value;
        }

        if (switchDistanceFilter.checked === true){
            dtObject.distance_filter = switchDistanceFilter.checked;
            dtObject.allowed_distance = inputDistanceLimit.value;
        }

        if (switchTimeFilter.checked === true){
            dtObject.time_filter = switchTimeFilter.checked;
            dtObject.access_type = choiceFilterType.getValue(true);

            if (choiceFilterType.getValue(true) === 1 ){
                dtObject.from_time = fieldFromTime.value;
                dtObject.to_time = fieldToTime.value;
            }

        }

        ///console.log(JSON.stringify(dtObject));

        addEndpoint(dtObject)
            .then(response => JSON.parse(response.data))
            .then(data => {

                let dataObject = data.data;
                let dateCreated = moment(dataObject.created_at, "YYYY-MM-DD hh:mm:ss").format("DD MMM, YYYY");

                customerList.add({
                    id: '<a href="javascript:void(0);" class="fw-medium link-primary">#VZ' + dataObject.id + "</a>",
                    business_id: choiceBusiness.getValue()['value'],
                    business_name: choiceBusiness.getValue()['label'],
                    group_name: inputGroupName.value,

                    spending_filter: switchSpendingFilter.checked === true ? 1 : 0,
                    distance_filter: switchDistanceFilter.checked === true ? 1 : 0,
                    time_filter: switchTimeFilter.checked === true ? 1 : 0,

                    time_filter_type: choiceFilterType.getValue(true),

                    from_time: fieldFromTime.value,
                    to_time: fieldToTime.value,

                    spending_amount: switchSpendingFilter.checked === true ? inputSpendingLimit.value : 'Not Activated',
                    allowed_distance: switchDistanceFilter.checked === true ? inputDistanceLimit.value  : 'Not Activated',
                    time_access: switchTimeFilter.checked === true ? (choiceFilterType.getValue(true) === 0 ? '24 Hr Access' : fieldFromTime.value + ' to '+fieldToTime.value) : 'Not Activated',

                    date: dateCreated,
                    status: isStatus(statusField.value),
                });

                customerList.sort('id', {order: "desc"});
                document.getElementById("close-modal").click();
                clearFields();
                filterContact("All");
                refreshCallbacks();

                Swal.fire({
                    position: 'center',
                    icon: 'success',
                    title: 'Added successfully!',
                    showConfirmButton: false,
                    timer: 2000,
                    showCloseButton: true
                });

            })
            .catch(error => {

                let data = JSON.parse(error.data);
                Swal.fire({
                    position: 'center',
                    icon: 'error',
                    title: data.message,
                    showConfirmButton: false,
                    timer: 2000,
                    showCloseButton: true
                });

            });


    }
});
editBtn.addEventListener("click", function (e) {

    let itemId = idField.value;
    var editValues = customerList.get({
        id: itemId,
    });
    Array.from(editValues).forEach(function (x) {
        isid = new DOMParser().parseFromString(x._values.id, "text/html");
        var selectedid = isid.body.firstElementChild.innerHTML;
        if (selectedid === itemId) {

            let id = itemId.replace('#VZ', '');
            let json = {
                business_id: choiceBusiness.getValue()['value'],
                name: inputGroupName.value,
                enable: getStatus(statusField.value)
            };


            if (switchSpendingFilter.checked === true){
                json.spending_filter = switchSpendingFilter.checked;
                json.spending_amount = inputSpendingLimit.value;
            }

            if (switchDistanceFilter.checked === true){
                json.distance_filter = switchDistanceFilter.checked;
                json.allowed_distance = inputDistanceLimit.value;
            }

            if (switchTimeFilter.checked === true){
                json.time_filter = switchTimeFilter.checked;
                json.access_type = choiceFilterType.getValue(true);

                if (choiceFilterType.getValue(true) === 1 ){
                    json.from_time = fieldFromTime.value;
                    json.to_time = fieldToTime.value;
                }

            }

            updateEndpoint(json,
                baseUrl + 'v1/web/group/update/' + id)
                .then(response => JSON.parse(response.data))
                .then(data => {

                    let dateCreated = moment().format("DD MMM, YYYY");
                    x.values({
                        id: '<a href="javascript:void(0);" class="fw-medium link-primary">' + idField.value + "</a>",
                        business_id: choiceBusiness.getValue()['value'],
                        business_name: choiceBusiness.getValue()['label'],
                        group_name: inputGroupName.value,

                        spending_filter: switchSpendingFilter.checked === true ? 1 : 0,
                        distance_filter: switchDistanceFilter.checked === true ? 1 : 0,
                        time_filter: switchTimeFilter.checked === true ? 1 : 0,

                        time_filter_type: choiceFilterType.getValue(true),

                        from_time: fieldFromTime.value,
                        to_time: fieldToTime.value,

                        spending_amount: switchSpendingFilter.checked === true ? inputSpendingLimit.value : 'Not Activated',
                        allowed_distance: switchDistanceFilter.checked === true ? inputDistanceLimit.value  : 'Not Activated',
                        time_access: switchTimeFilter.checked === true ? (choiceFilterType.getValue(true) === 0 ? '24 Hr Access' : fieldFromTime.value + ' to '+fieldToTime.value) : 'Not Activated',

                        date: dateCreated,
                        status: isStatus(statusField.value),
                    });

                    document.getElementById("close-modal").click();
                    clearFields();
                    Swal.fire({
                        position: 'center',
                        icon: 'success',
                        title: data.message,
                        showConfirmButton: false,
                        timer: 2000,
                        showCloseButton: true
                    });

                })
                .catch(error => {

                    let data = JSON.parse(error.data);
                    Swal.fire({
                        position: 'center',
                        icon: 'error',
                        title: data.message,
                        showConfirmButton: false,
                        timer: 2000,
                        showCloseButton: true
                    });

                })


        }
    });

});
deleteRecordBtn.addEventListener("click", function () {

    let id = inputDeleteId.value;
    deleteEndpoint(baseUrl + 'v1/web/group/delete/' + id.replace('#VZ', ''))
        .then(response => JSON.parse(response.data))
        .then(data => {

            customerList.remove("id", '<a href="javascript:void(0);" class="fw-medium link-primary">' + id + '</a>');
            document.getElementById("deleteRecordModal").click();
            Swal.fire({
                position: 'center',
                icon: 'success',
                title: data.message,
                showConfirmButton: false,
                timer: 2000,
                showCloseButton: true
            });
            clearFields();

        })
        .catch(error => {

            let data = JSON.parse(error.data);
            Swal.fire({
                position: 'center',
                icon: 'error',
                title: data.message,
                showConfirmButton: false,
                timer: 2000,
                showCloseButton: true
            });

        });

});

switchSpendingFilter.addEventListener("change", function () {
    if (this.checked) {
        inputSpendingLimit.removeAttribute('disabled');
    } else {
        inputSpendingLimit.setAttribute('disabled', 'disabled');
    }
});
switchDistanceFilter.addEventListener("change", function () {
    if (this.checked) {
        inputDistanceLimit.removeAttribute('disabled');
    } else {
        inputDistanceLimit.setAttribute('disabled', 'disabled');
    }
});
switchTimeFilter.addEventListener("change", function () {
    if (this.checked) {
        console.log("enable choice");
        choiceFilterType.enable();
    }
    else {

        hideTimeProperties();


    }
});

selectFilterType.addEventListener("change", function (evt) {

    if(choiceFilterType.getValue(true) !== 0 ){
        divTime.style.display = 'block';
    }
    else {
        divTime.style.setProperty("display", "none", "important");
    }

});

document.querySelector(".pagination-next").addEventListener("click", function () {
    (document.querySelector(".pagination.listjs-pagination")) ? (document.querySelector(".pagination.listjs-pagination").querySelector(".active")) ?
        document.querySelector(".pagination.listjs-pagination").querySelector(".active").nextElementSibling.children[0].click() : '' : '';
});
document.querySelector(".pagination-prev").addEventListener("click", function () {
    (document.querySelector(".pagination.listjs-pagination")) ? (document.querySelector(".pagination.listjs-pagination").querySelector(".active")) ?
        document.querySelector(".pagination.listjs-pagination").querySelector(".active").previousSibling.children[0].click() : '' : '';
});

document.getElementById("showModal").addEventListener("show.bs.modal", function (e) {
    if (e.relatedTarget.classList.contains("edit-item-btn")) {
        document.getElementById("exampleModalLabel").innerHTML = "Edit Group";
        document.getElementById("showModal").querySelector(".modal-footer").style.display = "block";
        document.getElementById("add-btn").style.display = "none";
        document.getElementById("edit-btn").style.display = "block";
    } else if (e.relatedTarget.classList.contains("add-btn")) {
        document.getElementById("exampleModalLabel").innerHTML = "Add Group";
        document.getElementById("showModal").querySelector(".modal-footer").style.display = "block";
        document.getElementById("edit-btn").style.display = "none";
        document.getElementById("add-btn").style.display = "block";
    } else {
        document.getElementById("exampleModalLabel").innerHTML = "List Currency";
        document.getElementById("showModal").querySelector(".modal-footer").style.display = "none";
    }
});
document.getElementById("showModal").addEventListener("hidden.bs.modal", function () {
    clearFields();

});

/* filter data using any specific value*/
function filterContact(isValue) {
    var values_status = isValue;
    customerList.filter(function (data) {
        var statusFilter = false;
        matchData = new DOMParser().parseFromString(
            data.values().status,
            "text/html"
        );
        var status = matchData.body.firstElementChild.innerHTML;
        if (status == "All" || values_status == "All") {
            statusFilter = true;
        } else {
            statusFilter = status == values_status;
        }
        return statusFilter;
    });

    customerList.update();
}

/* searching the data in the table*/
function SearchData() {

    var isstatus = document.getElementById("idStatus").value;
    var pickerVal = document.getElementById("datepicker-range").value;

    var date1 = pickerVal.split(" to ")[0];
    var date2 = pickerVal.split(" to ")[1];
    if (date2 == null)
        date2 = date1;

    console.log("Date 01 = " + date1 + " Date 02 = " + date2);

    customerList.filter(function (data) {
        matchData = new DOMParser().parseFromString(data.values().status, 'text/html');
        var status = matchData.body.firstElementChild.innerHTML;
        var statusFilter = false;
        var dateFilter = false;

        if (status == 'all' || isstatus == 'all') {
            statusFilter = true;
        } else {
            statusFilter = status == isstatus;
        }

        if (new Date(data.values().date.slice(0, 12)) >= new Date(date1) && new Date(data.values().date.slice(0, 12)) <= new Date(date2)) {
            dateFilter = true;
        } else {
            dateFilter = false;
        }

        if (statusFilter && dateFilter) {
            return statusFilter && dateFilter
        } else if (statusFilter && pickerVal == "") {
            return statusFilter
        } else if (dateFilter && pickerVal == "") {
            return dateFilter
        }
    });
    customerList.update();
}

/* clear the dialog fields*/
function clearFields() {

    inputGroupName.value = "";
    statusField.value = "";
    statusVal.setChoiceByValue("");

    choiceBusiness.setChoiceByValue("");

    switchSpendingFilter.checked = false;
    inputSpendingLimit.value = null;
    inputSpendingLimit.setAttribute('disabled', 'disabled');

    switchDistanceFilter.checked = false;
    inputDistanceLimit.value = null;
    inputDistanceLimit.setAttribute('disabled', 'disabled');

    switchTimeFilter.checked = false;

    hideTimeProperties();
}

function hideTimeProperties(){

    choiceFilterType.setChoiceByValue('');
    choiceFilterType.disable();

    fieldFromTime.value = '';
    fieldToTime.value = '';
    //divTime.style.display = 'none !important';
    divTime.style.setProperty("display", "none", "important");

}

/* delete the multiple data from list*/
function deleteMultiple() {
    ids_array = [];
    var items = document.getElementsByName('chk_child');
    Array.from(items).forEach(function (ele) {
        if (ele.checked == true) {
            var trNode = ele.parentNode.parentNode.parentNode;
            var id = trNode.querySelector('.id a').innerHTML;
            ids_array.push(id);
        }
    });
    if (typeof ids_array !== 'undefined' && ids_array.length > 0) {
        if (confirm('Are you sure you want to delete this?')) {
            Array.from(ids_array).forEach(function (id) {
                customerList.remove("id", `<a href="javascript:void(0);" class="fw-medium link-primary">${id}</a>`);
            });
            document.getElementById('checkAll').checked = false;
        } else {
            return false;
        }
    } else {
        Swal.fire({
            title: 'Please select at least one checkbox',
            confirmButtonClass: 'btn btn-info',
            buttonsStyling: false,
            showCloseButton: true
        });
    }
}

/* get the decorated status regaridng status value*/
function isStatus(val) {
    switch (val) {
        case "Active":
            return (
                '<span class="badge badge-soft-success text-uppercase">' +
                val +
                "</span>"
            );
        case "Block":
            return (
                '<span class="badge badge-soft-danger text-uppercase">' +
                val +
                "</span>"
            );

        case 0:
            return (
                '<span class="badge badge-soft-success text-uppercase">' +
                'Active' +
                "</span>"
            );
        case 1:
            return (
                '<span class="badge badge-soft-danger text-uppercase">' +
                'Block' +
                "</span>"
            );
    }
}

function getStatus(val) {
    switch (val) {
        case "Active":
            return 0;
        case "Block":
            return 1;
    }
}

/* Add click listener to checkbox
 also attach/remove the active class into checkbox */
function addActiveClassToCheckbox() {
    Array.from(document.getElementsByName("checkAll")).forEach(function (x) {
        x.addEventListener("click", function (e) {
            if (e.target.checked) {
                e.target.closest("tr").classList.add("table-active");
            } else {
                e.target.closest("tr").classList.remove("table-active");
            }
        });
    });
}

/* Attach the listeners to delete/edit buttons of table */
function refreshCallbacks() {

    Array.from(document.getElementsByClassName("remove-item-btn")).forEach(function (btn) {

        if (btn.getAttribute('listener') == 'false') {

            btn.setAttribute('listener', 'true');
            btn.addEventListener("click", function (e) {

                let itemIdRemove = e.target.closest("tr").children[1].innerText;
                let itemValuesRemove = customerList.get({
                    id: itemIdRemove,
                });

                Array.from(itemValuesRemove).forEach(function (x) {

                    let idDelete = new DOMParser().parseFromString(x._values.id, "text/html");
                    let isdeleteid = idDelete.body.firstElementChild.innerHTML;

                    if (isdeleteid === itemIdRemove) {

                        inputDeleteId.value = isdeleteid;

                    }

                });

            });

        }

    });
    Array.from(document.getElementsByClassName("edit-item-btn")).forEach(function (btn) {

        if (btn.getAttribute('listener') == 'false') {

            btn.setAttribute('listener', 'true');
            btn.addEventListener("click", function (e) {

                let itemIdEdit = e.target.closest("tr").children[1].innerText;
                let itemValuesEdit = customerList.get({
                    id: itemIdEdit,
                });

                Array.from(itemValuesEdit).forEach(function (x) {
                    let idEdit = new DOMParser().parseFromString(x._values.id, "text/html");
                    let selectedid = idEdit.body.firstElementChild.innerHTML;
                    if (selectedid === itemIdEdit) {

                        idField.value = selectedid;
                        inputGroupName.value = x._values.group_name;
                        choiceBusiness.setChoiceByValue(x._values.business_id);
                        
                        if (x._values.spending_filter === 1){

                            switchSpendingFilter.checked = true;
                            switchSpendingFilter.dispatchEvent(new Event("change"));
                            inputSpendingLimit.value = x._values.spending_amount;

                        }

                        if (x._values.distance_filter === 1){

                            switchDistanceFilter.checked = true;
                            switchDistanceFilter.dispatchEvent(new Event("change"));
                            inputDistanceLimit.value = x._values.allowed_distance;

                        }

                        if (x._values.time_filter === 1){

                            switchTimeFilter.checked = true;
                            switchTimeFilter.dispatchEvent(new Event("change"));

                            choiceFilterType.setChoiceByValue(x._values.time_filter_type);
                            if (x._values.time_filter_type === 1){

                                divTime.style.display = 'block';
                                fieldFromTime.value = x._values.from_time;
                                fieldToTime.value = x._values.to_time;

                            }



                        }

                        if (statusVal) statusVal.destroy();
                        statusVal = new Choices(statusField, {
                            searchEnabled: false
                        });
                        val = new DOMParser().parseFromString(x._values.status, "text/html");
                        var statusSelec = val.body.firstElementChild.innerHTML;
                        statusVal.setChoiceByValue(statusSelec);


                    }
                });
            });

        }

    });

}



