document.addEventListener('alpine:init', () => {
    Alpine.data('HF_AGG_APP', () => ({
        nonce: hfngAGGData.values.nonce,
        burnNonce: hfngAGGData.values.burnNonce,
        enableFileSystemScan: hfngAGGData.values.enable_filesystem_scan,
        disableFileEdit: hfngAGGData.values.disable_file_edit,
        enablePluginMonitoring: hfngAGGData.values.enable_plugin_monitoring,
        enableLoginRateLimit: hfngAGGData.values.enable_login_rate_limit,
        loginRateInterval: hfngAGGData.values.login_rate_interval,
        loginRateMax: hfngAGGData.values.login_rate_max,
        autoPatchRobots: hfngAGGData.values.auto_patch_robots,
        enabledURIPatterns: hfngAGGData.values.enabled_uri_patterns,
        uriPatterns:hfngAGGData.values.uri_patterns,
        featureEnabled: hfngAGGData.values.feature_enabled,
        checkbox_on: hfngAGGData.values.checkbox_on,
        checkbox_off: hfngAGGData.values.checkbox_off,
        myResult: '',
        myColor: 'hfng-success',           

        saveSettings() {
            fetch(hfngAGGData.ajaxurl, {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: new URLSearchParams({
                    action: 'happyfenceng_AGG_save_settings',
                    enable_filesystem_scan: this.enableFileSystemScan ? this.checkbox_on : this.checkbox_off,
                    disable_file_edit: this.disableFileEdit ? this.checkbox_on : this.checkbox_off,
                    enable_plugin_monitoring: this.enablePluginMonitoring ? this.checkbox_on : this.checkbox_off,
                    enable_login_rate_limit: this.enableLoginRateLimit ? this.checkbox_on : this.checkbox_off,
                    login_rate_interval: this.loginRateInterval,
                    login_rate_max: this.loginRateMax,
                    auto_patch_robots: this.autoPatchRobots,  
                    enabled_uri_patterns: JSON.stringify(this.enabledURIPatterns),                                                                            
                    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);
            });
        },
    }))
});
