<?php
/**
 * Delete IP AJAX Handler
 *
 * Handles permanent deletion of IP records from database.
 * This is used for cleaning up inactive/expired IPs.
 *
 * @package VMPFence
 * @since 2.1.0
 * @since 2.2.5 Added enhanced Audit Log 
 */

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

/**
 * Handle Delete IP AJAX request
 *
 * @since 2.1.0
 */
function vmpfence_ajax_delete_ip() {
    // Get IP first (needed for nonce)
    if (!isset($_POST['ip'])) {
        wp_send_json_error('IP address is required');
    }
    
    $ip = sanitize_text_field(wp_unslash($_POST['ip']));
    
    // Verify nonce (includes IP in nonce name)
    if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'vmpfence_delete_ip_' . $ip)) {
        wp_send_json_error('Nonce verification failed');
    }
    
    // Check user permissions
    if (!current_user_can('manage_options')) {
        wp_send_json_error('You do not have permission to perform this action');
    }
    
    // Validate IP format (supports both IPv4 and IPv6)
    $is_valid_ip = filter_var($ip, FILTER_VALIDATE_IP);
    $is_valid_cidr = false;
    
    if (!$is_valid_ip && strpos($ip, '/') !== false) {
        // Check CIDR notation for both IPv4 and IPv6
        $parts = explode('/', $ip);
        if (count($parts) === 2 && !empty($parts[0]) && !empty($parts[1])) {
            $ip_part = trim($parts[0]);
            $cidr_part = intval($parts[1]);
            
            // Validate IP and CIDR range
            if (filter_var($ip_part, FILTER_VALIDATE_IP)) {
                $is_ipv6 = filter_var($ip_part, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
                $max_cidr = $is_ipv6 ? 128 : 32;
                
                if ($cidr_part >= 0 && $cidr_part <= $max_cidr) {
                    $is_valid_cidr = true;
                }
            }
        }
    }
    
    if (!$is_valid_ip && !$is_valid_cidr) {
        wp_send_json_error('Invalid IP address format');
    }
    
    // Permanently delete from database
    $result = VMPFence_Blocked_IP::delete_blocked_ip($ip);
    
    if ($result) {
        // Fire hook for audit log observer
        do_action('vmpfence_ip_deleted', $ip, get_current_user_id());
        
        wp_send_json_success("IP {$ip} has been permanently deleted from database");
    } else {
        wp_send_json_error('Failed to delete IP record');
    }
}

// Register AJAX action
add_action('wp_ajax_vmpfence_delete_ip', 'vmpfence_ajax_delete_ip');
