var ServerConfigurationView = Backbone.View.extend({
    events: {
        "click .tab": "onSelectTab",
        "click #addVatCode": "addVatCodeForSageLive",
        "click #addNewPrinter": "openModalAddEditPrinter",
        "change #moduleName": "showHidePrinterFieldsByModuleName",
        "click #savePrinterBtn": "savePrinter",
        "click #removePrinterBtn": "removePrinter",
        "change #taxCalculatorType": "onTaxCalculatorTypeChange",
        "change #posDataAccessDbDriver": "onDbDriverChange",
        "change #useViaProxy": "onUseViaProxyChange",
        "click .accordion": "onAccordionClick",
        "click #restartServerBtn": "restartServer",
        "click #wooCommerceApiAccess" : "getWooCommerceAPIAccess",
        "change #NeverSummarize" : "onNeverSummarizeChange",
        "change #useTipsTenderCode" : "onUseTipsTenderCodeChange",
    },

    modules: [],
    printers: [],
    tenderTypes: [],
    glAccounts: { cogsAccountList:[], salesAccountList: [], inventoryAccountList: []},

    initialize: async function (options) {
        var that = this;
        this.options = options;
        this.model = options.model;
        this.template = _.template(options.template);
        this.getServerMonitorInfo();
        await this.getGlAccounts();
        await this.getTenderTypes();
        await this.getServerConfig();

        $(document).ready(() => {
           
            var selectElements = document.querySelectorAll("select");
            var instances = M.FormSelect.init(selectElements, options);
            var pickerElement = document.querySelectorAll('.datepicker');
            var instances = M.Datepicker.init(pickerElement, {
                autoClose: true,
                container: 'body',
                format: 'ddmmyyyy',
                i18n: App.i18n
            });

            that.onTaxCalculatorTypeChange();
            that.onDbDriverChange();
        });
    },

    render: function () {
        // this.$el.detach();
        this.$el.html(this.template({
            glAccounts: this.glAccounts
        }));
        return this;
    },

    getServerConfig: async function () {
        var that = this;
        var sessionToken = getCookie();

        return $.ajax({
            url: "data/get-server-configuration",
            data: {
                token: sessionToken,
            },
            dataType: "json",
            type: "POST",
            success: function (data) {
                that.modules = data.modules;
                that.printers = data.printers;

                that.printers.forEach((m) => {
                        that.addNewPrinter(m);
                });

                that.modules.forEach((m) => {
                        var form = document.getElementById(m.moduleName);
                        if (form)
                            that.loadModules(m);
                        else if(m.moduleName.includes('AccuServerTaxCalculator')) {
                            document.getElementById('AccuServerTaxCalculator').id = m.moduleName;
                            that.loadModules(m);
                        }
                        else if(m.moduleName.includes('AccuServerIntegrator.AccuServerIntegratorViaProxy')){
                            document.getElementById('AccuServerIntegrator.AccuServerIntegrator').id = 'AccuServerIntegrator.AccuServerIntegratorViaProxy';
                            that.loadModules(m);
                            document.getElementById('useViaProxy').checked = true;
                        }
                });

                that.renderTaxCodes(data.vatCodesList);
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                } else {
                    M.toast({
                        html:
                            "{Literal}There was a problem fetching data from the server{/Literal}",
                    });
                }
            },
        });
    },

    getTenderTypes: async function () {
        var that = this;
        var sessionToken = getCookie();

        return $.ajax({
            url: "data/get-tender-types",
            data: {
                token: sessionToken,
            },
            dataType: "json",
            type: "POST",
            success: function (data) {
                that.tenderTypes = data.results;
                // var tendersSelect = document.getElementById('TipsTenderCode');
                // that.tenderTypes.forEach( item => {
                //     var option = document.createElement('option');
                //     option.value = item.id;
                //     option.text = item.id + ' | ' + item.tenderName;
                //     tendersSelect.insertAdjacentElement('beforeend', option);
                // })
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                } else {
                    M.toast({
                        html:
                            "{Literal}There was a problem fetching data from the server{/Literal}",
                    });
                }
            },
        });
    },

    getGlAccounts: async function () {
        var that = this;
        var sessionToken = getCookie();

        return $.ajax({
            url: "data/get-gl-accounts",
            data: {
                token: sessionToken,
            },
            dataType: "json",
            type: "POST",
            success: function (data) {
                if(data.success){
                    that.glAccounts = data.glAccounts;
                    that.glAccounts.salesAccountList = that.glAccounts.salesAccountList.sort( (a,b) => a > b ? 1 : -1);
                    that.glAccounts.cogsAccountList = that.glAccounts.cogsAccountList.sort( (a,b) => a > b ? 1 : -1);
                    that.glAccounts.inventoryAccountList = that.glAccounts.inventoryAccountList.sort( (a,b) => a > b ? 1 : -1);

                    var tipsGlAccountSelect = document.getElementById('TipsGLAccount');
                    that.glAccounts.salesAccountList.forEach( glAccount => {
                        var option = document.createElement('option');
                        option.value = glAccount;
                        option.text = glAccount
                        tipsGlAccountSelect.insertAdjacentElement('beforeend', option);
                    });
                }
                else
                    M.toast({ html: "{Literal}There was a problem fetching data from the server{/Literal}"});
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                } else {
                    M.toast({html: "{Literal}There was a problem fetching data from the server{/Literal}"});
                }
            },
        });
    },

    setGlAccounts: function(formId) {
        var that = App.serverConfiguration;

        var formElement = document.getElementById(formId);
        var selectEl = formElement.querySelector('#defaultItemSalesAccount');
        that.setAccountsToSelectEl(selectEl, that.glAccounts.salesAccountList);

        var selectEl = formElement.querySelector('#newItemCOGSAccount');
        that.setAccountsToSelectEl(selectEl, that.glAccounts.cogsAccountList);

        var selectEl = formElement.querySelector('#inventoryAdjustmentsGlAccount');
        that.setAccountsToSelectEl(selectEl, that.glAccounts.cogsAccountList);
    },

    setAccountsToSelectEl(selectEl, accountsList){
        if(selectEl == null)
            return;

        options = '';
        accountsList.forEach( account => {
            options += '<option';
            if(selectEl.dataset.value == account)
                options += ' selected';
            options += ' value="'+ account + '">' + account +'</option>';
        })
        
        selectEl.innerHTML = options;
        M.FormSelect.init(selectEl, {});
        
    },

    getAccountingCompanies: async function (formId) {
        var that = this;
        var sessionToken = getCookie();
        var hostname = document.getElementById(formId).querySelector('#Hostname').value;
        var isActive = document.getElementById(formId).querySelector('[data-name="isActive"]').checked;
        
        document.getElementById(formId).querySelectorAll('input,select').forEach( el => {
            if(el.id != 'Hostname' && el.dataset.name != 'isActive')
                el.disabled = true;
        });

        var selectElements = document.querySelectorAll("select");
        var instances = M.FormSelect.init(selectElements, options);

        return $.ajax({
            url: "data/get-accounting-companies",
            data: {
                token: sessionToken,
            },
            dataType: "json",
            type: "POST",
            success: function (data) {
                if(data.success){
                    var selectEl = document.getElementById(formId).querySelector('#company');
                    var selectedCompanyPath = selectEl.dataset.value;
                    var options = '<option></option>';
                    data.accountingCompanyList.forEach( company => {
                        options += '<option ';
                        if(selectedCompanyPath == company.path)
                            options += ' selected ';
                        options +=  `data-path="${company.path}" value="${company.path}">${company.name}</option>`;
                    });

                    if(data.accountingCompanyList.length == 0){
                        options = '<option selected value="'+selectedCompanyPath+'">{Literal}No Companies Found{/Literal}</option>';
                        if(hostname != '' && isActive)
                            M.toast({ displayLength: 8000,  html: "{Literal}AccuServer could not connect with accounting adapter. Please make sure it running and has network connection.{/Literal}"});
                    }
                    else if(hostname != '' && isActive) {
                        document.getElementById(formId).querySelectorAll('input,select').forEach( el => el.disabled = false);
                        var selectElements = document.querySelectorAll("select");
                        var instances = M.FormSelect.init(selectElements, options);
                    }


                    selectEl.innerHTML = options;
                    M.FormSelect.init(selectEl, {});
                    document.getElementById('companyHelper').innerText = selectEl.selectedOptions[0].value;

                    selectEl.addEventListener('change', (e) => {
                        e.currentTarget.dataset.value = e.currentTarget.value;
                        document.getElementById('companyHelper').innerText = selectEl.selectedOptions[0].value;
                    })
                }
                else if(hostname != '' && isActive)
                    M.toast({ html: "{Literal}There was a problem fetching data from the server{/Literal}"});
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                } else if(hostname != '' && isActive) {
                    M.toast({html: "{Literal}There was a problem fetching data from the server{/Literal}"});
                }
            },
        });
    },

    prepareAutoCompleteData(list) {
        list = list.sort( (a,b) => a > b ? 1 : -1);
        var autoCompleteList = {};
        list.forEach( item => autoCompleteList[item] = null);
        return autoCompleteList;
    },

    onUseViaProxyChange: function (e) {
        var viaProxyElements = document.querySelectorAll('.viaProxySection');
        if(document.getElementById('useViaProxy').checked) {
            for (const el of viaProxyElements) {
                    el.classList.remove('hide');
            }
            document.getElementById('AccuServerIntegrator.AccuServerIntegrator').id = 'AccuServerIntegrator.AccuServerIntegratorViaProxy';
        }
        else {
            for (const el of viaProxyElements) {
                el.classList.add('hide');
            }
            document.getElementById('AccuServerIntegrator.AccuServerIntegratorViaProxy').id = 'AccuServerIntegrator.AccuServerIntegrator';
        }
    },

    onAccordionClick: async function (e) {
        var clickedModule = e.currentTarget;
        // var acc = document.getElementsByClassName("accordion");
        clickedModule.classList.toggle("active-accordion");
        var panel = clickedModule.nextElementSibling;
       

        if (panel.style.display === "block") {
           
            var isFormValid = true;
            if(panel.dataset.validate != undefined) {
                const func = this[panel.dataset.validate];
                isFormValid = func();
            }

            if(isFormValid) {
                if(panel.dataset.onclose != undefined) {
                    const func = this[panel.dataset.onclose];
                    await func();
                }
                this.saveModuleOnCloseAccordion(panel.id);
                panel.style.display = "none";
                panel.classList.add("accordion-panel-active");
            }

        } else {
            panel.style.display = "block";
            panel.classList.remove("accordion-panel-active");
            if(panel.dataset.onopen != undefined) {
                var onOpenFunctions = panel.dataset.onopen.split(',');
                onOpenFunctions.forEach(funcName => { 
                    var func = this[funcName.trim()];
                    if(func != undefined)
                    func(panel.id);
                });
            }
        }
    },
    
    saveModuleOnCloseAccordion: function (moduleName) {
        var that = this;
        this.currentModuleState = this.getModuleFormValues(moduleName);
        this.originalModuleState = this.modules.find( i => {return i.moduleName == moduleName});
        var isActive = this.currentModuleState.isActive == true || this.currentModuleState.isActive == 'true'
        // var isNewModule = originalModuleState == undefined;
        var isChanged = false;
        if(this.originalModuleState){
            this.originalModuleState.isActive = this.originalModuleState.isActive.toString();
            isChanged = this.isModuleFormChanged(this.originalModuleState, this.currentModuleState);
        }
        else if(this.originalModuleState && !isActive || !this.originalModuleState && isActive)
            isChanged = true;

        if(isChanged) {
            if (isActive) {
                var promise = this.saveModule(this.currentModuleState);
                promise.then( () => {
                    if(!this.originalModuleState)
                        this.modules.push(this.currentModuleState);
                    else {
                        var index = that.modules.findIndex( m => { return m.moduleName == this.currentModuleState.moduleName});
                        this.modules[index] = this.currentModuleState;
                    }
                })

            } else {
                var promise = this.removeModule(this.currentModuleState);
                promise.then( () => {
                    this.modules = this.modules.filter( m => { return m.moduleName != this.currentModuleState.moduleName});
                })
            }
        }
    },

    isModuleFormChanged: function(obj1, obj2) {
        var isChanged = false;
        
        if(obj1 && obj2) {
            var keys1 = Object.keys(obj1);
            var keys2 = Object.keys(obj2);

            if(keys1.length == keys2.length){
                keys1.forEach( k => {
                    if(obj1[k] != obj2[k]) {
                        isChanged = true;
                        return false;
                    }
                })
            }
            else
                isChanged = true;
        } else if(!obj2)
            isChanged = true;

        
        return isChanged;
    },
    renderTaxCodes: function (taxCodes) {
        var carryOutTaxCodeSelect = document.getElementById("CarryOutTaxCode");
        taxCodes.forEach((t) => {
            carryOutTaxCodeSelect.insertAdjacentHTML(
                "beforeend",
                `<option value="${t}">${t}</option>`
            );
        });
    },
    getServerMonitorInfo: async function () {
        var sessionToken = getCookie();

        return $.ajax({
            url: "data/get-monitor-info",
            data: {
                token: sessionToken,
            },
            dataType: "json",
            type: "POST",
            success: function (data) {
                data.messages = data.messages.split("<br>").reverse().join("\n");
                document.getElementById("serverLog").append(data.messages);
                var detailsKeys = Object.keys(data.serverInfo);
                var detailsElement = document.getElementById("serverInfo");
                detailsKeys.forEach((key) => {
                    detailsElement.insertAdjacentHTML(
                        "beforeend",
                        `<div style="line-height: 1.1;" ><span style="font-size:12px;font-weight: bold;">${key}</span><br> ${data.serverInfo[key]}</div><br>`
                    );
                });
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                } else {
                    M.toast({
                        html:
                            "{Literal}There was a problem fetching data from the server{/Literal}",
                    });
                }
            },
        });
    },

    showRestartButton: function () {
        var modulesElement = document.getElementById('modules');
        var a = document.createElement('a');
        a.addEventListener('click', re)

    },

    restartServer: async function () {
        var sessionToken = getCookie();

        return $.ajax({
            url: "data/restart-server",
            data: {
                token: sessionToken,
            },
            dataType: "json",
            type: "POST",
            success: function (data) {
                if(data.success)
                    setTimeout(() => {
                        window.location.href = "#/log-in";
                        location.reload();
                    }, 5000);
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                } else {
                    M.toast({
                        html:
                            "{Literal}There was a problem fetching data from the server{/Literal}",
                    });
                }
            },
        });
    },

    onSelectTab: function (e) {
        var element = e.currentTarget.childNodes[0];

        var activeClasses = ["active", "waves-effect", "waves-light", "btn"];
        var inActiveClasses = [
            "waves-effect",
            "waves-teal",
            "btn-flat",
            "teal",
            "lighten-5",
            "center",
        ];

        if (!element.classList.contains("active")) {
            var tabContentElements = document.getElementsByClassName("tab-content");
            for (var el of tabContentElements) {
                if (!el.id.includes(e.currentTarget.id)) el.classList.add("hide");
                else el.classList.remove("hide");
            }

            var tabButtonElements = document.querySelectorAll(".tabButtons a");
            for (var el of tabButtonElements) {
                el.classList = [];
                if (!el.isSameNode(e.currentTarget.childNodes[0])) {
                    el.classList.add(...inActiveClasses);
                } else {
                    el.classList.add(...activeClasses);
                }
            }
        }
    },

    onTaxCalculatorTypeChange: function (e) {
        var taxTypeSelectElement = document.getElementById("taxCalculatorType");
        var selected = taxTypeSelectElement.value;
        taxTypeSelectElement.parentElement.parentElement.parentElement.id = "AccuServerTaxCalculator." + selected;
        selected = selected.split('.')[1];
        var sections = document
            .getElementById("taxCalculatorTypeOptions")
            .querySelectorAll("section");
        for (section of sections) {
            if (section.classList.value.includes(selected))
                section.classList.remove("hide");
            else section.classList.add("hide");
        }

        // M.FormSelect.init(taxTypeSelectElement, {});

    },

    onDbDriverChange: function (e) {
        var selected = document.getElementById("posDataAccessDbDriver").value;

        var sections = document
            .getElementById("AccuServerDataAccess.POSDataAccess")
            .querySelectorAll("section");
        for (section of sections) {
            if (section.id == selected) {
                section.classList.remove("hide");
                var inputsToShow = section.querySelectorAll('input');
                for (input of inputsToShow) {
                    input.classList.remove('hide');
                }
            }
            else {
                section.classList.add("hide");
                var inputsToHide = section.querySelectorAll('input');
                for (input of inputsToHide) {
                    input.classList.add('hide');
                }
            }
        }
    },

    addVatCodeForSageLive: function (e = undefined, vat, fieldName) {
        var that = this;

        var tbody = document
            .getElementById("AccuServerIntegrator.AccuServerSageLiveIntegrator")
            .getElementsByTagName("tbody")[0];
        var length = tbody.querySelectorAll('tr').length;
        tbody.insertAdjacentHTML(
            "beforeend",
      /*html*/ `<tr><td><input data-name="Vat${length + 1}"/></td><td><input/></td><td><a class="btn-floating btn-small waves-effect waves-light red" onclick="App.serverConfiguration.removeVatCodeForSageLive(this)"><i class="material-icons">remove</i></a></td></tr>`
        );

      if(vat) {
        var vatArray = vat.split(";");
        var vatKeyElement = document.querySelector(`[data-name="${fieldName}" i]`);
        var vatValueElement = vatKeyElement.parentElement.nextElementSibling.firstElementChild;
        vatKeyElement.value = vatArray[0];
        vatValueElement.value = vatArray[1];
      }
    },
    
    removeVatCodeForSageLive: function (el) {
        el.parentElement.parentElement.remove();
        
    },

    addNewPrinter: function (printer) {
        var tbody = document
            .getElementById("printers-container")
            .getElementsByTagName("tbody")[0];
        var tr = document.createElement("tr");
        tr.dataset.name = printer.Name;
        tr.dataset.module = printer.moduleName;
        tr.innerHTML = /*html*/ `<td>${printer.moduleName}</td><td>${printer.Name}</td><td>${printer.Printer}</td>`;
        tr.addEventListener("click", (e) => {
            this.openModalAddEditPrinter(e, this);
        });
        tbody.append(tr);
    },

    removePrinter: async function () {
        var printer = this.getPrinterFormValues();
        
        var response = await this.removeModule(printer);
        if (response.success) {
            var tbody = document.getElementById("printers-container").getElementsByTagName("tbody")[0];
            var rows = tbody.querySelectorAll("tr");
            for (tr of rows) {
                if (
                    tr.dataset.name == printer.Name &&
                    tr.dataset.module == printer.moduleName
                )
                    tr.remove();
            }

            this.printers = this.printers.filter( p => { return p.moduleName != printer.moduleName &&  p.Name != printer.Name});
        }
            

    },
    openModalAddEditPrinter: function (e, that) {
        document.getElementById("printerForm").reset();
        this.isCreate = e.currentTarget.id == "addNewPrinter";

        if (!this.isCreate) {
            var printerName = e.currentTarget.dataset.name;
            var moduleName = e.currentTarget.dataset.module;
            var printer = that.printers.find(
                (m) => m.moduleName == moduleName && m.Name == printerName
            );


            // var printerType = moduleName.split('.')[1];

            var paramNames = Object.keys(printer);
            paramNames.forEach((p) => {
                var el = document.getElementById(p);
                if (el != null) {
                    if (el.nodeName == "INPUT") {
                        if (el.type == "checkbox")
                            el.checked = printer[p] == "true" || printer[p] == true;
                        else
                            el.value = printer[p];
                    } else if (el.nodeName == "SELECT") {
                        for (opt of el.children) {
                            if (opt.value == printer[p]) {
                                opt.selected = "selected";
                            }
                        }
                    }
                }
            });
        }

        M.updateTextFields();
        this.showHidePrinterFieldsByModuleName();

        var selectElements = document.querySelectorAll("#printerForm select");
        var modalElement = document.getElementById("printerModal");
        M.FormSelect.init(selectElements, {});
        var instances = M.Modal.init(modalElement, {});
        instances.open();

        var moduleNameElement = document.getElementById("moduleName").parentNode
            .childNodes[0];
        var deleteBtn = document.getElementById("removePrinterBtn");
        if (this.isCreate) {
            moduleNameElement.disabled = false;
            deleteBtn.classList.add("hide");
        } else {
            moduleNameElement.disabled = true;
            deleteBtn.classList.remove("hide");
        }
    },

    showHidePrinterFieldsByModuleName: function (e) {
        var shiftReportElements = document.querySelectorAll(".shift-report");
        var clientOrderElements = document.querySelectorAll(".client-order");
        var clientOrderVatElements = document.querySelectorAll(".client-order-vat");
        var selected = document.getElementById("moduleName").selectedOptions[0].value;

        if (selected.includes("ClientOrderPrinter")) {
            for (el of clientOrderElements) el.classList.remove("hide");
            for (el of shiftReportElements) el.classList.add("hide");
        } else if (selected.includes("ShiftReportPrinter")) {
            for (el of clientOrderElements) el.classList.add("hide");
            for (el of shiftReportElements) el.classList.remove("hide");
        }

        if(selected == "Outputs.ClientOrderPrinterVat")
            for (el of clientOrderVatElements) el.classList.remove("hide");
        else
            for (el of clientOrderVatElements) el.classList.add("hide");
    },

    savePrinter: async function (e) {
        var printer = this.getPrinterFormValues();
        var response = await this.saveModule(printer);
        if (response.success) {
            // if(this.isCreate)
            //     this.addNewPrinter(printer);

            var index = this.printers.findIndex( p => {return p.moduleName == printer.moduleName && p.Name == printer.Name});
            if(index > -1)
                this.printers[index] = printer;
            else
                this.printers.push(printer);

            document.querySelector('#printers-table tbody').innerHTML = '';

            this.printers.forEach((m) => {
                this.addNewPrinter(m);
            });

        }
    },

    getPrinterFormValues: function (e) {
        var form = document.getElementById("printerForm");
        // var selected =  document.getElementById('moduleName').selectedOptions[0].value;
        var module = {};
        for (el of form.elements) {
            if (el != null && !el.classList.contains('hide') &&  !el.classList.contains('select-dropdown')) {
                if (el.nodeName == "INPUT") {
                    if (el.type == "checkbox") 
                        module[el.id] = el.checked;
                    else
                        module[el.id] = el.value;
                } else if (el.nodeName == "SELECT") {
                    module[el.id] = el.selectedOptions[0].value;
                }
            }
        }

        return module;
    },

    getModuleFormValues: function (moduleName) {
        var form = document.getElementById(moduleName);
        var module = { moduleName: moduleName };
        var email = "";

        for (el of form.elements) {
            if (el != null && el.dataset.name && !el.classList.contains('hide')) {
                if (el.nodeName == "INPUT" || el.nodeName == 'TEXTAREA') {
                    if (el.type == "checkbox" || el.type == 'radio'){
                        // if(el.dataset.name == 'UpdateItemTypes') // reverse logic for this param
                            // module[el.dataset.name] = el.checked ? "false" : "true";
                        // else
                            module[el.dataset.name] = el.checked ? "true" : "false";
                    }
                    else {
                        var regex = /Vat[1-99]/gi;
                        const value = el.value.trim();

                        if(el.dataset.name.includes('Email'))
                            email += value + ";";
                        else if(el.dataset.name.match(regex)){
                            var vatKey = value;
                            var vatValue = el.parentElement.nextElementSibling.firstElementChild.value;
                            module[el.dataset.name] = vatKey + ';' + vatValue;
                        }
                        else {
                            module[el.dataset.name] = value;
                        }
                    }
                } else if (el.nodeName == "SELECT") {
                    const value = el.selectedOptions[0]?.value;
                    if(typeof value !== 'undefined')
                        module[el.dataset.name] = value;
                }
            }
        }

        if(email != "")
            module["Email"] = email;

        return module;
    },

    saveModule: async function (module) {
        var sessionToken = getCookie();
        var that = this;
        // delete module.isActive;
        return $.ajax({
            url: "data/save-module",
            data: {
                token: sessionToken,
                module: JSON.stringify(module),
            },
            dataType: "json",
            type: "POST",
            success: function (data) {
                if (data.success) {
                    M.toast({ html: "{Literal}Configuration Saved{/Literal}" });
                    document.getElementById('restartServerBtn').classList.remove('hide');
                }
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                } else {
                    M.toast({
                        html: "{Literal}There was a problem saving data{/Literal}",
                    });
                }
            },
            complete: function () { },
        });
    },

    removeModule: async function (module) {
        var sessionToken = getCookie();
        var that = this;

        return $.ajax({
            url: "data/remove-module",
            data: {
                token: sessionToken,
                module: JSON.stringify(module),
            },
            dataType: "json",
            type: "POST",
            success: function (data) {
                if (data.success) {
                    document.getElementById('restartServerBtn').classList.remove('hide');
                    M.toast({ html: `${module.moduleName} {Literal}Deactivated{/Literal}` });                
                }
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                } else {
                    M.toast({
                        html: "{Literal}There was a problem saving data{/Literal}",
                    });
                }
            },
        });
    },

    loadModules: function (module) {
        var paramNames = Object.keys(module);
        var form = document.getElementById(module.moduleName);
        // var isActiveElement = form.querySelector('[data-name="isActive"]');
        // isActiveElement.checked = true;

        paramNames.forEach((p) => {
            var el = form.querySelector(`[data-name="${p}" i]`);
            if (el != null) {
                if (el.nodeName == "INPUT" || el.nodeName == "TEXTAREA") {
                    if (el.type == "checkbox" || el.type == "radio")
                        el.checked = module[p] == "true" || module[p] == true;
                    else {
                        el.value = module[p];
                    }
                } else if (el.nodeName == "SELECT") {
                    for (opt of el.children) {
                        if (opt.value == module[p]) {
                            opt.selected = "selected";
                        }
                    }
                }
                el.dataset.value = module[p];
            } else if(p.startsWith("Vat")) 
                this.addVatCodeForSageLive( '', module[p], p);
        });

        M.updateTextFields();
    },

    onNeverSummarizeChange: function() {
        if(document.getElementById('NeverSummarize').checked){
            $('input[data-name="SummarizeAllCashSales"]').prop("disabled", true);
            $('input[data-name="SummarizeAllCashSales"]').prop('checked', false)
        }
        else{
            $('input[data-name="SummarizeAllCashSales"]').prop("disabled", false);
        }
    },

    getWooCommerceAPIAccess: function() {
        var webstoreUrl = document.getElementById('SiteUrl').value;
        if(webstoreUrl != '') {
            
            var returnUrl = encodeURIComponent(window.location.href);
            var callbackUrl = "https://enjgg691xujs.x.pipedream.net";
            var url = "https://" + webstoreUrl + "/wc-auth/v1/authorize?app_name=AccuPOS&scope=read_write&user_id=AccuPOS_user&return_url=" + returnUrl +"&callback_url=" + callbackUrl;
            window.open(url, '_blank');
        }
    },

    validateWebConnector: function() {
        // var isValid = true;
        // var form = document.getElementById('AccuServerIntegrator.AccuServerQBWebIntegrator');
        // if(form.ConnectViaHost.checked && form.companyFilePath.value == '')
        //     isValid = false;
        //     form.companyFilePath.classList.add('invalid');
        // else
        //     form.companyFilePath.classList.remove('invalid');


        // return isValid;
    

    },

    onMainServerSettingsOpen: function() {
        var that = App.serverConfiguration;
        var selectEl = document.getElementById('TipsGLAccount');
        var tipsTenderCode = document.getElementById('TipsTenderCode').value;
        if(tipsTenderCode.trim() != '') {
            document.getElementById('useTipsTenderCode').checked = true;
            var tipsTender = that.tenderTypes.find(t => t.id == tipsTenderCode);
            selectEl.value = tipsTender?.glAccount;
            selectEl.disabled = false;
        } else {
            selectEl.disabled = true;
        }
        
        M.FormSelect.init(document.getElementById('TipsGLAccount'));
    },

    onUseTipsTenderCodeChange: function() {
        var selectEl = document.getElementById('TipsGLAccount');
        selectEl.disabled = !document.getElementById('useTipsTenderCode').checked;
        // if(selectEl.disabled)
        //     document.getElementById('TipsTenderCode').value = '';
        M.FormSelect.init(selectEl, {});
    },

    setTipsTenderCode: async function() {
        var glAccount = document.getElementById('TipsGLAccount').value;
        var unsetTipsTenderCode = !document.getElementById('useTipsTenderCode').checked;

        var sessionToken = getCookie();
        var that = this;

        return $.ajax({
            url: "data/set-tips-tender-code",
            data: {
                token: sessionToken,
                tipsTenderGLAccount: glAccount,
                unsetTipsTenderCode: unsetTipsTenderCode
            },
            dataType: "json",
            type: "POST",
            success: function (data) {
                if (data.success) {
                    document.getElementById('TipsTenderCode').value = data.tipsTenderCode;
                    // M.toast({ html: "{Literal}Configuration Saved{/Literal}" });
                }
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                } else {
                    M.toast({
                        html: "{Literal}There was a problem setting Tips Tender Code{/Literal}",
                    });
                }
            },
            complete: function () { },
        });
    }

});