<?php
/**
 * WAF Optimizer AJAX Handler
 * 
 * Handles AJAX requests for WAF optimization operations
 * 
 * @package VMPFence
 * @since 2.2.4
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

class VMPFence_WAF_Optimizer_Ajax {
    
    public function __construct() {
        // Register AJAX handlers
        add_action('wp_ajax_vmpfence_get_waf_status', array($this, 'get_waf_status'));
        add_action('wp_ajax_vmpfence_download_htaccess', array($this, 'download_htaccess'));
        add_action('wp_ajax_vmpfence_dismiss_waf_notice', array($this, 'dismiss_waf_notice')); 
    }
    
    /**
     * Get WAF optimization status
     * Returns server type, multisite status, subdirectory detection, and optimization state
     */
    public function get_waf_status() {        
        // Verify nonce
        if (!check_ajax_referer('vmpfence_waf_optimizer_nonce', 'nonce', false)) {
            wp_send_json_error(array(
                'message' => 'Security check failed.'
            ));
            return;
        }
        
        // Check user permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array(
                'message' => 'Unauthorized access.'
            ));
            return;
        }
        
        // Get optimization status from controller
        if (!class_exists('VMPFence_WAF_Optimizer')) {
            wp_send_json_error(array(
                'message' => 'WAF Optimizer class not available.'
            ));
            return;
        }
        
        $status = VMPFence_WAF_Optimizer::get_optimization_status();        
        wp_send_json_success($status);
    }
    
    /**
     * Download .htaccess backup file
     * Streams the backup file to browser as download
     */
    public function download_htaccess() {        
        // Verify nonce
        if (!check_ajax_referer('vmpfence_waf_optimizer_nonce', 'nonce', false)) {
            wp_die('Security check failed.');
        }
        
        // Check user permissions
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized access.');
        }
        
        // Get backup file path
        $htaccess_file = ABSPATH . '.htaccess';
        
        if (!file_exists($htaccess_file)) {
            wp_die('.htaccess file not found.');
        }
        
        // Create backup directory
        $upload_dir = wp_upload_dir();
        $backup_dir = $upload_dir['basedir'] . '/vmpfence-backups';
        
        if (!file_exists($backup_dir)) {
            wp_mkdir_p($backup_dir);
        }
        
        // Copy .htaccess to backup directory (overwrite if exists)
        $backup_file_path = $backup_dir . '/.htaccess';
        @copy($htaccess_file, $backup_file_path);
        
        // Get site name and sanitize for filename
        $site_name = get_bloginfo('name');
        $site_name = sanitize_file_name($site_name);
        $site_name = str_replace(' ', '-', $site_name);
        $site_name = strtolower($site_name);
                
        // Set headers for download
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="htaccess-backup-' . date('Y-m-d-His') . '-' . $site_name . '.txt"');
        header('Content-Length: ' . filesize($htaccess_file));
        header('Cache-Control: no-cache, must-revalidate');
        header('Expires: 0');
        
        // Output file contents
        readfile($htaccess_file);        
        exit;
    }
    
    /**
     * Dismiss WAF optimization notice/banner
     * Saves dismiss state to database
     */
    public function dismiss_waf_notice() {        
        // Verify nonce
        if (!check_ajax_referer('vmpfence_waf_optimizer_nonce', 'nonce', false)) {
            wp_send_json_error(array(
                'message' => 'Security check failed.'
            ));
            return;
        }
        
        // Check user permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array(
                'message' => 'Unauthorized access.'
            ));
            return;
        }
        
        // Save dismiss state
        $result = VMPFence_Config::set('vmpfence_waf_notice_dismissed', 1);
        
        if ($result !== false) {
            wp_send_json_success(array(
                'message' => 'Notice dismissed.'
            ));
        } else {
            wp_send_json_error(array(
                'message' => 'Failed to save dismiss state.'
            ));
        }
    }
}

// Initialize the AJAX handler
new VMPFence_WAF_Optimizer_Ajax();
