/**
 * WAF Optimization JavaScript
 * 
 * Handles modal interactions and AJAX calls for WAF optimization
 * 
 * @package VMPFence
 * @since 2.2.4
 * @since 2.2.5 Added WAF optimization modal functionality in All Options page
 */

(function($) {
    'use strict';
    
    // State tracking
    let downloadCompleted = false;
    let serverStatus = null;
    
    /**
     * Initialize WAF optimization functionality
     */
    $(document).ready(function() {
        // Load initial status
        loadWAFStatus();
        
        // Bind banner buttons
        $('#vmpfence-waf-banner-configure').on('click', function(e) {
            e.preventDefault();
            openOptimizationModal();
        });
        
        $('#vmpfence-waf-banner-dismiss').on('click', function(e) {
            e.preventDefault();
            dismissWAFBanner();
        });
        
        // Bind firewall options buttons
        $('#optimize-firewall, #vmpfence-ao-optimize-firewall').on('click', function(e) {
            e.preventDefault();
            openOptimizationModal();
        });
        
        $('#remove-extended-protection, #vmpfence-ao-remove-extended-protection').on('click', function(e) {
            e.preventDefault();
            openRemovalModal();
        });
    });
    
    /**
     * Load WAF status from server
     */
    function loadWAFStatus() {
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'vmpfence_get_waf_status',
                nonce: vmpfence_waf_ajax.waf_optimizer_nonce
            },
            success: function(response) {
                if (response.success) {
                    serverStatus = response.data;
                } else {
                    console.error('[VMP WAF] Failed to load status:', response.data);
                }
            },
            error: function(xhr, status, error) {
                console.error('[VMP WAF] AJAX error loading status:', error);
            }
        });
    }
    
    /**
     * Open optimization modal
     */
    window.vmpfenceOpenOptimizationModal = function() {        
        // Reset state
        downloadCompleted = false;
        $('#vmpfence-waf-continue-btn').prop('disabled', true);
        $('#vmpfence-waf-error-display').hide();
        
        // Show modal and config screen
        $('#vmpfence-waf-optimization-modal').fadeIn(200);
        $('#vmpfence-waf-config-screen').show();
        $('#vmpfence-waf-processing-screen').hide();
        $('#vmpfence-waf-success-screen').hide();
        
        // Populate server info and file path
        populateServerInfo();
        populateOptServerConfig();
    };
    
    /**
     * Populate server information in modal
     */
    function populateServerInfo() {        
        if (!serverStatus) {            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'vmpfence_get_waf_status',
                    nonce: vmpfence_waf_ajax.waf_optimizer_nonce
                },
                success: function(response) {                    
                    if (response.success) {
                        serverStatus = response.data;
                        updateServerInfoDisplay();
                        populateOptServerConfig();
                    } else {
                        showError(response.data);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('[VMP WAF] AJAX error:', error);
                    showError('Failed to load server information. Please try again.');
                }
            });
        } else {
            updateServerInfoDisplay();
        }
    }
    
    /**
     * Update server info display in modal
     */
    function updateServerInfoDisplay() {
        // Display file path in optimization modal
        if (serverStatus && serverStatus.waf_file_path) {
            $('#vmpfence-waf-file-path-display-opt').text(serverStatus.waf_file_path);
        }
        
        // Show warnings
        if (!serverStatus.server_type || (serverStatus.server_type.toLowerCase() !== 'apache' && serverStatus.server_type.toLowerCase() !== 'litespeed')) {
            $('#vmpfence-waf-server-warning-text').text(
                'Your server (' + serverStatus.server_type + ') does not support .htaccess files. ' +
                'Auto-prepend firewall optimization is not available for your server type.'
            );
            $('#vmpfence-waf-server-warning').show();
            $('#vmpfence-waf-continue-btn').prop('disabled', true);
        }
        
        if (serverStatus.is_subdirectory) {
            $('#vmpfence-waf-subdirectory-warning').show();
        }
        
        if (serverStatus.is_multisite_subsite) {
            $('#vmpfence-waf-multisite-warning').show();
            $('#vmpfence-waf-continue-btn').prop('disabled', true);
        }
    }
    
    /**
     * Populate server configuration dropdown for optimization modal
     */
    function populateOptServerConfig() {
        if (!serverStatus || !serverStatus.server_type) {
            return;
        }
        
        const serverType = serverStatus.server_type.toLowerCase();
        const $select = $('#vmpfence-waf-server-config-select-opt');
        let detectedValue = '';
        
        if (serverType.includes('apache')) {
            detectedValue = 'apache';
        } else if (serverType.includes('litespeed')) {
            detectedValue = 'litespeed';
        }
        
        if (detectedValue) {
            $select.val(detectedValue);
            const $option = $select.find('option[value="' + detectedValue + '"]');
            const originalText = $option.text();
            $option.text(originalText + ' (recommended based on our tests)');
        }
    }
    
    /**
     * Download .htaccess backup
     */
    window.vmpfenceDownloadHtaccess = function() {        
        // Create hidden iframe for download
        let downloadUrl = ajaxurl + '?action=vmpfence_download_htaccess&nonce=' + vmpfence_waf_ajax.waf_optimizer_nonce;
        let iframe = $('<iframe>', {
            src: downloadUrl,
            style: 'display: none;'
        });
        
        $('body').append(iframe);
        
        // Mark download as completed and enable continue button
        setTimeout(function() {
            downloadCompleted = true;
            $('#vmpfence-waf-continue-btn').prop('disabled', false);
            $('#vmpfence-waf-removal-continue-btn').prop('disabled', false);            
            // Remove iframe after a delay
            setTimeout(function() {
                iframe.remove();
            }, 2000);
        }, 500);
    };
    
    /**
     * Start WAF optimization process
     */
    window.vmpfenceStartOptimization = function() {        
        if (!downloadCompleted) {
            alert('Please download the .htaccess backup before continuing.');
            return;
        }
        
        // Show processing screen
        $('#vmpfence-waf-config-screen').hide();
        $('#vmpfence-waf-processing-screen').show();
        
        // Call existing AJAX handler
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'vmpfence_enable_extended_protection',
                nonce: vmpfence_firewall_ajax.protection_level_nonce
            },
            success: function(response) {                
                if (response.success) {
                    // Generate random delay between 10-30 seconds (10000-30000 ms)
                    const randomDelay = Math.floor(Math.random() * (30000 - 10000 + 1)) + 10000;
                    
                    // Automatically transition to success screen after random delay
                    setTimeout(function() {
                        showSuccessScreen();
                    }, randomDelay);
                } else {
                    console.error('[VMP WAF] Optimization failed:', response.data);
                    showError(response.data);
                    $('#vmpfence-waf-processing-screen').hide();
                    $('#vmpfence-waf-config-screen').show();
                }
            },
            error: function(xhr, status, error) {
                console.error('[VMP WAF] AJAX error during optimization:', error);
                showError('An error occurred during optimization. Please check the error logs.');
                $('#vmpfence-waf-processing-screen').hide();
                $('#vmpfence-waf-config-screen').show();
            }
        });
    };
    
    /**
     * Show success screen
     */
    function showSuccessScreen() {
        $('#vmpfence-waf-processing-screen').hide();
        $('#vmpfence-waf-success-screen').show();
    }
    
    /**
     * Close optimization modal
     */
    window.vmpfenceCloseOptimizationModal = function() {
        $('#vmpfence-waf-optimization-modal').fadeOut(200);
        
        // Reload page if success screen was shown
        if ($('#vmpfence-waf-success-screen').is(':visible')) {
            setTimeout(function() {
                location.reload();
            }, 300);
        }
    };
    
    /**
     * Open removal modal
     */
    window.vmpfenceOpenRemovalModal = function() {        
        // Reset state
        downloadCompleted = false;
        $('#vmpfence-waf-removal-continue-btn').prop('disabled', true);
        $('#vmpfence-waf-removal-error-display').hide();
        
        // Show modal and config screen
        $('#vmpfence-waf-removal-modal').fadeIn(200);
        $('#vmpfence-waf-removal-config-screen').show();
        $('#vmpfence-waf-removal-processing-screen').hide();
        $('#vmpfence-waf-removal-success-screen').hide();
        
        // Display file path and populate server config
        if (serverStatus && serverStatus.waf_file_path) {
            $('#vmpfence-waf-file-path-display').text(serverStatus.waf_file_path);
            populateServerConfig();
        } else {
            loadWAFStatus();
            setTimeout(function() {
                if (serverStatus && serverStatus.waf_file_path) {
                    $('#vmpfence-waf-file-path-display').text(serverStatus.waf_file_path);
                    populateServerConfig();
                }
            }, 500);
        }
    };
    
    /**
     * Populate server configuration dropdown
     */
    function populateServerConfig() {
        if (!serverStatus || !serverStatus.server_type) {
            return;
        }
        
        const serverType = serverStatus.server_type.toLowerCase();
        const $select = $('#vmpfence-waf-server-config-select');
        let detectedValue = '';
        
        // Determine which server configuration was detected
        if (serverType.includes('apache')) {
            detectedValue = 'apache';
        } else if (serverType.includes('litespeed')) {
            detectedValue = 'litespeed';
        }
        // TODO: Add support for more server types later
        // else if (serverType.includes('nginx')) {
        //     detectedValue = 'nginx';
        // } else if (serverType.includes('iis')) {
        //     detectedValue = 'iis';
        // }
        
        // Set the detected option as selected and add recommended text
        if (detectedValue) {
            $select.val(detectedValue);
            const $option = $select.find('option[value="' + detectedValue + '"]');
            const originalText = $option.text();
            $option.text(originalText + ' (recommended based on our tests)');
        }
    }
    
    /**
     * Start WAF removal process
     */
    window.vmpfenceStartRemoval = function() {        
        if (!downloadCompleted) {
            alert('Please download the .htaccess backup before continuing.');
            return;
        }
        
        // Show processing screen
        $('#vmpfence-waf-removal-config-screen').hide();
        $('#vmpfence-waf-removal-processing-screen').show();
                
        // Call existing AJAX handler
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'vmpfence_disable_extended_protection',
                nonce: vmpfence_firewall_ajax.protection_level_nonce
            },
            success: function(response) {                
                if (response.success) {
                    // Generate random delay between 10-30 seconds (10000-30000 ms)
                    const randomDelay = Math.floor(Math.random() * (30000 - 10000 + 1)) + 10000;
                    
                    // Automatically transition to success screen after random delay
                    setTimeout(function() {
                        showRemovalSuccessScreen();
                    }, randomDelay);
                } else {
                    console.error('[VMP WAF] Removal failed:', response.data);
                    showRemovalError(response.data);
                    $('#vmpfence-waf-removal-processing-screen').hide();
                    $('#vmpfence-waf-removal-config-screen').show();
                }
            },
            error: function(xhr, status, error) {
                console.error('[VMP WAF] AJAX error during removal:', error);
                showRemovalError('An error occurred during removal. Please check the error logs.');
                $('#vmpfence-waf-removal-processing-screen').hide();
                $('#vmpfence-waf-removal-config-screen').show();
            }
        });
    };
    
    /**
     * Show removal success screen
     */
    function showRemovalSuccessScreen() {        
        $('#vmpfence-waf-removal-processing-screen').hide();
        $('#vmpfence-waf-removal-success-screen').show();
    }
    
    /**
     * Close removal modal
     */
    window.vmpfenceCloseRemovalModal = function() {
        $('#vmpfence-waf-removal-modal').fadeOut(200);
        
        // Reload page if success screen was shown
        if ($('#vmpfence-waf-removal-success-screen').is(':visible')) {
            setTimeout(function() {
                location.reload();
            }, 300);
        }
    };
    
    /**
     * Dismiss WAF banner
     */
    function dismissWAFBanner() {
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'vmpfence_dismiss_waf_notice',
                nonce: vmpfence_waf_ajax.waf_optimizer_nonce
            },
            success: function(response) {
                if (response.success) {
                    $('#vmpfence-waf-optimization-banner').fadeOut(200);
                } else {
                    console.error('[VMP WAF] Failed to dismiss banner:', response.data);
                }
            },
            error: function(xhr, status, error) {
                console.error('[VMP WAF] AJAX error dismissing banner:', error);
            }
        });
    }
    
    /**
     * Show error message in optimization modal
     */
    function showError(message) {
        console.error('[VMP WAF] Showing error:', message);
        
        $('#vmpfence-waf-error-message').text(message);
        $('#vmpfence-waf-error-display').show();
    }
    
    /**
     * Show error message in removal modal
     */
    function showRemovalError(message) {
        console.error('[VMP WAF] Showing removal error:', message);
        
        $('#vmpfence-waf-removal-error-message').text(message);
        $('#vmpfence-waf-removal-error-display').show();
    }
    
    // Expose functions for onclick handlers
    window.openOptimizationModal = window.vmpfenceOpenOptimizationModal;
    window.openRemovalModal = window.vmpfenceOpenRemovalModal;
    
})(jQuery);
