<?php
/**
 * AJAX handler for unblocking IPs
 *
 * @package VMPFence
 * @since 2.1.0
 * @since 2.2.5 -- Added Enhanced Audit Log integration for unblock IP action
 */

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

/**
 * AJAX handler for unblocking an IP
 */
function vmpfence_ajax_unblock_ip() {
    // Get IP address first (needed for nonce)
    if (!isset($_POST['ip'])) {
        wp_send_json_error('IP address is required');
    }
    
    $ip = sanitize_text_field($_POST['ip']);
    
    // Verify nonce (includes IP in nonce name)
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'vmpfence_unblock_ip_' . $ip)) {
        wp_send_json_error('Nonce verification failed');
    }
    
    // Check permissions
    if (!current_user_can('manage_options')) {
        wp_send_json_error('You do not have permission to perform this action');
    }
    
    // Validate IP format
    $is_valid = false;
    if (strpos($ip, '/') !== false) {
        // CIDR notation
        list($base_ip, $cidr) = explode('/', $ip, 2);
        if (filter_var($base_ip, FILTER_VALIDATE_IP) && is_numeric($cidr)) {
            $is_ipv6 = filter_var($base_ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
            $max_cidr = $is_ipv6 ? 128 : 32;
            $is_valid = ($cidr >= 0 && $cidr <= $max_cidr);
        }
    } else {
        // Single IP
        $is_valid = filter_var($ip, FILTER_VALIDATE_IP);
    }
    
    if (!$is_valid) {
        wp_send_json_error('Invalid IP address format');
    }
    
    // Get IP details to check source
    $ip_details = VMPFence_Blocked_IP::get_blocked_ip_details($ip);
    
    // Remove the IP from blocklist
    $result = VMPFence_Blocked_IP::remove_blocked_ip($ip);
    
    if ($result) {
        $message = 'IP unblocked successfully';
        
        // If IP was synced with API, unblock on API too
        if ($ip_details && ($ip_details['source'] === 'api' || $ip_details['source'] === 'both')) {
            $license_tier = VMPFence_Config::get('firewall_license_tier', 'free');
            if ($license_tier === 'premium') {
                $api_key = VMPFence_Config::get('central_api_key');
                if ($api_key) {
                    $api_client = new VMPFence_API_Client();
                    $api_response = $api_client->unblock_ip($api_key, $ip);
                    
                    if (is_wp_error($api_response)) {
                        VMPFence_Secure_Logger::error('Failed to unblock IP from API', [
                            'ip' => $ip,
                            'error' => $api_response->get_error_message()
                        ]);
                        $message .= ' (Warning: Failed to unblock from API - ' . $api_response->get_error_message() . ')';
                    } else if (isset($api_response['success']) && $api_response['success']) {
                        $message .= ' and removed from API';
                    } else {
                        $error_msg = isset($api_response['error']) ? $api_response['error'] : 'Unknown error';
                        VMPFence_Secure_Logger::error('Failed to unblock IP from API', [
                            'ip' => $ip,
                            'error' => $error_msg
                        ]);
                        $message .= ' (Warning: Failed to unblock from API - ' . $error_msg . ')';
                    }
                }
            }
        }
        
        // Log the unblock event
        if (class_exists('VMPFence_Logging_Service')) {
            $logging_service = VMPFence_Logging_Service::get_instance();
            $logging_service->log_event('ip_unblocked', 'info', array(
                'ip_address' => $ip,
                'unblocked_by' => wp_get_current_user()->user_login,
                'source' => $ip_details ? $ip_details['source'] : 'unknown'
            ), 'firewall');
        }

        // Fire audit log hook for block deleted
        do_action('vmpfence_ip_unblocked', $ip);

        wp_send_json_success($message);
    } else {
        wp_send_json_error('Failed to unblock IP');
    }
}

add_action('wp_ajax_vmpfence_unblock_ip', 'vmpfence_ajax_unblock_ip');
