<?php
/**
 * Plugin Name: BotFend Anti-Bot Firewall
 * Plugin URI: https://wordpress.org/plugins/botfend-anti-bot-firewall/
 * Description: Professional security plugin that protects WordPress sites from malicious bots, spam, and severe server attacks using an advanced Web Application Firewall (WAF) and real-time threat intelligence.
 * Version: 4.9.1
 * Author: Omajemite Don
 * Author URI: https://ejesgist.com/developer/
 * License: GPL v2 or later
 * Text Domain: botfend-anti-bot-firewall
 * Domain Path: /languages
 * Requires at least: 6.4
 * Tested up to: 7.0
 * Requires PHP: 8.0
 */

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

// ============================================
// DEFINE PLUGIN CONSTANTS
// ============================================
define('BOTFEND_VERSION', '4.9.1');
define('BOTFEND_FILE', __FILE__);
define('BOTFEND_PATH', plugin_dir_path(__FILE__));
define('BOTFEND_URL', plugin_dir_url(__FILE__));
define('BOTFEND_BASENAME', plugin_basename(__FILE__));
define('BOTFEND_INC_PATH', BOTFEND_PATH . 'includes/');
define('BOTFEND_ADMIN_PATH', BOTFEND_PATH . 'admin/');
define('BOTFEND_ASSETS_URL', BOTFEND_URL . 'assets/');

// FIXED: Use uploads directory instead of WP_CONTENT_DIR
$upload_dir = wp_upload_dir();
define('BOTFEND_DATA_DIR', $upload_dir['basedir'] . '/botfend-anti-bot-firewall/');
define('BOTFEND_LOG_DIR', BOTFEND_DATA_DIR . 'logs/');

// ============================================
// LOAD AUTOLOADER
// ============================================
require_once BOTFEND_INC_PATH . 'core/Autoloader.php';
BotFend\Core\Autoloader::register();

// ============================================
// GLOBAL DATABASE INSTANCE REFERENCE
// ============================================
$GLOBALS['botfend_database'] = null;

// ============================================
// CREATE DATA DIRECTORY ON ACTIVATION
// ============================================
function botfend_create_data_directory(): void {
    // Create main data directory
    if (!file_exists(BOTFEND_DATA_DIR)) {
        wp_mkdir_p(BOTFEND_DATA_DIR);
        
        // Add index.php for security
        $index_content = "<?php\n// Silence is golden.\n";
        file_put_contents(BOTFEND_DATA_DIR . 'index.php', $index_content);
        
        // Add .htaccess to prevent direct access
        $htaccess_content = "Deny from all\n";
        file_put_contents(BOTFEND_DATA_DIR . '.htaccess', $htaccess_content);
    }
    
    // Create logs subdirectory
    if (!file_exists(BOTFEND_LOG_DIR)) {
        wp_mkdir_p(BOTFEND_LOG_DIR);
        
        // Add index.php for security
        $index_content = "<?php\n// Silence is golden.\n";
        file_put_contents(BOTFEND_LOG_DIR . 'index.php', $index_content);
        
        // Add .htaccess to prevent direct access
        $htaccess_content = "Deny from all\n";
        file_put_contents(BOTFEND_LOG_DIR . '.htaccess', $htaccess_content);
    }
}

// ============================================
// SET DEFAULT OPTIONS (ALL EXTERNAL SERVICES OFF)
// ============================================
function botfend_set_default_options(): void {
    // External services - ALL DISABLED BY DEFAULT (opt-in required)
    $external_options = [
        'botfend_enable_geolocation' => 0,
        'botfend_enable_external_tor_check' => 0,
        'botfend_enable_threat_intel' => 0,
        'botfend_enable_iphub' => 0,
        'botfend_enable_abuseipdb' => 0,
        'botfend_geolocation_service' => 'local', // Use local database, not external API
        // Cloudflare settings
        'botfend_cf_enabled' => 0,
        'botfend_cf_auth_method' => 'key', // Changed default to 'key' (Global API Key is recommended)
        'botfend_cf_api_token' => '',
        'botfend_cf_email' => '',
        'botfend_cf_api_key' => '',
        'botfend_cf_zone_id' => '',
        'botfend_cf_account_id' => '',
        'botfend_cf_sync_blocks' => 1,
        'botfend_cf_min_block_score' => 5,
        'botfend_cf_challenge_action' => 'block', // Changed default to 'block'
        // License settings
        'botfend_license_key' => '',
        'botfend_license_data' => '',
    ];
    
    foreach ($external_options as $option => $default) {
        if (false === get_option($option)) {
            add_option($option, $default);
        }
    }
    
    // Other security options
    $security_options = [
        'botfend_enabled' => 1,
        'botfend_adaptive_mode' => 'balanced',
        'botfend_enable_waf' => 1,
        'botfend_block_duration' => 24,
        'botfend_rate_limit' => 100,
        'botfend_max_404s' => 10,
        'botfend_enable_smart_aggregation' => 1,
        'botfend_enable_centralized_logging' => 1,
        'botfend_max_detailed_logs' => 300,
        'botfend_log_sampling_rate' => 0.1,
        'botfend_critical_score_threshold' => 7,
        'botfend_aggregate_after_hours' => 24,
        'botfend_keep_aggregates_days' => 90,
        'botfend_log_throttle_seconds' => 10,
        'botfend_log_deduplication_window' => 300,
        'botfend_enable_smart_duration' => 1,
        'botfend_debug_mode' => 0,
    ];
    
    foreach ($security_options as $option => $default) {
        if (false === get_option($option)) {
            add_option($option, $default);
        }
    }
}

// ============================================
// ACTIVATION HOOK
// ============================================
function botfend_activate(): void {
    try {
        // Set default options first
        botfend_set_default_options();
        
        // Create data directory
        botfend_create_data_directory();
        
        $activator = new BotFend\Core\Activator();
        $activator->activate();
        
        BotFend\Core\Activator::mark_just_activated();
        
        // Force database tables creation on activation
        if (class_exists('BotFend\Database\Database')) {
            $database = new BotFend\Database\Database();
            $database->create_tables();
            $GLOBALS['botfend_database'] = $database;
        }
        
        // Initialize Cloudflare sync table if Cloudflare classes exist
        if (class_exists('BotFend\\Cloudflare\\CloudflareAPI') && class_exists('BotFend\\Cloudflare\\CloudflareSync')) {
            try {
                $encryption = BotFend\Security\Encryption::get_instance();
                $config = BotFend\Core\Config::get_instance();
                $api = new BotFend\Cloudflare\CloudflareAPI($config, $encryption);
                $sync = new BotFend\Cloudflare\CloudflareSync($api, $config);
                // Table creation happens in CloudflareSync constructor
            } catch (\Throwable $e) {
                error_log('BotFend Cloudflare init during activation: ' . $e->getMessage());
            }
        }
        
        if (function_exists('flush_rewrite_rules')) {
            flush_rewrite_rules();
        }
        
    } catch (\Throwable $e) {
        error_log('BotFend activation error: ' . $e->getMessage());
        
        add_action('admin_notices', function() use ($e) {
            echo '<div class="notice notice-error"><p>';
            echo '<strong>' . esc_html__('BotFend Anti-Bot Firewall:', 'botfend-anti-bot-firewall') . '</strong> ';
            echo esc_html($e->getMessage());
            echo '</p></div>';
        });
        
        wp_die(
            esc_html__('BotFend Anti-Bot Firewall could not be activated. Check error log for details.', 'botfend-anti-bot-firewall'),
            esc_html__('Plugin Activation Error', 'botfend-anti-bot-firewall'),
            ['back_link' => true]
        );
    }
}
register_activation_hook(__FILE__, 'botfend_activate');

// ============================================
// DEACTIVATION HOOK
// ============================================
function botfend_deactivate(): void {
    try {
        $deactivator = new BotFend\Core\Deactivator();
        $deactivator->deactivate();
        
        delete_transient('botfend_just_activated');
        
        if (function_exists('flush_rewrite_rules')) {
            flush_rewrite_rules();
        }
        
    } catch (\Throwable $e) {
        error_log('BotFend deactivation error: ' . $e->getMessage());
    }
}
register_deactivation_hook(__FILE__, 'botfend_deactivate');

// ============================================
// UNINSTALL HOOK
// ============================================
function botfend_uninstall(): void {
    if (!defined('WP_UNINSTALL_PLUGIN')) {
        return;
    }
    
    try {
        // Clean up data directory on uninstall if option is set
        $remove_data = get_option('botfend_remove_data_on_uninstall', false);
        
        if ($remove_data) {
            // Recursively delete data directory
            if (file_exists(BOTFEND_DATA_DIR)) {
                $files = new RecursiveIteratorIterator(
                    new RecursiveDirectoryIterator(BOTFEND_DATA_DIR, RecursiveDirectoryIterator::SKIP_DOTS),
                    RecursiveIteratorIterator::CHILD_FIRST
                );
                
                foreach ($files as $fileinfo) {
                    if ($fileinfo->isDir()) {
                        rmdir($fileinfo->getRealPath());
                    } else {
                        unlink($fileinfo->getRealPath());
                    }
                }
                rmdir(BOTFEND_DATA_DIR);
            }
            
            // Clean up Cloudflare sync table
            global $wpdb;
            $cf_sync_table = $wpdb->prefix . 'botfend_cf_sync';
            $wpdb->query("DROP TABLE IF EXISTS {$cf_sync_table}");
            
            // Clean up Cloudflare options
            $cf_options = [
                'botfend_cf_enabled',
                'botfend_cf_auth_method',
                'botfend_cf_api_token',
                'botfend_cf_email',
                'botfend_cf_api_key',
                'botfend_cf_zone_id',
                'botfend_cf_account_id',
                'botfend_cf_sync_blocks',
                'botfend_cf_min_block_score',
                'botfend_cf_challenge_action',
                'botfend_cf_last_sync',
                'botfend_cf_errors',
            ];
            foreach ($cf_options as $option) {
                delete_option($option);
            }
            
            // Clean up license options
            delete_option('botfend_license_key');
            delete_option('botfend_license_data');
        }
        
        $uninstaller = new BotFend\Core\Uninstaller();
        $uninstaller->uninstall();
        
    } catch (\Throwable $e) {
        error_log('BotFend uninstall error: ' . $e->getMessage());
    }
}
register_uninstall_hook(__FILE__, 'botfend_uninstall');

// ============================================
// BOOTSTRAP INITIALIZATION
// ============================================
function botfend_bootstrap(): void {
    static $bootstrapped = false;
    
    if ($bootstrapped) {
        return;
    }
    
    try {
        $bootstrap = BotFend\Core\Bootstrap::get_instance();
        $bootstrap->init();
        
        $GLOBALS['botfend_bootstrap'] = $bootstrap;
        $bootstrapped = true;
        
        // DEPRECATED: Cloudflare initialization is now handled inside Bootstrap
        // with proper license checking. Keeping this as fallback for compatibility.
        // The Bootstrap class now checks license before initializing Cloudflare.
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            $config = BotFend\Core\Config::get_instance();
            if ($config->get_bool('debug_mode', false)) {
                error_log('BotFend: Bootstrap initialized successfully');
                
                // Log license status for debugging
                $license = $bootstrap->get_license();
                if ($license && $license->is_valid()) {
                    error_log('BotFend: Pro license active with features: ' . implode(', ', array_keys($license->get_license_data()['features'] ?? [])));
                }
            }
        }
        
    } catch (\Throwable $e) {
        error_log('BotFend bootstrap error: ' . $e->getMessage());
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            add_action('admin_notices', function() use ($e) {
                echo '<div class="notice notice-error"><p>';
                echo '<strong>' . esc_html__('BotFend Error:', 'botfend-anti-bot-firewall') . '</strong> ';
                echo esc_html($e->getMessage());
                echo '</p></div>';
            });
        }
    }
}
add_action('init', 'botfend_bootstrap', 5);

// ============================================
// ADMIN INITIALIZATION
// ============================================
function botfend_admin_init(): void {
    if (!is_admin() || wp_doing_cron() || wp_doing_ajax()) {
        return;
    }
    
    if (!isset($GLOBALS['botfend_bootstrap']) || !$GLOBALS['botfend_bootstrap']) {
        botfend_bootstrap();
        
        if (!isset($GLOBALS['botfend_bootstrap']) || !$GLOBALS['botfend_bootstrap']) {
            return;
        }
    }
    
    $bootstrap = $GLOBALS['botfend_bootstrap'];
    
    if (!$bootstrap->is_initialized()) {
        return;
    }
    
    if (function_exists('get_current_screen')) {
        $screen = get_current_screen();
        if ($screen && strpos($screen->id, 'botfend') !== false) {
            // Admin initialization handled by Bootstrap
        }
    }
}
add_action('admin_init', 'botfend_admin_init', 999);

// ============================================
// SINGLE AJAX HANDLER FOR NOTICE DISMISSAL
// ============================================
function botfend_ajax_dismiss_notice(): void {
    check_ajax_referer('botfend_dismiss_notice', 'nonce');
    
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => esc_html__('Unauthorized', 'botfend-anti-bot-firewall')]);
        return;
    }
    
    $notice_id = isset($_POST['notice_id']) ? sanitize_key(wp_unslash($_POST['notice_id'])) : '';
    
    if (empty($notice_id)) {
        wp_send_json_error(['message' => esc_html__('Invalid notice ID', 'botfend-anti-bot-firewall')]);
        return;
    }
    
    $user_id = get_current_user_id();
    update_user_meta($user_id, 'botfend_dismissed_' . $notice_id, time());
    
    wp_send_json_success(['message' => esc_html__('Notice dismissed', 'botfend-anti-bot-firewall')]);
}
add_action('wp_ajax_botfend_dismiss_admin_notice', 'botfend_ajax_dismiss_notice');

// ============================================
// REDIRECT AFTER ACTIVATION
// ============================================
function botfend_activation_redirect(): void {
    if (!BotFend\Core\Activator::was_just_activated()) {
        return;
    }
    
    BotFend\Core\Activator::clear_just_activated();
    
    if (wp_doing_ajax() || wp_doing_cron()) {
        return;
    }
    
    $action = isset($_GET['action']) ? sanitize_text_field(wp_unslash($_GET['action'])) : '';
    if ($action === 'activate-selected' || $action === 'activate-multi') {
        return;
    }
    
    if (!current_user_can('manage_options')) {
        return;
    }
    
    wp_safe_redirect(admin_url('admin.php?page=botfend-dashboard'));
    exit;
}
add_action('admin_init', 'botfend_activation_redirect');

// ============================================
// HEALTH CHECK INTEGRATION
// ============================================
function botfend_site_health_info(array $info): array {
    $bootstrap = $GLOBALS['botfend_bootstrap'] ?? null;
    $config = BotFend\Core\Config::get_instance();
    $database = $GLOBALS['botfend_database'] ?? null;
    
    $info['botfend-anti-bot-firewall'] = [
        'label' => esc_html__('BotFend Anti-Bot Firewall', 'botfend-anti-bot-firewall'),
        'fields' => [
            'version' => [
                'label' => esc_html__('Version', 'botfend-anti-bot-firewall'),
                'value' => BOTFEND_VERSION,
            ],
            'db_version' => [
                'label' => esc_html__('Database Schema Version', 'botfend-anti-bot-firewall'),
                'value' => defined('BotFend\Database\Database::DB_VERSION') ? BotFend\Database\Database::DB_VERSION : 'Unknown',
            ],
            'enabled' => [
                'label' => esc_html__('Enabled', 'botfend-anti-bot-firewall'),
                'value' => $config->get_bool('botfend_enabled', true) ? esc_html__('Yes', 'botfend-anti-bot-firewall') : esc_html__('No', 'botfend-anti-bot-firewall'),
            ],
            'adaptive_mode' => [
                'label' => esc_html__('Protection Mode', 'botfend-anti-bot-firewall'),
                'value' => ucfirst(esc_html($config->get_string('botfend_adaptive_mode', 'balanced'))),
            ],
            'waf_enabled' => [
                'label' => esc_html__('WAF', 'botfend-anti-bot-firewall'),
                'value' => $config->get_bool('botfend_enable_waf', true) ? esc_html__('Enabled', 'botfend-anti-bot-firewall') : esc_html__('Disabled', 'botfend-anti-bot-firewall'),
            ],
        ],
    ];
    
    // Add license status to health check
    if ($bootstrap && method_exists($bootstrap, 'get_license')) {
        $license = $bootstrap->get_license();
        if ($license) {
            $info['botfend-anti-bot-firewall']['fields']['license_status'] = [
                'label' => esc_html__('Pro License', 'botfend-anti-bot-firewall'),
                'value' => $license->is_valid() ? esc_html__('Active', 'botfend-anti-bot-firewall') : esc_html__('Inactive', 'botfend-anti-bot-firewall'),
            ];
            
            if ($license->is_valid()) {
                $info['botfend-anti-bot-firewall']['fields']['license_expires'] = [
                    'label' => esc_html__('License Expires', 'botfend-anti-bot-firewall'),
                    'value' => $license->get_status_text(),
                ];
            }
        }
    }
    
    // Add Cloudflare status if enabled AND license is valid
    $cloudflare_enabled = $config->get_bool('cf_enabled', false);
    if ($cloudflare_enabled) {
        // Check if license allows Cloudflare
        $license_allows_cf = false;
        if ($bootstrap && method_exists($bootstrap, 'get_license')) {
            $license = $bootstrap->get_license();
            $license_allows_cf = $license && $license->has_feature('cloudflare');
        }
        
        if (!$license_allows_cf) {
            $info['botfend-anti-bot-firewall']['fields']['cloudflare'] = [
                'label' => esc_html__('Cloudflare Integration', 'botfend-anti-bot-firewall'),
                'value' => esc_html__('Requires Pro License', 'botfend-anti-bot-firewall'),
            ];
        } else {
            $info['botfend-anti-bot-firewall']['fields']['cloudflare'] = [
                'label' => esc_html__('Cloudflare Integration', 'botfend-anti-bot-firewall'),
                'value' => esc_html__('Enabled (Pro)', 'botfend-anti-bot-firewall'),
            ];
            
            // Get sync status if available
            if (class_exists('BotFend\\Cloudflare\\CloudflareAPI') && class_exists('BotFend\\Cloudflare\\CloudflareSync')) {
                try {
                    $encryption = BotFend\Security\Encryption::get_instance();
                    $api = new BotFend\Cloudflare\CloudflareAPI($config, $encryption);
                    if ($api->is_configured()) {
                        $sync = new BotFend\Cloudflare\CloudflareSync($api, $config);
                        $sync_status = $sync->get_sync_status();
                        $info['botfend-anti-bot-firewall']['fields']['cloudflare_synced'] = [
                            'label' => esc_html__('Cloudflare IPs Synced', 'botfend-anti-bot-firewall'),
                            'value' => $sync_status['total_synced'],
                        ];
                    }
                } catch (\Throwable $e) {
                    // Silently fail in health check
                }
            }
        }
    }
    
    // Add external services status (should show disabled by default)
    $external_services_status = [];
    if (!$config->get_bool('botfend_enable_geolocation', 0)) {
        $external_services_status[] = esc_html__('Geolocation: Disabled (opt-in required)', 'botfend-anti-bot-firewall');
    }
    if (!$config->get_bool('botfend_enable_external_tor_check', 0)) {
        $external_services_status[] = esc_html__('Tor Check: Disabled (opt-in required)', 'botfend-anti-bot-firewall');
    }
    if (!$config->get_bool('botfend_enable_threat_intel', 0)) {
        $external_services_status[] = esc_html__('Threat Intel: Disabled (opt-in required)', 'botfend-anti-bot-firewall');
    }
    
    if (!empty($external_services_status)) {
        $info['botfend-anti-bot-firewall']['fields']['external_services'] = [
            'label' => esc_html__('External Services', 'botfend-anti-bot-firewall'),
            'value' => implode(', ', $external_services_status),
        ];
    }
    
    // Check if optimized indexes exist
    if ($database && method_exists($database, 'get_table_name')) {
        $logs_table = $database->get_table_name(BotFend\Database\Database::LOG_TABLE);
        global $wpdb;
        if ($logs_table) {
            $indexes = $wpdb->get_results($wpdb->prepare(
                "SHOW INDEX FROM `{$logs_table}` WHERE Key_name IN ('idx_for_aggregation', 'idx_ip_action_created_recent')"
            ));
            $has_optimized_indexes = count($indexes) === 2;
            
            $info['botfend-anti-bot-firewall']['fields']['optimized_indexes'] = [
                'label' => esc_html__('Optimized Database Indexes', 'botfend-anti-bot-firewall'),
                'value' => $has_optimized_indexes ? esc_html__('Present', 'botfend-anti-bot-firewall') : esc_html__('Missing', 'botfend-anti-bot-firewall'),
                'debug' => $has_optimized_indexes ? '' : esc_html__('Run plugin upgrade to add performance indexes.', 'botfend-anti-bot-firewall'),
            ];
        }
    }
    
    if ($bootstrap && $bootstrap->is_initialized()) {
        $benchmarks = $bootstrap->get_benchmarks();
        if (!empty($benchmarks)) {
            $info['botfend-anti-bot-firewall']['fields']['init_time'] = [
                'label' => esc_html__('Initialization Time', 'botfend-anti-bot-firewall'),
                'value' => round(($benchmarks['total_init'] ?? 0) * 1000, 2) . ' ms',
            ];
        }
    }
    
    return $info;
}
add_filter('debug_information', 'botfend_site_health_info');

// ============================================
// PLUGIN ACTION LINKS
// ============================================
function botfend_plugin_action_links(array $links): array {
    $dashboard_link = '<a href="' . esc_url(admin_url('admin.php?page=botfend-dashboard')) . '">' 
                    . esc_html__('Dashboard', 'botfend-anti-bot-firewall') . '</a>';
    $settings_link = '<a href="' . esc_url(admin_url('admin.php?page=botfend-settings')) . '">' 
                    . esc_html__('Settings', 'botfend-anti-bot-firewall') . '</a>';
    $license_link = '<a href="' . esc_url(admin_url('admin.php?page=botfend-license')) . '" class="botfend-pro-link">' 
                   . esc_html__('Pro License', 'botfend-anti-bot-firewall') . '</a>';
    $cloudflare_link = '<a href="' . esc_url(admin_url('admin.php?page=botfend-cloudflare')) . '">' 
                      . esc_html__('Cloudflare', 'botfend-anti-bot-firewall') . '</a>';
    $docs_link = '<a href="https://wordpress.org/plugins/botfend-anti-bot-firewall/" target="_blank" rel="noopener noreferrer">' 
                . esc_html__('Docs', 'botfend-anti-bot-firewall') . '</a>';
    
    array_unshift($links, $dashboard_link);
    array_unshift($links, $settings_link);
    array_unshift($links, $license_link);
    array_unshift($links, $cloudflare_link);
    $links[] = $docs_link;
    
    return $links;
}
add_filter('plugin_action_links_' . BOTFEND_BASENAME, 'botfend_plugin_action_links');

// Add pro badge styling to action links
function botfend_enqueue_admin_styles(): void {
    wp_add_inline_style(
        'wp-admin',
        '.botfend-pro-link { color: #f05a28 !important; font-weight: bold; }' .
        '.botfend-pro-link:hover { color: #dc3232 !important; }'
    );
}
add_action('admin_enqueue_scripts', 'botfend_enqueue_admin_styles');

// ============================================
// REGISTER CSS ASSETS
// ============================================
function botfend_register_assets(): void {
    wp_register_style(
        'botfend-block-screen',
        BOTFEND_ASSETS_URL . 'css/botfend-block-screen.css',
        array(),
        BOTFEND_VERSION,
        'all'
    );
}
add_action('init', 'botfend_register_assets', 1);

// ============================================
// UPGRADE ROUTINE
// ============================================
function botfend_check_upgrade(): void {
    $current_version = get_option('botfend_version', '0');
    
    if (version_compare($current_version, BOTFEND_VERSION, '<')) {
        try {
            // Ensure data directory exists on upgrade
            botfend_create_data_directory();
            
            // Set default options for new options
            botfend_set_default_options();
            
            $config = BotFend\Core\Config::get_instance();
            
            if (method_exists($config, 'migrate_all')) {
                $config->migrate_all();
            }
            
            // Create Cloudflare sync table on upgrade
            if (class_exists('BotFend\\Cloudflare\\CloudflareAPI') && class_exists('BotFend\\Cloudflare\\CloudflareSync')) {
                try {
                    $encryption = BotFend\Security\Encryption::get_instance();
                    $api = new BotFend\Cloudflare\CloudflareAPI($config, $encryption);
                    $sync = new BotFend\Cloudflare\CloudflareSync($api, $config);
                } catch (\Throwable $e) {
                    error_log('BotFend Cloudflare upgrade error: ' . $e->getMessage());
                }
            }
            
            upgrade_440:
            if (version_compare($current_version, '4.4.0', '<')) {
                // Migrate old log files from WP_CONTENT_DIR to new location
                $old_log_dir = WP_CONTENT_DIR . '/botfend-logs/';
                if (file_exists($old_log_dir) && !file_exists(BOTFEND_LOG_DIR)) {
                    wp_mkdir_p(BOTFEND_LOG_DIR);
                    $files = glob($old_log_dir . '*.log');
                    foreach ($files as $file) {
                        $filename = basename($file);
                        copy($file, BOTFEND_LOG_DIR . $filename);
                    }
                }
            }
            
            // Migrate old auth method setting (default to 'key' for new installs)
            if (version_compare($current_version, '4.9.1', '<')) {
                $auth_method = get_option('botfend_cf_auth_method', '');
                if (empty($auth_method)) {
                    update_option('botfend_cf_auth_method', 'key');
                }
            }
            
            update_option('botfend_version', BOTFEND_VERSION);
            
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log("BotFend: Upgraded from {$current_version} to " . BOTFEND_VERSION);
            }
            
        } catch (\Throwable $e) {
            error_log("BotFend upgrade error: " . $e->getMessage());
        }
    }
}
add_action('plugins_loaded', 'botfend_check_upgrade', 3);

// ============================================
// CLI COMMAND FOR MANUAL DATABASE UPGRADE
// ============================================
if (defined('WP_CLI') && WP_CLI) {
    WP_CLI::add_command('botfend upgrade-database', function() {
        WP_CLI::line('Upgrading BotFend database schema...');
        
        try {
            if (!class_exists('BotFend\Database\Database')) {
                WP_CLI::error('Database class not found. Make sure plugin is properly installed.');
                return;
            }
            
            $database = new BotFend\Database\Database();
            $database->create_tables();
            $upgraded = $database->maybe_upgrade_database();
            
            if ($upgraded) {
                WP_CLI::success('Database schema upgraded successfully to version ' . BotFend\Database\Database::DB_VERSION);
            } else {
                WP_CLI::success('Database schema is already at the latest version');
            }
        } catch (\Throwable $e) {
            WP_CLI::error('Database upgrade failed: ' . $e->getMessage());
        }
    });
    
    // Add Cloudflare sync CLI command (only works with valid license)
    WP_CLI::add_command('botfend cloudflare-sync', function($args, $assoc_args) {
        WP_CLI::line('Syncing blocked IPs to Cloudflare...');
        
        try {
            $bootstrap = BotFend\Core\Bootstrap::get_instance();
            $license = $bootstrap->get_license();
            
            if (!$license || !$license->has_feature('cloudflare')) {
                WP_CLI::error('Cloudflare integration requires a Pro license with Cloudflare feature.');
                return;
            }
            
            $config = BotFend\Core\Config::get_instance();
            $encryption = BotFend\Security\Encryption::get_instance();
            $api = new BotFend\Cloudflare\CloudflareAPI($config, $encryption);
            
            if (!$api->is_configured()) {
                WP_CLI::error('Cloudflare not configured. Please check your settings.');
                return;
            }
            
            $sync = new BotFend\Cloudflare\CloudflareSync($api, $config);
            $limit = isset($assoc_args['limit']) ? (int)$assoc_args['limit'] : 50;
            $result = $sync->sync_all_blocked_ips($limit);
            
            WP_CLI::success(sprintf('Sync complete: %d IPs synced, %d failed out of %d total.', $result['synced'], $result['failed'], $result['total']));
        } catch (\Throwable $e) {
            WP_CLI::error('Sync failed: ' . $e->getMessage());
        }
    });
}

// ============================================
// CLEANUP OLD LOG DIRECTORY ON SHUTDOWN (IF EMPTY)
// ============================================
function botfend_cleanup_old_log_dir(): void {
    $old_log_dir = WP_CONTENT_DIR . '/botfend-logs/';
    if (file_exists($old_log_dir)) {
        $files = glob($old_log_dir . '*');
        if (empty($files) || (count($files) === 1 && basename($files[0]) === 'index.php')) {
            @rmdir($old_log_dir);
        }
    }
}
add_action('shutdown', 'botfend_cleanup_old_log_dir');