;(function($){

class FensePageOptions {

    __find(id,itemOrder,add = true) {
        if (add) {
            $("#form" + id).find(`tr:eq(${itemOrder})`).addClass('hide');
        } else {
            $("#form" + id).find(`tr:eq(${itemOrder})`).removeClass('hide');
        }
    }

    onLoad() {

        const se = $('select[name=FENSE_BPVT_DEVOZON_enable_on_custom]').val();
        const st = $('select[name=FENSE_BPVT_DEVOZON_protection_mode]').val();
        const sy = $('select[name=FENSE_BPVT_DEVOZON_crawlers_bots]').val();

        const whitelisting_enable = $('input[name=FENSE_BPVT_DEVOZON_ip_whitelisting_enable]').prop('checked');
        const blacklisting_enable = $('input[name=FENSE_BPVT_DEVOZON_ip_blacklisting_enable]').prop('checked');

        if (se === 'all') {
            this.__find(1,3)
            this.__find(1,4)
            this.__find(1,5)
            this.__find(1,6)
        }

        if (st === 'message') {
            this.__find(2,2)
            this.__find(2,3)
        }

        if (st === 'redirect') {
            this.__find(2,1)
            this.__find(2,3)
        }

        if (st === 'show_content') {
            this.__find(2,1)
            this.__find(2,2)
        }

        if (sy === 'yes') {
            this.__find(2,11,false)
        } else {
            this.__find(2,11)
        }

        if (blacklisting_enable) {
            this.__find(5,4,false)
            this.__find(5,5,false)
        } else {
            this.__find(5,4)
            this.__find(5,5)
        }

        if (whitelisting_enable) {
            this.__find(5,1,false)
            this.__find(5,2,false)
        } else {
            this.__find(5,1)
            this.__find(5,2)
        }

       this.loadEvents()
    }

    saveSettings() {
        /** if not Valid Return **/
        if (!this.__checkIpSection()) return false;

        const submit = document.getElementById("submit");

        submit.innerHTML = `<i class="fas fa-floppy-disk"></i> ${this.__getLang(2)} ...`;
        submit.className = 'btn btn-primary mt-4 disabled';

        for (let i = 1; i < 6; i++) {


            // (A) GET FORM DATA
            const form = document.getElementById("form" + i);

            const data = new FormData(form);

            // (B) AJAX
            const xhr = new XMLHttpRequest();
            xhr.open("POST", this.__getLang(3));

            // What to do when server responds
            xhr.onload =  () => {
                if (i === 5) {
                    if (xhr.status === 200) {
                        submit.innerHTML = `<i class="fas fa-floppy-disk"></i>` + this.__getLang(4);
                        submit.className = 'btn btn-primary mt-4';

                        this.__alert(5,'success')

                            // Send the AJAX request
                            $.ajax({
                                type: 'POST',
                                url: this.__getLang(6),
                                data: {
                                    action: 'fense_bpvt_save_settings',
                                },
                            });
                    } else {
                        submit.innerHTML = '<i class="fas fa-floppy-disk"></i> ' + this.__getLang(4);
                        submit.className = 'btn btn-primary mt-4';

                        this.__alert(1)
                    }
                }

            }

            xhr.send(data);
        }

        // (C) PREVENT HTML FORM SUBMIT
        return false;
    }

    __getLang(id) {
        return document.getElementById("fense-bpvt-settings-page").dataset['s' + id] ?? null;
    }

    __alert(id,type = 'danger' ,input = null) {
        document.getElementById("alert").innerHTML = `<div class="alert alert-${type} alert-border-left alert-dismissible fade show mb-xl-0 mt-4" role="alert">
                            <i class="ri-error-warning-line me-3 align-middle fs-16"></i>
                            ${this.__getLang(id)}
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>`;

        setTimeout(() => {
            if (input) input.reportValidity();
        }, 500);

        setTimeout(() => {
            document.getElementById("alert").innerHTML = '';
        }, 3000);
    }

    __checkIpSection() {

        let invalid = false;
        document.getElementById("form5").querySelectorAll('[id^="ip-range-container"] input[type="text"]').forEach(input => {
            if (!this.__isValidIP(input.value)) {

                window.location.hash = 'ips';

                const hash = window.location.hash;
                if (hash) {
                    const trigger = document.querySelector(`.nav-link[href="${hash}"]`);
                    if (trigger) new bootstrap.Tab(trigger).show();
                }

                this.__alert(1,'danger',input);

                invalid = true;
            }
        });
        return !invalid;
    }

    __isValidIP(ip) {
        const parts = ip.trim().split('.');
        if (parts.length !== 4) return false;
        return parts.every(n => {
            const num = Number(n);
            return String(num) === n && num >= 0 && num <= 255;
        });
    }

    loadEvents() {
       this.__EV_select_enable_on_custom()
       this.__EV_select_protection_mode()
       this.__EV_crawlers_bots()
       this.__EV_ip_whitelisting_enable()
       this.__EV_ip_blacklisting_enable()
       this.__EV_windowHash_Navigate()
    }
    __EV_select_enable_on_custom() {

        const that = this;

        $(document).on('change', 'select[name=FENSE_BPVT_DEVOZON_enable_on_custom]', function () {
            const se = $('select[name=FENSE_BPVT_DEVOZON_enable_on_custom]').val();

            if (se === 'all') {
                that.__find(1,3)
                that.__find(1,4)
                that.__find(1,5)
                that.__find(1,6)

            } else {
                that.__find(1,3,false)
                that.__find(1,4,false)
                that.__find(1,5,false)
                that.__find(1,6,false)
            }
        });
    }
    __EV_select_protection_mode() {

        const that = this;

        $(document).on('change', 'select[name=FENSE_BPVT_DEVOZON_protection_mode]', function () {

            const st = $('select[name=FENSE_BPVT_DEVOZON_protection_mode]').val();

            that.__find(2,1,false)
            that.__find(2,2,false)
            that.__find(2,3,false)

            switch (st) {
                case 'message':
                    that.__find(2,2)
                    that.__find(2,3)
                    break;
                case 'redirect':
                    that.__find(2,1)
                    that.__find(2,3)
                    break;
                case 'show_content':
                    that.__find(2,1)
                    that.__find(2,2)
                    break;
                default:
                // code block
            }

        });
    }
    __EV_crawlers_bots() {

        const that = this;

        $(document).on('change', 'select[name=FENSE_BPVT_DEVOZON_crawlers_bots]', function () {

            const st = $('select[name=FENSE_BPVT_DEVOZON_crawlers_bots]').val();

            switch (st) {
                case 'yes':
                    that.__find(2,11,false)
                    break;
                case 'no':
                    that.__find(2,11)
                    break;
                default:
                // code block
            }

        });
    }
    __EV_ip_whitelisting_enable() {

        const that = this;

        $(document).on('change', 'input[name=FENSE_BPVT_DEVOZON_ip_whitelisting_enable]', function () {
            switch ($(this).prop('checked')) {
                case false:
                    that.__find(5,1)
                    that.__find(5,2)
                    break;
                case true:
                    that.__find(5,1,false)
                    that.__find(5,2,false)
                    break;
            }
        });
    }
    __EV_ip_blacklisting_enable() {

        const that = this;

        $(document).on('change', 'input[name=FENSE_BPVT_DEVOZON_ip_blacklisting_enable]', function () {
            switch ($(this).prop('checked')) {
                case false:
                    that.__find(5,4)
                    that.__find(5,5)
                    break;
                case true:
                    that.__find(5,4,false)
                    that.__find(5,5,false)
                    break;
            }
        });
    }
    __EV_windowHash_Navigate() {
        // on page load, activate from URL
        const hash = window.location.hash;
        if (hash) {
            const trigger = document.querySelector(`.nav-link[href="${hash}"]`);
            if (trigger) new bootstrap.Tab(trigger).show();
        }

        // when a tab is shown, update the URL
        document.querySelectorAll('a[data-bs-toggle="pill"]').forEach(tab => {
            tab.addEventListener('shown.bs.tab', e => {
                history.replaceState(null, null, e.target.getAttribute('href'));
            });
        });
    }
}

$(function(){
    const loader = new FensePageOptions();

    loader.onLoad();

    $('#submit').on('click', function(e) {
        // handler code
        loader.saveSettings()
    });
});

})(jQuery);
