<?php
/**
 * Import/Export Management Class
 *
 * @package VMPFence
 * @since 1.0.0
 * @since 2.2.5 -- Added Enhanced Audit Log integration for import/export actions
 */

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

/**
 * VMPFence Import/Export Class
 *
 * @since 1.0.0
 */
class VMPFence_Import_Export {

    /**
     * Export configuration settings
     *
     * @since 1.0.0
     * @param array $include_sections Sections to include
     * @return array
     */
    public static function export_configuration($include_sections = array()) {
        $default_sections = array(
            'general_settings',
            'waf_settings',
            'scan_settings',
            'login_protection',
            'audit_settings',
            'notification_settings',
            'whitelist_blacklist',
            'advanced_settings'
        );

        if (empty($include_sections)) {
            $include_sections = $default_sections;
        }

        $export_data = array(
            'vmpfence_version' => VMPFence_Constants::PLUGIN_VERSION,
            'export_timestamp' => current_time('timestamp'),
            'site_url' => get_site_url(),
            'wp_version' => get_bloginfo('version'),
            'configuration' => array()
        );

        foreach ($include_sections as $section) {
            $method = 'export_' . $section;
            if (method_exists(__CLASS__, $method)) {
                $export_data['configuration'][$section] = self::$method();
            }
        }

        do_action('vmpfence_settings_exported', $include_sections);

        return $export_data;
    }

    /**
     * Import configuration settings
     *
     * @since 1.0.0
     * @param array $import_data Import data
     * @param array $options Import options
     * @return array
     */
    public static function import_configuration($import_data, $options = array()) {
        $defaults = array(
            'overwrite_existing' => false,
            'backup_current' => true,
            'validate_data' => true,
            'sections_to_import' => array()
        );

        $options = wp_parse_args($options, $defaults);
        
        $result = array(
            'success' => false,
            'message' => '',
            'imported_sections' => array(),
            'errors' => array(),
            'backup_id' => null
        );

        // Validate import data structure
        if (!self::validate_import_data($import_data)) {
            $result['message'] = __('Invalid import data format', 'vmpfence-security');
            return $result;
        }

        // Create backup if requested
        if ($options['backup_current']) {
            $backup_id = self::create_configuration_backup();
            $result['backup_id'] = $backup_id;
        }

        // Import each section
        $sections_to_import = !empty($options['sections_to_import']) 
            ? $options['sections_to_import'] 
            : array_keys($import_data['configuration']);

        foreach ($sections_to_import as $section) {
            if (!isset($import_data['configuration'][$section])) {
                continue;
            }

            try {
                $import_method = 'import_' . $section;
                if (method_exists(__CLASS__, $import_method)) {
                    $section_result = self::$import_method(
                        $import_data['configuration'][$section],
                        $options
                    );
                    
                    if ($section_result['success']) {
                        $result['imported_sections'][] = $section;
                    } else {
                        $result['errors'][] = array(
                            'section' => $section,
                            'message' => $section_result['message']
                        );
                    }
                }
            } catch (Exception $e) {
                $result['errors'][] = array(
                    'section' => $section,
                    'message' => $e->getMessage()
                );
            }
        }

        // Determine overall success
        $result['success'] = !empty($result['imported_sections']) && empty($result['errors']);
        
        if ($result['success']) {
            $result['message'] = sprintf(
                /* translators: %d: number of configuration sections */
                __('Successfully imported %d configuration sections', 'vmpfence-security'),
                count($result['imported_sections'])
            );
            
            // REMOVED: VMPFence_Audit_Log::log_event('config_imported') — now handled by Observer_VMPFence
            do_action('vmpfence_settings_imported', $result['imported_sections']);
        } else {
            $result['message'] = __('Import completed with errors', 'vmpfence-security');
        }

        return $result;
    }

    /**
     * Export threat data
     *
     * @since 1.0.0
     * @param array $args Export arguments
     * @return array
     */
    public static function export_threat_data($args = array()) {
        global $wpdb;

        $defaults = array(
            'date_from' => '',
            'date_to' => '',
            'threat_types' => array(),
            'include_resolved' => false,
            'limit' => 10000
        );

        $args = wp_parse_args($args, $defaults);

        $threats_table = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_THREATS);
        
        // Build WHERE clause
        $where_conditions = array('1=1');
        $where_values = array();

        if (!empty($args['date_from'])) {
            $where_conditions[] = 'first_seen >= %d';
            $where_values[] = strtotime($args['date_from']);
        }

        if (!empty($args['date_to'])) {
            $where_conditions[] = 'first_seen <= %d';
            $where_values[] = strtotime($args['date_to']) + 86399;
        }

        if (!empty($args['threat_types'])) {
            $placeholders = implode(',', array_fill(0, count($args['threat_types']), '%s'));
            $where_conditions[] = "threat_type IN ($placeholders)";
            $where_values = array_merge($where_values, $args['threat_types']);
        }

        if (!$args['include_resolved']) {
            $where_conditions[] = 'status != %s';
            $where_values[] = 'resolved';
        }

        $where_clause = implode(' AND ', $where_conditions);
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared -- Table name from VMPFence_Constants, where_clause built from prepared statements
        $query = "SELECT * FROM $threats_table WHERE $where_clause ORDER BY first_seen DESC LIMIT %d";
        $where_values[] = $args['limit'];

        $threats = $wpdb->get_results($wpdb->prepare($query, $where_values), ARRAY_A);
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared

        $export_data = array(
            'vmpfence_version' => VMPFence_Constants::PLUGIN_VERSION,
            'export_timestamp' => current_time('timestamp'),
            'export_args' => $args,
            'total_threats' => count($threats),
            'threats' => $threats
        );

        return $export_data;
    }

    /**
     * Export audit log data
     *
     * @since 1.0.0
     * @param array $args Export arguments
     * @return array
     */
    public static function export_audit_log($args = array()) {
        $defaults = array(
            'date_from' => gmdate('Y-m-d', strtotime('-30 days')),
            'date_to' => gmdate('Y-m-d'),
            'event_types' => array(),
            'limit' => 10000
        );

        $args = wp_parse_args($args, $defaults);
        
        $entries = VMPFence_Audit_Log::get_entries($args);

        $export_data = array(
            'vmpfence_version' => VMPFence_Constants::PLUGIN_VERSION,
            'export_timestamp' => current_time('timestamp'),
            'export_args' => $args,
            'total_entries' => count($entries),
            'audit_entries' => $entries
        );

        return $export_data;
    }

    /**
     * Export whitelist/blacklist data
     *
     * @since 1.0.0
     * @return array
     */
    public static function export_lists() {
        global $wpdb;

        $whitelist_table = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_WHITELIST);
        $blacklist_table = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_BLACKLIST);

        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table names properly escaped via VMPFence_Constants
        $whitelist = $wpdb->get_results("SELECT * FROM $whitelist_table ORDER BY created_at DESC", ARRAY_A);
        $blacklist = $wpdb->get_results("SELECT * FROM $blacklist_table ORDER BY created_at DESC", ARRAY_A);
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

        return array(
            'vmpfence_version' => VMPFence_Constants::PLUGIN_VERSION,
            'export_timestamp' => current_time('timestamp'),
            'whitelist' => $whitelist,
            'blacklist' => $blacklist
        );
    }

    /**
     * Import whitelist/blacklist data
     *
     * @since 1.0.0
     * @param array $import_data Import data
     * @param array $options Import options
     * @return array
     */
    public static function import_lists($import_data, $options = array()) {
        global $wpdb;

        $result = array(
            'success' => false,
            'message' => '',
            'imported_whitelist' => 0,
            'imported_blacklist' => 0,
            'errors' => array()
        );

        $defaults = array(
            'overwrite_existing' => false,
            'skip_duplicates' => true
        );

        $options = wp_parse_args($options, $defaults);

        // Import whitelist
        if (isset($import_data['whitelist'])) {
            $whitelist_result = self::import_whitelist_entries($import_data['whitelist'], $options);
            $result['imported_whitelist'] = $whitelist_result['imported'];
            if (!empty($whitelist_result['errors'])) {
                $result['errors'] = array_merge($result['errors'], $whitelist_result['errors']);
            }
        }

        // Import blacklist
        if (isset($import_data['blacklist'])) {
            $blacklist_result = self::import_blacklist_entries($import_data['blacklist'], $options);
            $result['imported_blacklist'] = $blacklist_result['imported'];
            if (!empty($blacklist_result['errors'])) {
                $result['errors'] = array_merge($result['errors'], $blacklist_result['errors']);
            }
        }

        $result['success'] = ($result['imported_whitelist'] > 0 || $result['imported_blacklist'] > 0) && empty($result['errors']);
        
        if ($result['success']) {
            $result['message'] = sprintf(
                /* translators: %1$d: number of whitelist entries, %2$d: number of blacklist entries */
                __('Successfully imported %1$d whitelist and %2$d blacklist entries', 'vmpfence-security'),
                $result['imported_whitelist'],
                $result['imported_blacklist']
            );
        }

        return $result;
    }

    /**
     * Create configuration backup
     *
     * @since 1.0.0
     * @return string Backup ID
     */
    public static function create_configuration_backup() {
        $backup_id = 'backup_' . gmdate('YmdHis') . '_' . wp_generate_password(8, false);
        
        $backup_data = self::export_configuration();
        $backup_data['backup_id'] = $backup_id;
        $backup_data['backup_type'] = 'manual';

        // Store backup in database
        global $wpdb;
        $backups_table = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_BACKUPS);
        
        $wpdb->insert(
            $backups_table,
            array(
                'backup_id' => $backup_id,
                'backup_type' => 'configuration',
                'backup_data' => maybe_serialize($backup_data),
                'created_at' => current_time('timestamp'),
                'file_size' => strlen(serialize($backup_data))
            ),
            array('%s', '%s', '%s', '%d', '%d')
        );

        // Fire hook for observer-based audit logging
        do_action('vmpfence_backup_created', $backup_id, 'configuration');

        return $backup_id;
    }

    /**
     * Restore from backup
     *
     * @since 1.0.0
     * @param string $backup_id Backup ID
     * @return array
     */
    public static function restore_from_backup($backup_id) {
        global $wpdb;

        $backups_table = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_BACKUPS);
        
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name properly escaped via VMPFence_Constants
        $backup = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM $backups_table WHERE backup_id = %s",
            $backup_id
        ), ARRAY_A);
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

        if (!$backup) {
            return array(
                'success' => false,
                'message' => __('Backup not found', 'vmpfence-security')
            );
        }

        $backup_data = maybe_unserialize($backup['backup_data']);
        
        // Create a backup of current settings before restore
        $current_backup_id = self::create_configuration_backup();

        // Import the backup data
        $result = self::import_configuration($backup_data, array(
            'overwrite_existing' => true,
            'backup_current' => false
        ));

        if ($result['success']) {
            // Fire hook for observer-based audit logging
            do_action('vmpfence_backup_restored', $backup_id, $current_backup_id);
        }

        return $result;
    }

    /**
     * Export to file
     *
     * @since 1.0.0
     * @param array $data Data to export
     * @param string $filename Filename
     * @param string $format Export format (json, xml, csv)
     * @return string File path
     */
    public static function export_to_file($data, $filename, $format = 'json') {
        $upload_dir = wp_upload_dir();
        $vmpfence_dir = $upload_dir['basedir'] . '/vmpfence/exports/';
        
        if (!file_exists($vmpfence_dir)) {
            wp_mkdir_p($vmpfence_dir);
        }

        $filepath = $vmpfence_dir . $filename;

        switch ($format) {
            case 'json':
                $content = wp_json_encode($data, JSON_PRETTY_PRINT);
                break;
                
            case 'xml':
                $content = self::array_to_xml($data);
                break;
                
            case 'csv':
                $content = self::array_to_csv($data);
                break;
                
            default:
                $content = serialize($data);
        }

        file_put_contents($filepath, $content);
        
        return $filepath;
    }

    /**
     * Import from file
     *
     * @since 1.0.0
     * @param string $filepath File path
     * @param string $format File format
     * @return array
     */
    public static function import_from_file($filepath, $format = 'json') {
        if (!file_exists($filepath)) {
            return array(
                'success' => false,
                'message' => __('Import file not found', 'vmpfence-security')
            );
        }

        $content = file_get_contents($filepath);
        
        switch ($format) {
            case 'json':
                $data = json_decode($content, true);
                break;
                
            case 'xml':
                $data = self::xml_to_array($content);
                break;
                
            case 'csv':
                $data = self::csv_to_array($content);
                break;
                
            default:
                $data = unserialize($content);
        }

        if (!$data) {
            return array(
                'success' => false,
                'message' => __('Failed to parse import file', 'vmpfence-security')
            );
        }

        return $data;
    }

    /**
     * Get available backups
     *
     * @since 1.0.0
     * @param string $type Backup type filter
     * @return array
     */
    public static function get_backups($type = '') {
        global $wpdb;

        $backups_table = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_BACKUPS);
        
        $where_clause = '1=1';
        $where_values = array();

        if (!empty($type)) {
            $where_clause .= ' AND backup_type = %s';
            $where_values[] = $type;
        }

        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared -- Table name from VMPFence_Constants, where_clause safely built
        $query = "SELECT * FROM $backups_table WHERE $where_clause ORDER BY created_at DESC";
        
        if (!empty($where_values)) {
            $query = $wpdb->prepare($query, $where_values);
        }

        $backups = $wpdb->get_results($query, ARRAY_A);
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared

        foreach ($backups as &$backup) {
            $backup['created_at_formatted'] = date_i18n(
                get_option('date_format') . ' ' . get_option('time_format'),
                $backup['created_at']
            );
            $backup['file_size_formatted'] = size_format($backup['file_size']);
        }

        return $backups;
    }

    /**
     * Delete backup
     *
     * @since 1.0.0
     * @param string $backup_id Backup ID
     * @return bool
     */
    public static function delete_backup($backup_id) {
        global $wpdb;

        $backups_table = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_BACKUPS);
        
        $deleted = $wpdb->delete(
            $backups_table,
            array('backup_id' => $backup_id),
            array('%s')
        );

        if ($deleted) {
            // Fire hook for observer-based audit logging
            do_action('vmpfence_backup_deleted', $backup_id);
        }

        return $deleted !== false;
    }

    /**
     * Export individual configuration sections
     */
    
    private static function export_general_settings() {
        return array(
            'license_key' => VMPFence_Config::get('license_key', ''),
            'api_key' => VMPFence_Config::get('api_key', ''),
            'enable_audit_log' => VMPFence_Config::get('enable_audit_log', true),
            'audit_log_retention_days' => VMPFence_Config::get('audit_log_retention_days', 90),
            'central_management_enabled' => VMPFence_Config::get('central_management_enabled', false),
            'central_api_key' => VMPFence_Config::get('central_api_key', ''),
            'debug_mode' => VMPFence_Config::get('debug_mode', false)
        );
    }

    private static function export_waf_settings() {
        return array(
            'waf_enabled' => VMPFence_Config::get('waf_enabled', false),
            'waf_protection_level' => VMPFence_Config::get('waf_protection_level', 'medium'),
            'waf_block_mode' => VMPFence_Config::get('waf_block_mode', 'block'),
            'waf_learning_mode' => VMPFence_Config::get('waf_learning_mode', false),
            'waf_custom_rules' => VMPFence_Config::get('waf_custom_rules', array()),
            'waf_whitelist_rules' => VMPFence_Config::get('waf_whitelist_rules', array())
        );
    }

    private static function export_scan_settings() {
        return array(
            'scan_schedule' => VMPFence_Config::get('scan_schedule', 'daily'),
            'scan_time' => VMPFence_Config::get('scan_time', '02:00'),
            'scan_file_extensions' => VMPFence_Config::get('scan_file_extensions', array('php', 'js', 'html')),
            'scan_exclude_directories' => VMPFence_Config::get('scan_exclude_directories', array()),
            'scan_max_file_size' => VMPFence_Config::get('scan_max_file_size', 10485760),
            'scan_timeout' => VMPFence_Config::get('scan_timeout', 300),
            'auto_quarantine' => VMPFence_Config::get('auto_quarantine', false)
        );
    }

    private static function export_login_protection() {
        return array(
            'login_protection_enabled' => VMPFence_Config::get('login_protection_enabled', false),
            'max_login_attempts' => VMPFence_Config::get('max_login_attempts', 5),
            'login_attempt_window' => VMPFence_Config::get('login_attempt_window', 900),
            'lockout_duration' => VMPFence_Config::get('lockout_duration', 3600),
            'two_factor_enabled' => VMPFence_Config::get('two_factor_enabled', false),
            'captcha_enabled' => VMPFence_Config::get('captcha_enabled', false),
            'whitelist_admin_ips' => VMPFence_Config::get('whitelist_admin_ips', array())
        );
    }

    private static function export_audit_settings() {
        return array(
            'enable_audit_log' => VMPFence_Config::get('enable_audit_log', true),
            'audit_log_retention_days' => VMPFence_Config::get('audit_log_retention_days', 90),
            'audit_events' => VMPFence_Config::get('audit_events', array()),
            'audit_log_level' => VMPFence_Config::get('audit_log_level', 'medium')
        );
    }

    private static function export_notification_settings() {
        return array(
            'email_notifications' => VMPFence_Config::get('email_notifications', true),
            'notification_email' => VMPFence_Config::get('notification_email', get_option('admin_email')),
            'notification_events' => VMPFence_Config::get('notification_events', array()),
            'notification_frequency' => VMPFence_Config::get('notification_frequency', 'immediate'),
            'slack_webhook' => VMPFence_Config::get('slack_webhook', ''),
            'webhook_notifications' => VMPFence_Config::get('webhook_notifications', false)
        );
    }

    private static function export_whitelist_blacklist() {
        return self::export_lists();
    }

    private static function export_advanced_settings() {
        return array(
            'cache_enabled' => VMPFence_Config::get('cache_enabled', true),
            'cache_duration' => VMPFence_Config::get('cache_duration', 3600),
            'rate_limiting' => VMPFence_Config::get('rate_limiting', array()),
            'geo_blocking' => VMPFence_Config::get('geo_blocking', array()),
            'custom_headers' => VMPFence_Config::get('custom_headers', array()),
            'advanced_threat_detection' => VMPFence_Config::get('advanced_threat_detection', false)
        );
    }

    /**
     * Import individual configuration sections
     */
    
    private static function import_general_settings($data, $options) {
        $settings = array(
            'license_key', 'api_key', 'enable_audit_log', 'audit_log_retention_days',
            'central_management_enabled', 'central_api_key', 'debug_mode'
        );

        return self::import_settings_group($data, $settings, $options);
    }

    private static function import_waf_settings($data, $options) {
        $settings = array(
            'waf_enabled', 'waf_protection_level', 'waf_block_mode', 'waf_learning_mode',
            'waf_custom_rules', 'waf_whitelist_rules'
        );

        return self::import_settings_group($data, $settings, $options);
    }

    private static function import_scan_settings($data, $options) {
        $settings = array(
            'scan_schedule', 'scan_time', 'scan_file_extensions', 'scan_exclude_directories',
            'scan_max_file_size', 'scan_timeout', 'auto_quarantine'
        );

        return self::import_settings_group($data, $settings, $options);
    }

    private static function import_login_protection($data, $options) {
        $settings = array(
            'login_protection_enabled', 'max_login_attempts', 'login_attempt_window',
            'lockout_duration', 'two_factor_enabled', 'captcha_enabled', 'whitelist_admin_ips'
        );

        return self::import_settings_group($data, $settings, $options);
    }

    private static function import_audit_settings($data, $options) {
        $settings = array(
            'enable_audit_log', 'audit_log_retention_days', 'audit_events', 'audit_log_level'
        );

        return self::import_settings_group($data, $settings, $options);
    }

    private static function import_notification_settings($data, $options) {
        $settings = array(
            'email_notifications', 'notification_email', 'notification_events',
            'notification_frequency', 'slack_webhook', 'webhook_notifications'
        );

        return self::import_settings_group($data, $settings, $options);
    }

    private static function import_whitelist_blacklist($data, $options) {
        return self::import_lists($data, $options);
    }

    private static function import_advanced_settings($data, $options) {
        $settings = array(
            'cache_enabled', 'cache_duration', 'rate_limiting', 'geo_blocking',
            'custom_headers', 'advanced_threat_detection'
        );

        return self::import_settings_group($data, $settings, $options);
    }

    /**
     * Helper methods
     */
    
    private static function validate_import_data($data) {
        return isset($data['vmpfence_version']) && 
               isset($data['configuration']) && 
               is_array($data['configuration']);
    }

    private static function import_settings_group($data, $settings, $options) {
        $imported = 0;
        $errors = array();

        foreach ($settings as $setting) {
            if (isset($data[$setting])) {
                try {
                    if ($options['overwrite_existing'] || VMPFence_Config::get($setting) === null) {
                        VMPFence_Config::set($setting, $data[$setting]);
                        $imported++;
                    }
                } catch (Exception $e) {
                    $errors[] = array(
                        'setting' => $setting,
                        'message' => $e->getMessage()
                    );
                }
            }
        }

        return array(
            'success' => $imported > 0 && empty($errors),
            'imported' => $imported,
            'errors' => $errors,
            /* translators: %d: number of settings imported */
            'message' => sprintf(__('Imported %d settings', 'vmpfence-security'), $imported)
        );
    }

    private static function import_whitelist_entries($entries, $options) {
        global $wpdb;
        
        $whitelist_table = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_WHITELIST);
        $imported = 0;
        $errors = array();

        foreach ($entries as $entry) {
            try {
                // Check for duplicates if skip_duplicates is enabled
                if ($options['skip_duplicates']) {
                    // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name properly escaped via VMPFence_Constants
                    $exists = $wpdb->get_var($wpdb->prepare(
                        "SELECT COUNT(*) FROM $whitelist_table WHERE ip_address = %s AND type = %s",
                        $entry['ip_address'],
                        $entry['type']
                    ));
                    // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                    
                    if ($exists > 0) {
                        continue;
                    }
                }

                $result = $wpdb->insert(
                    $whitelist_table,
                    array(
                        'ip_address' => $entry['ip_address'],
                        'type' => $entry['type'],
                        'reason' => $entry['reason'] ?? '',
                        'created_at' => current_time('timestamp')
                    ),
                    array('%s', '%s', '%s', '%d')
                );

                if ($result) {
                    $imported++;
                }
            } catch (Exception $e) {
                $errors[] = array(
                    'entry' => $entry['ip_address'],
                    'message' => $e->getMessage()
                );
            }
        }

        return array(
            'success' => $imported > 0,
            'imported' => $imported,
            'errors' => $errors
        );
    }

    private static function import_blacklist_entries($entries, $options) {
        global $wpdb;
        
        $blacklist_table = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_BLACKLIST);
        $imported = 0;
        $errors = array();

        foreach ($entries as $entry) {
            try {
                // Check for duplicates if skip_duplicates is enabled
                if ($options['skip_duplicates']) {
                    // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name properly escaped via VMPFence_Constants
                    $exists = $wpdb->get_var($wpdb->prepare(
                        "SELECT COUNT(*) FROM $blacklist_table WHERE ip_address = %s",
                        $entry['ip_address']
                    ));
                    // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                    
                    if ($exists > 0) {
                        continue;
                    }
                }

                $result = $wpdb->insert(
                    $blacklist_table,
                    array(
                        'ip_address' => $entry['ip_address'],
                        'reason' => $entry['reason'] ?? '',
                        'created_at' => current_time('timestamp'),
                        'expires_at' => $entry['expires_at'] ?? 0
                    ),
                    array('%s', '%s', '%d', '%d')
                );

                if ($result) {
                    $imported++;
                }
            } catch (Exception $e) {
                $errors[] = array(
                    'entry' => $entry['ip_address'],
                    'message' => $e->getMessage()
                );
            }
        }

        return array(
            'success' => $imported > 0,
            'imported' => $imported,
            'errors' => $errors
        );
    }

    private static function array_to_xml($data, $root_element = 'vmpfence_export') {
        $xml = new SimpleXMLElement('<' . $root_element . '/>');
        self::array_to_xml_recursive($data, $xml);
        return $xml->asXML();
    }

    private static function array_to_xml_recursive($data, &$xml) {
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                if (is_numeric($key)) {
                    $key = 'item';
                }
                $subnode = $xml->addChild($key);
                self::array_to_xml_recursive($value, $subnode);
            } else {
                $xml->addChild($key, htmlspecialchars($value));
            }
        }
    }

    private static function xml_to_array($xml_content) {
        $xml = simplexml_load_string($xml_content);
        return json_decode(json_encode($xml), true);
    }

    private static function array_to_csv($data) {
        if (empty($data)) {
            return '';
        }

        $output = '';
        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- Using php://temp stream for in-memory CSV generation
        $temp = fopen('php://temp', 'r+');

        // Flatten the array for CSV
        $flattened = self::flatten_array($data);
        
        // Write headers
        fputcsv($temp, array('Key', 'Value'));
        
        // Write data
        foreach ($flattened as $key => $value) {
            fputcsv($temp, array($key, $value));
        }

        rewind($temp);
        $output = stream_get_contents($temp);
        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- Closing php://temp stream
        fclose($temp);

        return $output;
    }

    private static function csv_to_array($csv_content) {
        $lines = str_getcsv($csv_content, "\n");
        $data = array();
        $headers = str_getcsv(array_shift($lines));

        foreach ($lines as $line) {
            $row = str_getcsv($line);
            if (count($row) === count($headers)) {
                $data[] = array_combine($headers, $row);
            }
        }

        return $data;
    }

    private static function flatten_array($array, $prefix = '') {
        $result = array();
        
        foreach ($array as $key => $value) {
            $new_key = $prefix === '' ? $key : $prefix . '.' . $key;
            
            if (is_array($value)) {
                $result = array_merge($result, self::flatten_array($value, $new_key));
            } else {
                $result[$new_key] = $value;
            }
        }
        
        return $result;
    }
}
