<?php
/**
 * Main admin interface for BotFend Anti-Bot Firewall
 *
 * @package BotFend\Admin
 */

namespace BotFend\Admin;

use BotFend\Core\Config;
use BotFend\Core\Core;
use BotFend\Admin\Pages\FirewallPage;
use BotFend\Admin\Pages\LicensePage;  // ADD THIS LINE
use Exception;

defined('ABSPATH') || exit;

class AdminCoreManager {

    private $core;
    private $pages;
    private $settings;
    private $config;
    private $firewall_page;

    public function __construct(Core $core) {
        $this->core = $core;
        $this->config = Config::get_instance();

        $this->pages = new AdminPages($core);
        $this->settings = new AdminSettings($core);
        $this->firewall_page = new FirewallPage($core);

        add_action('admin_menu', [$this, 'admin_menu']);
        add_action('admin_init', [$this, 'init_settings']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_scripts']);
        add_action('admin_head', [$this, 'highlight_firewall_menu']);

        add_action('admin_post_botfend_export_settings', [$this, 'handle_export_settings']);
        add_action('admin_post_botfend_import_settings', [$this, 'handle_import_settings']);
        add_action('admin_post_botfend_reset', [$this, 'handle_reset_action']);
        add_action('admin_post_botfend_set_mode', [$this, 'handle_set_mode']);
        add_action('admin_post_botfend_unblock_action', [$this, 'handle_unblock_action']);

        add_action('wp_ajax_botfend_test_api_detection', [$this, 'ajax_test_api_detection']);
        add_action('wp_ajax_botfend_clear_session_cache', [$this, 'ajax_clear_session_cache']);
        add_action('wp_ajax_botfend_reset_session_errors', [$this, 'ajax_reset_session_errors']);

        if (defined('WP_DEBUG') && WP_DEBUG && $this->config->get_bool('debug_mode', false)) {
            error_log('BotFend AdminCoreManager initialized successfully');
        }
    }

    private function get_config_string(string $key, string $default = ''): string {
        return $this->config->get_string($key, $default);
    }

    private function get_config_bool(string $key, bool $default = false): bool {
        return $this->config->get_bool($key, $default);
    }

    private function get_config_int(string $key, int $default = 0): int {
        return $this->config->get_int($key, $default);
    }

    public function admin_menu(): void {
        $capability = $this->get_config_string('admin_capability', 'manage_options');

        add_menu_page(
            esc_html__('BotFend Anti-Bot Firewall', 'botfend-anti-bot-firewall'),
            esc_html__('BotFend', 'botfend-anti-bot-firewall'),
            $capability,
            'botfend-dashboard',
            [$this->pages, 'render_dashboard'],
            'dashicons-shield-alt',
            80
        );

        if ($this->get_config_bool('show_unblock_menu', true)) {
            add_submenu_page(
                'botfend-dashboard',
                esc_html__('Unblock Requests', 'botfend-anti-bot-firewall'),
                esc_html__('Unblock Requests', 'botfend-anti-bot-firewall'),
                $capability,
                'botfend-unblock-requests',
                [$this->pages, 'render_unblock_requests']
            );
        }

        add_submenu_page(
            'botfend-dashboard',
            esc_html__('Settings', 'botfend-anti-bot-firewall'),
            esc_html__('Settings', 'botfend-anti-bot-firewall'),
            $capability,
            'botfend-settings',
            [$this->pages, 'render_settings']
        );

        add_submenu_page(
            'botfend-dashboard',
            esc_html__('Firewall Setup', 'botfend-anti-bot-firewall'),
            esc_html__('Firewall Setup', 'botfend-anti-bot-firewall'),
            $capability,
            'botfend-firewall',
            [$this->firewall_page, 'render']
        );

        add_submenu_page(
            'botfend-dashboard',
            esc_html__('Blocklist', 'botfend-anti-bot-firewall'),
            esc_html__('Blocklist', 'botfend-anti-bot-firewall'),
            $capability,
            'botfend-blocklist',
            [$this->pages, 'render_blocklist']
        );

        add_submenu_page(
            'botfend-dashboard',
            esc_html__('Logs', 'botfend-anti-bot-firewall'),
            esc_html__('Logs', 'botfend-anti-bot-firewall'),
            $capability,
            'botfend-logs',
            [$this->pages, 'render_logs']
        );

        add_submenu_page(
            'botfend-dashboard',
            esc_html__('Threat Dashboard', 'botfend-anti-bot-firewall'),
            esc_html__('Threat Dashboard', 'botfend-anti-bot-firewall'),
            $capability,
            'botfend-adaptive',
            [$this->pages, 'render_adaptive_dashboard']
        );

        add_submenu_page(
            'botfend-dashboard',
            esc_html__('Cloudflare Integration', 'botfend-anti-bot-firewall'),
            esc_html__('Cloudflare', 'botfend-anti-bot-firewall'),
            $capability,
            'botfend-cloudflare',
            [$this->pages, 'render_cloudflare']
        );

        // ============================================
        // ADD LICENSE PAGE - IMPORTANT!
        // ============================================
        add_submenu_page(
            'botfend-dashboard',
            esc_html__('Pro License', 'botfend-anti-bot-firewall'),
            esc_html__('Pro License', 'botfend-anti-bot-firewall') . ' <span class="botfend-pro-badge">PRO</span>',
            $capability,
            'botfend-license',
            [$this, 'render_license_page']  // Direct callback to avoid handler issues
        );
    }

    /**
     * Render license page directly
     */
    public function render_license_page(): void {
        if (!class_exists('BotFend\\Admin\\Pages\\LicensePage')) {
            // Fallback if class doesn't exist
            echo '<div class="wrap"><h1>' . esc_html__('BotFend Pro License', 'botfend-anti-bot-firewall') . '</h1>';
            echo '<div class="notice notice-error"><p>' . esc_html__('License page not available. Please reinstall the plugin.', 'botfend-anti-bot-firewall') . '</p></div>';
            echo '</div>';
            return;
        }
        
        $license_page = new LicensePage();
        $license_page->render();
    }

    /**
     * Highlight firewall menu if not configured
     */
    public function highlight_firewall_menu(): void {
        $screen = get_current_screen();
        if (!$screen) {
            return;
        }

        if (strpos($screen->id, 'botfend') === false) {
            return;
        }
    }

    public function init_settings(): void {
        $this->settings->register_settings();
        
        if (defined('WP_DEBUG') && WP_DEBUG && $this->get_config_bool('debug_mode', false)) {
            error_log('BotFend: Settings registered successfully');
        }
    }

    public function enqueue_admin_scripts(string $hook): void {
        if (strpos($hook, 'botfend-') === false) {
            return;
        }

        wp_enqueue_script('jquery');

        wp_enqueue_style(
            'botfend-admin-css', 
            BOTFEND_ASSETS_URL . 'css/botfend-admin.css', 
            [], 
            BOTFEND_VERSION
        );

        $admin_data = [
            'ajax_url' => esc_url(admin_url('admin-ajax.php')),
            'nonce' => esc_attr(wp_create_nonce('botfend_admin_nonce')),
            'loading_text' => esc_html__('Loading...', 'botfend-anti-bot-firewall'),
            'debug_mode' => $this->get_config_bool('debug_mode', false),
            'auto_refresh' => $this->get_config_bool('dashboard_auto_refresh', true),
            'refresh_interval' => $this->get_config_int('dashboard_refresh_interval', 30),
        ];

        $features = [
            'adaptive' => $this->get_config_bool('enable_adaptive', true),
            'waf' => $this->get_config_bool('enable_waf', true),
            'threat_intel' => $this->get_config_bool('enable_threat_intel', true),
            'signatures' => $this->get_config_bool('enable_signatures', true),
            'advanced_404' => $this->get_config_bool('enable_advanced_404', true),
            'connection_fp' => $this->get_config_bool('enable_connection_fp', true),
            'intelligent_session' => $this->get_config_bool('enable_intelligent_session', true),
            'behavioral_analysis' => $this->get_config_bool('enable_behavioral_analysis', true),
            'smart_aggregation' => $this->get_config_bool('enable_smart_aggregation', true),
        ];
        $admin_data['features'] = $features;

        wp_add_inline_script('jquery', '
            var botfend_ajax = ' . wp_json_encode($admin_data) . ';
        ', 'before');
    }



	

    private function clear_cache_group(string $group): void {
        global $wpdb;

        $cache_keys = [
            'logs' => ['botfend_log_stats', 'botfend_recent_logs', 'botfend_dedup_logs_'],
            'blocklist' => ['botfend_blocked_ips', 'botfend_block_stats', 'botfend_blocklist_list_'],
            'unblock' => ['botfend_unblock_requests_count', 'botfend_unblock_requests_stats'],
            'adaptive' => ['botfend_adaptive_settings', 'botfend_protection_mode'],
            'session' => ['botfend_session_cache', 'botfend_challenge_stats', 'botfend_session_errors'],
            'dashboard' => ['botfend_dashboard_stats', 'botfend_quick_stats'],
        ];

        if (isset($cache_keys[$group])) {
            foreach ($cache_keys[$group] as $pattern) {
                wp_cache_delete($pattern, 'botfend_admin');

                if (strpos($pattern, '_') !== false) {
                    $wpdb->query($wpdb->prepare(
                        "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
                        '_transient_' . $pattern . '%'
                    ));
                }
            }
        }

        if (method_exists($this->config, 'clear_cache')) {
            $this->config->clear_cache();
        }
    }

    public function handle_reset_action(): void {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have permission to perform this action.', 'botfend-anti-bot-firewall'));
        }

        check_admin_referer('botfend_reset');

        $action = isset($_POST['reset_action']) ? sanitize_text_field(wp_unslash($_POST['reset_action'])) : '';
        $components = $this->core->get_components();
        $database = $components['database'] ?? null;

        if (!$database) {
            wp_die(esc_html__('Database component not available.', 'botfend-anti-bot-firewall'));
        }

        switch ($action) {
            case 'reset_settings':
                if (method_exists($this->config, 'clear_cache')) {
                    $this->config->clear_cache();
                }
                $settings = new AdminSettings($this->core);
                $success = $settings->reset_to_defaults();
                if ($success) {
                    add_settings_error('botfend_messages', 'botfend_message', esc_html__('Plugin settings have been reset to defaults.', 'botfend-anti-bot-firewall'), 'success');
                } else {
                    add_settings_error('botfend_messages', 'botfend_message', esc_html__('Failed to reset settings. Please try again.', 'botfend-anti-bot-firewall'), 'error');
                }
                break;

            case 'clear_logs':
                if (method_exists($database, 'clear_logs')) {
                    $database->clear_logs();
                }
                $this->clear_cache_group('logs');
                add_settings_error('botfend_messages', 'botfend_message', esc_html__('All security logs have been cleared.', 'botfend-anti-bot-firewall'), 'success');
                break;

            case 'unblock_all':
                global $wpdb;
                $table = $wpdb->prefix . 'botfend_blocklist';
                $wpdb->query("TRUNCATE TABLE `{$table}`");
                $this->clear_cache_group('blocklist');
                add_settings_error('botfend_messages', 'botfend_message', esc_html__('All blocked IPs have been unblocked.', 'botfend-anti-bot-firewall'), 'success');
                break;

            case 'clear_unblock_requests':
                global $wpdb;
                $table = $wpdb->prefix . 'botfend_unblock_requests';
                $wpdb->query("TRUNCATE TABLE `{$table}`");
                $this->clear_cache_group('unblock');
                add_settings_error('botfend_messages', 'botfend_message', esc_html__('All unblock requests have been cleared.', 'botfend-anti-bot-firewall'), 'success');
                break;

            case 'clear_aggregates':
                if (method_exists($database, 'clear_aggregated_data')) {
                    $database->clear_aggregated_data();
                }
                $this->clear_cache_group('logs');
                add_settings_error('botfend_messages', 'botfend_message', esc_html__('Aggregated log data has been cleared.', 'botfend-anti-bot-firewall'), 'success');
                break;

            case 'clear_transients':
                $settings = new AdminSettings($this->core);
                $settings->clear_plugin_transients();
                add_settings_error('botfend_messages', 'botfend_message', esc_html__('All temporary caches and transients have been successfully cleared.', 'botfend-anti-bot-firewall'), 'success');
                break;

            default:
                add_settings_error('botfend_messages', 'botfend_message', esc_html__('Invalid action selected.', 'botfend-anti-bot-firewall'), 'error');
                break;
        }

        set_transient('settings_errors', get_settings_errors(), 30);
        wp_safe_redirect(esc_url(admin_url('admin.php?page=botfend-settings&settings-updated=true')));
        exit;
    }

    public function handle_set_mode(): void {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have permission to perform this action.', 'botfend-anti-bot-firewall'));
        }

        check_admin_referer('botfend_adaptive_control');

        $mode = isset($_POST['protection_mode']) ? sanitize_text_field(wp_unslash($_POST['protection_mode'])) : 'balanced';
        $components = $this->core->get_components();
        $adaptive = $components['adaptive'] ?? null;

        if (!$adaptive) {
            wp_die(esc_html__('Adaptive protection component not available.', 'botfend-anti-bot-firewall'));
        }

        $valid_modes = ['learning', 'balanced', 'aggressive', 'emergency'];
        if (!in_array($mode, $valid_modes, true)) {
            $mode = 'balanced';
        }

        if ($adaptive->set_protection_mode($mode, true)) {
            $this->config->set('adaptive_mode', $mode);
            $this->clear_cache_group('adaptive');

            add_settings_error('botfend_messages', 'botfend_message', sprintf(esc_html__('Protection mode changed to: %s', 'botfend-anti-bot-firewall'), esc_html(ucfirst($mode))), 'success');
        } else {
            add_settings_error('botfend_messages', 'botfend_message', esc_html__('Failed to change protection mode.', 'botfend-anti-bot-firewall'), 'error');
        }

        set_transient('settings_errors', get_settings_errors(), 30);
        wp_safe_redirect(esc_url(admin_url('admin.php?page=botfend-adaptive&settings-updated=true')));
        exit;
    }

    public function handle_unblock_action(): void {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have permission to perform this action.', 'botfend-anti-bot-firewall'));
        }

        $components = $this->core->get_components();
        $database = $components['database'] ?? null;

        if (!$database) {
            wp_die(esc_html__('Database component not available.', 'botfend-anti-bot-firewall'));
        }

        if (isset($_POST['bulk_submit']) && !empty($_POST['bulk_ids'])) {
            check_admin_referer('botfend_bulk_unblock_action');

            $bulk_action = isset($_POST['bulk_action']) ? sanitize_text_field(wp_unslash($_POST['bulk_action'])) : '';
            $bulk_ids = isset($_POST['bulk_ids']) ? array_map('absint', (array) wp_unslash($_POST['bulk_ids'])) : [];

            $valid_actions = ['approve', 'reject', 'delete'];
            if (empty($bulk_action) || !in_array($bulk_action, $valid_actions, true)) {
                wp_safe_redirect(esc_url(admin_url('admin.php?page=botfend-unblock-requests')));
                exit;
            }

            $processed = 0;
            foreach ($bulk_ids as $id) {
                switch ($bulk_action) {
                    case 'approve':
                        if ($database->update_unblock_request($id, ['status' => 'approved'])) $processed++;
                        break;
                    case 'reject':
                        if ($database->update_unblock_request($id, ['status' => 'rejected'])) $processed++;
                        break;
                    case 'delete':
                        if ($database->delete_unblock_request($id)) $processed++;
                        break;
                }
            }

            if ($processed > 0) {
                $this->clear_cache_group('unblock');
            }

            $redirect_url = add_query_arg(['action_result' => 'bulk_processed', 'result_type' => 'success', 'processed' => absint($processed)], admin_url('admin.php?page=botfend-unblock-requests'));
            wp_safe_redirect(esc_url($redirect_url));
            exit;
        }

        if (isset($_POST['single_action'])) {
            check_admin_referer('botfend_unblock_action');

            $request_id = isset($_POST['request_id']) ? absint(wp_unslash($_POST['request_id'])) : 0;
            $action = isset($_POST['single_action']) ? sanitize_text_field(wp_unslash($_POST['single_action'])) : '';

            $valid_actions = ['approve', 'reject', 'delete'];
            if ($request_id <= 0 || !in_array($action, $valid_actions, true)) {
                wp_safe_redirect(esc_url(admin_url('admin.php?page=botfend-unblock-requests')));
                exit;
            }

            $result = false;
            $result_type = 'error';

            switch ($action) {
                case 'approve':
                    $result = $database->update_unblock_request($request_id, ['status' => 'approved']);
                    $result_type = $result ? 'approved' : 'error';
                    break;
                case 'reject':
                    $result = $database->update_unblock_request($request_id, ['status' => 'rejected']);
                    $result_type = $result ? 'rejected' : 'error';
                    break;
                case 'delete':
                    $result = $database->delete_unblock_request($request_id);
                    $result_type = $result ? 'deleted' : 'error';
                    break;
            }

            if ($result) {
                $this->clear_cache_group('unblock');
            }

            $redirect_url = add_query_arg(['action_result' => $result_type, 'result_type' => $result ? 'success' : 'error'], admin_url('admin.php?page=botfend-unblock-requests'));
            wp_safe_redirect(esc_url($redirect_url));
            exit;
        }

        wp_safe_redirect(esc_url(admin_url('admin.php?page=botfend-unblock-requests')));
        exit;
    }

    public function ajax_test_api_detection(): void {
        check_ajax_referer('botfend_admin_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Unauthorized', 'botfend-anti-bot-firewall')]);
        }

        $url = isset($_POST['url']) ? sanitize_text_field(wp_unslash($_POST['url'])) : '';
        $method = isset($_POST['method']) ? sanitize_text_field(wp_unslash($_POST['method'])) : 'GET';

        if (empty($url)) {
            wp_send_json_error(['message' => esc_html__('URL is required', 'botfend-anti-bot-firewall')]);
        }

        $components = $this->core->get_components();
        $challenges = $components['challenges'] ?? null;

        if (!$challenges) {
            wp_send_json_error(['message' => esc_html__('Challenges component not available', 'botfend-anti-bot-firewall')]);
        }

        try {
            $result = method_exists($challenges, 'test_api_detection') ? $challenges->test_api_detection($url, $method) : false;

            $details = [];
            if (strpos($url, '/wp-json/') !== false) {
                $details[] = esc_html__('WordPress REST API pattern detected', 'botfend-anti-bot-firewall');
            }
            if (strpos($url, wp_parse_url(admin_url('admin-ajax.php'), PHP_URL_PATH)) !== false) {
                $details[] = esc_html__('Admin AJAX endpoint', 'botfend-anti-bot-firewall');
            }
            if (strpos($url, '/api/') !== false) {
                $details[] = esc_html__('Generic API pattern', 'botfend-anti-bot-firewall');
            }

            wp_send_json_success(['url' => esc_url($url), 'method' => esc_html($method), 'is_api' => (bool) $result, 'details' => implode(', ', $details)]);
        } catch (Exception $e) {
            wp_send_json_error(['message' => esc_html($e->getMessage())]);
        }
    }

    public function ajax_clear_session_cache(): void {
        check_ajax_referer('botfend_admin_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Unauthorized', 'botfend-anti-bot-firewall')]);
        }

        $components = $this->core->get_components();
        $challenges = $components['challenges'] ?? null;

        if ($challenges && method_exists($challenges, 'clear_static_cache')) {
            $challenges->clear_static_cache();
            $this->clear_cache_group('session');
            wp_send_json_success(['message' => esc_html__('Session cache cleared', 'botfend-anti-bot-firewall')]);
        } else {
            wp_send_json_error(['message' => esc_html__('Method not available', 'botfend-anti-bot-firewall')]);
        }
    }

    public function handle_export_settings(): void {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have permission to perform this action.', 'botfend-anti-bot-firewall'));
        }

        if (!isset($_GET['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'botfend_export_action')) {
            wp_die(esc_html__('Security check failed.', 'botfend-anti-bot-firewall'));
        }

        $format = isset($_GET['format']) ? sanitize_text_field(wp_unslash($_GET['format'])) : 'json';
        $settings_data = $this->settings->export_settings();

        if (!$settings_data) {
            wp_die(esc_html__('Failed to export settings.', 'botfend-anti-bot-firewall'));
        }

        $filename = 'botfend-settings-' . gmdate('Y-m-d-His') . '.' . $format;

        switch ($format) {
            case 'json':
                $content_type = 'application/json';
                $content = $settings_data;
                break;
            case 'xml':
                $content_type = 'application/xml';
                $data = json_decode($settings_data, true);
                $content = $this->array_to_xml($data);
                break;
            case 'csv':
                $content_type = 'text/csv';
                $data = json_decode($settings_data, true);
                $content = $this->array_to_csv($data['settings'] ?? []);
                break;
            default:
                wp_die(esc_html__('Invalid export format.', 'botfend-anti-bot-firewall'));
        }

        while (ob_get_level()) {
            ob_end_clean();
        }

        header('Content-Description: File Transfer');
        header('Content-Type: ' . $content_type);
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . strlen($content));

        echo $content;
        exit;
    }

    private function array_to_xml(array $data, string $rootElement = 'settings', $xml = null): string {
        if ($xml === null) {
            $xml = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><' . $rootElement . '/>');
        }

        foreach ($data as $key => $value) {
            if (is_array($value)) {
                if (is_numeric($key)) {
                    $key = 'item_' . $key;
                }
                $child = $xml->addChild($key);
                $this->array_to_xml($value, $rootElement, $child);
            } else {
                $value = htmlspecialchars((string)$value);
                $xml->addChild($key, $value);
            }
        }

        return $xml->asXML();
    }

    private function array_to_csv(array $data): string {
        $flat_data = $this->flatten_array($data);
        $output = fopen('php://temp', 'r+');
        fputcsv($output, ['Setting', 'Value']);
        foreach ($flat_data as $key => $value) {
            fputcsv($output, [$key, $value]);
        }
        rewind($output);
        $csv = stream_get_contents($output);
        fclose($output);
        return $csv;
    }

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

    public function handle_import_settings(): void {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have permission to perform this action.', 'botfend-anti-bot-firewall'));
        }

        if (!isset($_POST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'botfend_import_action')) {
            wp_die(esc_html__('Security check failed.', 'botfend-anti-bot-firewall'));
        }

        if (!isset($_FILES['import_file']) || $_FILES['import_file']['error'] !== UPLOAD_ERR_OK) {
            $redirect_url = add_query_arg(['import_result' => 'error', 'import_message' => urlencode(esc_html__('No file uploaded or upload error occurred.', 'botfend-anti-bot-firewall'))], admin_url('admin.php?page=botfend-settings&tab=system'));
            wp_safe_redirect(esc_url($redirect_url));
            exit;
        }

        $file = $_FILES['import_file'];
        $validate_only = isset($_POST['validate_only']) && $_POST['validate_only'] === '1';
        $content = file_get_contents($file['tmp_name']);

        if (!$content) {
            $redirect_url = add_query_arg(['import_result' => 'error', 'import_message' => urlencode(esc_html__('Failed to read uploaded file.', 'botfend-anti-bot-firewall'))], admin_url('admin.php?page=botfend-settings&tab=system'));
            wp_safe_redirect(esc_url($redirect_url));
            exit;
        }

        $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
        $settings_data = null;
        $parse_error = null;

        try {
            switch (strtolower($extension)) {
                case 'json':
                    $settings_data = json_decode($content, true);
                    if (json_last_error() !== JSON_ERROR_NONE) {
                        $parse_error = esc_html__('Invalid JSON file.', 'botfend-anti-bot-firewall');
                    }
                    break;
                case 'xml':
                    $settings_data = $this->xml_to_array($content);
                    if ($settings_data === null) {
                        $parse_error = esc_html__('Invalid XML file format.', 'botfend-anti-bot-firewall');
                    }
                    break;
                case 'csv':
                    $settings_data = $this->csv_to_settings_array($content);
                    if (empty($settings_data)) {
                        $parse_error = esc_html__('Invalid CSV file format.', 'botfend-anti-bot-firewall');
                    }
                    break;
                default:
                    $parse_error = esc_html__('Unsupported file format. Please upload JSON, XML, or CSV.', 'botfend-anti-bot-firewall');
            }
        } catch (Exception $e) {
            $parse_error = esc_html__('Error parsing file.', 'botfend-anti-bot-firewall');
        }

        if ($parse_error || !$settings_data) {
            $redirect_url = add_query_arg(['import_result' => 'error', 'import_message' => urlencode($parse_error ?: esc_html__('Failed to parse settings file.', 'botfend-anti-bot-firewall'))], admin_url('admin.php?page=botfend-settings&tab=system'));
            wp_safe_redirect(esc_url($redirect_url));
            exit;
        }

        if ($validate_only) {
            $redirect_url = add_query_arg(['import_result' => 'success', 'import_message' => urlencode(esc_html__('File validation successful! Settings are valid.', 'botfend-anti-bot-firewall'))], admin_url('admin.php?page=botfend-settings&tab=system'));
            wp_safe_redirect(esc_url($redirect_url));
            exit;
        }

        $backup_first = isset($_POST['backup_first']) && $_POST['backup_first'] === '1';
        if ($backup_first) {
            $backup_data = $this->settings->export_settings();
            set_transient('botfend_last_backup', $backup_data, 300);
        }

        $import_result = $this->settings->import_settings(json_encode($settings_data));

        if (is_wp_error($import_result)) {
            $redirect_url = add_query_arg(['import_result' => 'error', 'import_message' => urlencode($import_result->get_error_message())], admin_url('admin.php?page=botfend-settings&tab=system'));
        } else {
            $message = sprintf(esc_html__('Import successful! %d settings imported, %d skipped.', 'botfend-anti-bot-firewall'), $import_result['imported'], $import_result['skipped']);
            $redirect_url = add_query_arg(['import_result' => 'success', 'import_message' => urlencode($message)], admin_url('admin.php?page=botfend-settings&tab=system'));
            $this->clear_cache_group('logs');
            $this->clear_cache_group('blocklist');
            $this->clear_cache_group('adaptive');
            $this->clear_cache_group('dashboard');
        }

        wp_safe_redirect(esc_url($redirect_url));
        exit;
    }

    /**
     * Convert XML to array safely - REMOVED deprecated libxml_disable_entity_loader()
     * LIBXML_NONET is sufficient for XXE prevention on all supported PHP versions
     *
     * @param string $xml_string
     * @return array|null
     */
    private function xml_to_array(string $xml_string): ?array {
        $xml = simplexml_load_string($xml_string, 'SimpleXMLElement', LIBXML_NONET);

        if ($xml === false) {
            return null;
        }

        $json = json_encode($xml);
        return json_decode($json, true);
    }

    private function csv_to_settings_array(string $csv_content): ?array {
        $lines = explode("\n", trim($csv_content));
        if (count($lines) < 2) {
            return null;
        }

        $settings = ['settings' => []];

        for ($i = 1; $i < count($lines); $i++) {
            $line = trim($lines[$i]);
            if (empty($line)) continue;

            $parts = str_getcsv($line);
            if (count($parts) >= 2) {
                $key = trim($parts[0]);
                $value = trim($parts[1]);

                $keys = explode('.', $key);
                $current = &$settings['settings'];
                
                foreach ($keys as $k) {
                    if (!isset($current[$k]) || !is_array($current[$k])) {
                        $current[$k] = [];
                    }
                    $current = &$current[$k];
                }
                
                $current = $value;
            }
        }

        $settings['plugin'] = 'BotFend Anti-Bot Firewall';
        $settings['version'] = BOTFEND_VERSION;
        $settings['export_date'] = current_time('mysql');

        return $settings;
    }

    public function ajax_reset_session_errors(): void {
        check_ajax_referer('botfend_admin_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Unauthorized', 'botfend-anti-bot-firewall')]);
        }

        delete_transient('botfend_session_error_count');
        $this->clear_cache_group('session');

        wp_send_json_success(['message' => esc_html__('Session errors reset', 'botfend-anti-bot-firewall')]);
    }
}