<?php
/**
 * WAF AJAX Handler
 *
 * @package VMPFence
 * @since 2.0.0
 * @since 2.1.0 - Added hybrid local + API rule fetching
 * @since 2.2.1 Updated text-domain to vmpfence-security
 * @since 2.2.5 - Added Enhanced Audit Log integration for all WAF actions
 */

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

/**
 * WAF AJAX Handler Class
 *
 * @since 2.0.0
 */
class VMPFence_WAF_Ajax {

    /**
     * Initialize AJAX hooks
     *
     * @since 2.0.0
     */
    public static function init() {
        add_action('wp_ajax_vmpfence_toggle_waf_rule', array(__CLASS__, 'toggle_rule'));
        add_action('wp_ajax_vmpfence_toggle_waf_category', array(__CLASS__, 'toggle_category'));
        add_action('wp_ajax_vmpfence_sync_waf_rules', array(__CLASS__, 'sync_waf_rules'));
        // REMOVED: Old blocked IP sync handler - now in admin/ajax/blocked-ip-sync-ajax.php
        // add_action('wp_ajax_vmpfence_sync_blocked_ips', array(__CLASS__, 'sync_blocked_ips'));
    }

    /**
     * Toggle WAF rule via AJAX
     *
     * @since 2.0.0
     */
    public static function toggle_rule() {
        // Check for rule ID
        if (!isset($_POST['rule_id'])) {
            wp_send_json_error(__('Rule ID is required', 'vmpfence-security'));
            return;
        }

        $rule_id = intval($_POST['rule_id']);

        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'toggle_waf_rule_' . $rule_id)) {
            wp_send_json_error(__('Nonce verification failed', 'vmpfence-security'));
            return;
        }

        // Check user permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('You do not have permission to perform this action', 'vmpfence-security'));
            return;
        }

        // Toggle the rule
        $result = VMPFence_WAF_Rule::toggle_rule($rule_id);

        if ($result) {
            // Fetch the rule after toggle to get its current state and name
            $rule = VMPFence_WAF_Rule::get_by_id($rule_id);
            $enabled = $rule ? intval($rule['enabled']) : null;
            $rule_name = $rule ? ($rule['description'] ?: $rule['rule_id']) : $rule_id;
            do_action('vmpfence_waf_rule_toggled', $rule_id, $enabled, $rule_name);
            wp_send_json_success(__('Rule toggled successfully', 'vmpfence-security'));
        } else {
            wp_send_json_error(__('Failed to toggle rule', 'vmpfence-security'));
        }
    }
    
    /**
     * Toggle WAF category (enable/disable all rules in category) via AJAX
     *
     * @since 2.1.0
     */
    public static function toggle_category() {
        // Check for category
        if (!isset($_POST['category']) || !isset($_POST['nonce'])) {
            wp_send_json_error(__('Required parameters missing', 'vmpfence-security'));
            return;
        }

        // Verify nonce BEFORE sanitization (nonce was created with raw value)
        if (!wp_verify_nonce($_POST['nonce'], 'toggle_waf_category_' . $_POST['category'])) {
            wp_send_json_error(__('Nonce verification failed', 'vmpfence-security'));
            return;
        }

        // Now sanitize after nonce verification
        $category = sanitize_text_field($_POST['category']);
        $enable = isset($_POST['enable']) ? intval($_POST['enable']) : 0;

        // Check user permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('You do not have permission to perform this action', 'vmpfence-security'));
            return;
        }

        // Toggle all rules in the category (case-insensitive)
        global $wpdb;
        $table_name = $wpdb->prefix . 'vmpfence_waf_rules';
        
        $result = $wpdb->query(
            $wpdb->prepare(
                "UPDATE {$table_name} SET enabled = %d WHERE LOWER(category) = LOWER(%s)",
                $enable,
                $category
            )
        );

        // Clear WAF rules cache to force reload
        wp_cache_delete('vmpfence_waf_enabled_rules');

        if ($result !== false) {
            do_action('vmpfence_waf_category_toggled', $category, $enable);
            $action_text = $enable ? 'enabled' : 'disabled';
            if ($result > 0) {
                wp_send_json_success(sprintf(__('%d rules %s successfully', 'vmpfence-security'), $result, $action_text));
            } else {
                // No rows updated - already in desired state
                wp_send_json_success(sprintf(__('All rules already %s', 'vmpfence-security'), $action_text));
            }
        } else {
            wp_send_json_error(__('Failed to toggle category', 'vmpfence-security'));
        }
    }
    
    /**
     * Sync WAF rules from API
     *
     * @since 2.1.0
     */
    public static function sync_waf_rules() {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'vmpfence_sync_waf_rules')) {
            wp_send_json_error('Nonce verification failed');
            return;
        }

        // Check user permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error('You do not have permission to perform this action');
            return;
        }
        
        // Perform sync
        $stats = VMPFence_WAF_Rule::sync_from_api();

        if (!empty($stats['errors'])) {
            wp_send_json_error(implode(', ', $stats['errors']));
        } else {
            $message = sprintf(
                'Synced %d WAF rules from API (%d new, %d updated)',
                $stats['total'],
                $stats['new'],
                $stats['updated']
            );
            
            wp_send_json_success(array('message' => $message, 'stats' => $stats));
        }
    }
    
    /**
     * Sync Blocked IPs from API (background, non-blocking)
     *
     * @since 2.1.0
     */
    public static function sync_blocked_ips() {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'vmpfence_sync_ips')) {
            wp_send_json_error('Nonce verification failed');
            return;
        }

        // Check user permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error('You do not have permission to perform this action');
            return;
        }
        
        // Perform sync using the correct class
        $result = VMPFence_Blocked_IP_Sync::sync_from_api();

        if (isset($result['success']) && $result['success']) {
            wp_send_json_success(array(
                'imported' => $result['imported'],
                'total' => isset($result['total_count']) ? $result['total_count'] : 0,
                'message' => sprintf('Synced %d blocked IPs from API', $result['imported'])
            ));
        } else {
            $error_msg = isset($result['errors']) ? implode(', ', $result['errors']) : 'Unknown error';
            wp_send_json_error('Sync failed: ' . $error_msg);
        }
    }
}

// Initialize AJAX hooks
VMPFence_WAF_Ajax::init();
