<?php
/**
 * Allowlist AJAX Handler
 * 
 * Handles AJAX requests for allowlist management.
 * Phase 1: WAF Parameter Allowlist operations.
 * @since 2.0.0
 * @since 2.2.5 -- Added Enhanced Audit Log integration for allowlist actions
 * @package VMPFence
 * @subpackage Firewall\Ajax
 */

if (!defined('ABSPATH')) {
    exit;
}

class VMPFence_Allowlist_Ajax {
    
    /**
     * Initialize AJAX handlers
     */
    public static function init() {
        add_action('wp_ajax_vmpfence_add_param_allowlist', array(__CLASS__, 'add_param_allowlist'));
        add_action('wp_ajax_vmpfence_remove_param_allowlist', array(__CLASS__, 'remove_param_allowlist'));
        add_action('wp_ajax_vmpfence_toggle_param_allowlist', array(__CLASS__, 'toggle_param_allowlist'));
        add_action('wp_ajax_vmpfence_get_allowlist_data', array(__CLASS__, 'get_allowlist_data'));
    }
    
    /**
     * Add parameter to allowlist
     * 
     * Handles form submission from admin UI.
     */
    public static function add_param_allowlist() {
        // Verify nonce
        check_ajax_referer('vmpfence_allowlist_nonce', 'nonce');
        
        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Insufficient permissions'));
            return;
        }
        
        // Sanitize inputs
        $path = isset($_POST['path']) ? sanitize_text_field($_POST['path']) : '';
        $param_key = isset($_POST['param_key']) ? sanitize_text_field($_POST['param_key']) : '';
        $param_type = isset($_POST['param_type']) ? sanitize_text_field($_POST['param_type']) : 'POST Body';
        $rule_id = isset($_POST['rule_id']) ? sanitize_text_field($_POST['rule_id']) : '';
        
        if ($param_type === 'Header') {
            $param_key = strtoupper($param_key);
        }
        
        // Validate required fields
        if (empty($path) || empty($param_key) || empty($rule_id)) {
            wp_send_json_error(array('message' => 'Missing required fields'));
            return;
        }
        
        // Prepare metadata
        $metadata = array(
            'source' => 'Allowlisted via Firewall Options page',
            'param_type' => $param_type
        );
        
        // Check if entry already exists (note: function expects rule_id, path, param_key)
        if (VMPFence_Param_Allowlist::is_rule_param_allowlisted($rule_id, $path, $param_key)) {
            wp_send_json_error(array(
                'message' => 'An allowlist entry for this URL and parameter already exists.',
                'duplicate' => true
            ));
            return;
        }
        
        // Add to allowlist
        $result = VMPFence_Param_Allowlist::allowlist_rule_for_param($path, $param_key, $rule_id, $metadata);
        
        if ($result) {
            $all_data = VMPFence_Param_Allowlist::get_all_allowlisted_params();

            // Fire audit log hook
            do_action('vmpfence_waf_allow_entry_created', array(
                'path'      => $path,
                'param_key' => $param_key,
                'rule_id'   => $rule_id,
            ));

            wp_send_json_success(array(
                'message' => 'Parameter allowlisted successfully',
                'data' => $all_data
            ));
        } else {
            wp_send_json_error(array('message' => 'Failed to add allowlist entry'));
        }
    }
    
    /**
     * Remove parameter from allowlist
     */
    public static function remove_param_allowlist() {
        // Verify nonce
        check_ajax_referer('vmpfence_allowlist_nonce', 'nonce');
        
        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Insufficient permissions'));
            return;
        }
        
        // Sanitize inputs
        $path = isset($_POST['path']) ? sanitize_text_field($_POST['path']) : '';
        $param_key = isset($_POST['param_key']) ? sanitize_text_field($_POST['param_key']) : '';
        $rule_id = isset($_POST['rule_id']) ? sanitize_text_field($_POST['rule_id']) : '';
        
        // Validate required fields
        if (empty($path) || empty($param_key) || empty($rule_id)) {
            wp_send_json_error(array('message' => 'Missing required fields'));
            return;
        }
        
        // Remove from allowlist
        $result = VMPFence_Param_Allowlist::remove_allowlist($path, $param_key, $rule_id);
        
        if ($result) {
            // Fire audit log hook
            do_action('vmpfence_waf_allow_entry_deleted', $rule_id);

            $all_data = VMPFence_Param_Allowlist::get_all_allowlisted_params();
            
            wp_send_json_success(array(
                'message' => 'Allowlist entry removed successfully',
                'data' => $all_data
            ));
        } else {
            wp_send_json_error(array('message' => 'Failed to remove allowlist entry'));
        }
    }
    
    /**
     * Toggle allowlist entry (enable/disable)
     */
    public static function toggle_param_allowlist() {
        // Verify nonce
        check_ajax_referer('vmpfence_allowlist_nonce', 'nonce');
        
        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Insufficient permissions'));
            return;
        }
        
        // Sanitize inputs
        $path = isset($_POST['path']) ? sanitize_text_field($_POST['path']) : '';
        $param_key = isset($_POST['param_key']) ? sanitize_text_field($_POST['param_key']) : '';
        $rule_id = isset($_POST['rule_id']) ? sanitize_text_field($_POST['rule_id']) : '';
        
        // Validate required fields
        if (empty($path) || empty($param_key) || empty($rule_id)) {
            wp_send_json_error(array('message' => 'Missing required fields'));
            return;
        }
        
        // Toggle entry
        $result = VMPFence_Param_Allowlist::toggle_allowlist($path, $param_key, $rule_id);
        
        if ($result) {
            // Check the actual enabled state after toggle
            $composite_key = VMPFence_Param_Allowlist::generate_composite_key($path, $param_key);
            $allowlist = VMPFence_Config::get('allowlisted_url_params', array());
            $is_enabled = empty($allowlist[$composite_key][$rule_id]['disabled']);

            // Fire audit log hook
            do_action('vmpfence_waf_allow_entry_toggled', $rule_id, $is_enabled);

            wp_send_json_success(array(
                'message' => 'Allowlist entry toggled successfully',
                'data' => VMPFence_Param_Allowlist::get_all_allowlisted_params()
            ));
        } else {
            wp_send_json_error(array('message' => 'Failed to toggle allowlist entry'));
        }
    }
    
    /**
     * Get all allowlist data for table population
     */
    public static function get_allowlist_data() {
        // Verify nonce
        check_ajax_referer('vmpfence_allowlist_nonce', 'nonce');
        
        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Insufficient permissions'));
            return;
        }
        
        // Get all allowlisted parameters
        $data = VMPFence_Param_Allowlist::get_all_allowlisted_params();
        
        wp_send_json_success(array(
            'data' => $data
        ));
    }
}
