document.addEventListener('alpine:init', () => {
    Alpine.data('HF_BUN_APP', () => ({
        nonce: hfngBUNData.values.nonce,
        burnNonce: hfngBUNData.values.burnNonce,
        autoremoveDangerousFiles: hfngBUNData.values.auto_remove_dangerous_files,
        allRestEndpoints: hfngBUNData.values.all_rest_endpoints,
        blockedEndpoints: hfngBUNData.values.blocked_endpoints,
        enableRestBlocking: hfngBUNData.values.enable_rest_blocking,
        enableBlockUserEnum: hfngBUNData.values.block_user_enum,
        enable404Trap: hfngBUNData.values.enable_404_trap,        
        trap404Mode: hfngBUNData.values.trap_404_mode,
        trap404MaxWords: hfngBUNData.values.trap_404_MAX_WORDS,
        pages: hfngBUNData.values.pages,
        selectedPageId:hfngBUNData.values.trap_404_template_page,
        myResult: '',
        myColor: 'hfng-success',           
        featureEnabled: hfngBUNData.values.feature_enabled,
        checkbox_on: hfngBUNData.values.checkbox_on,
        checkbox_off: hfngBUNData.values.checkbox_off,

        saveSettings() {
            fetch(hfngBUNData.ajaxurl, {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: new URLSearchParams({
                    action: 'happyfenceng_BUN_save_settings',
                    auto_remove_dangerous_files: this.autoremoveDangerousFiles ? this.checkbox_on : this.checkbox_off,                    
                    enable_rest_blocking: this.enableRestBlocking ? this.checkbox_on : this.checkbox_off,                    
                    blocked_endpoints: this.blockedEndpoints,
                    block_user_enum: this.enableBlockUserEnum,
                    enable_404_trap: this.enable404Trap,
                    trap_404_mode: this.trap404Mode,
                    trap_404_MAX_WORDS: this.trap404MaxWords,
                    trap_404_template_page: this.selectedPageId,
                    security: this.nonce,
                    burn: this.burnNonce 
                })
            })
            .then(res => res.json())
           .then(res => {                
                    this.myResult = res.message;
                    this.myColor = (res.warning)? 'hfng-error':'hfng-success';
                    if (res.result === 'OK'){                                          
                        if(res.burn) {                        
                                this.burnNonce = res.burn; 
                        }
                    }  else {
                    this.myColor = 'hfng-error';
                }
                setTimeout(() => this.myResult = '', 2000);
            });
        },
    }))
});
