<?php
/**
 * Activation Fix for WPFort Security Plugin
 * 
 * This file addresses issues with the plugin activation process:
 * 1. Defers resource-intensive downloads to prevent activation timeouts
 * 2. Ensures database tables are created before they're accessed
 * 3. Improves activation sequence to prevent 504 errors
 */

// Only run if admin
if (!is_admin()) {
    return;
}

/**
 * Function to safely defer signature and pattern downloads
 * Instead of running them during activation (which causes timeouts)
 */
function wpsec_defer_downloads() {
    // Only schedule if not already scheduled
    if (!wp_next_scheduled('wpsec_download_signatures_event')) {
        wp_schedule_single_event(time() + 10, 'wpsec_download_signatures_event');
    }
    
    if (!wp_next_scheduled('wpsec_download_patterns_event')) {
        wp_schedule_single_event(time() + 20, 'wpsec_download_patterns_event');
    }
}

/**
 * Function to initialize activity log table on plugin activation
 * before any logging is attempted
 */
function wpsec_ensure_tables_exist() {
    if (function_exists('wpsec_activity_log_init')) {
        wpsec_activity_log_init();
    }
}

/**
 * Override the activation hook to use our improved version
 */
function wpsec_improved_activation() {
    // First ensure database tables exist
    wpsec_ensure_tables_exist();
    
    // Set default API key if needed
    if (!get_option('wpsec_api_key')) {
        add_option('wpsec_api_key', 'sadasda78as78sda78sda78sfa687fajk');
    }
    
    // Run firewall installation
    if (class_exists('WPSEC_Firewall_Installer')) {
        WPSEC_Firewall_Installer::install();
    }
    
    // Schedule deferred downloads instead of doing them synchronously
    wpsec_defer_downloads();
}

/**
 * Apply our modifications
 */
function wpsec_apply_activation_fixes() {
    // Get the main plugin file path
    $main_plugin_file = dirname(__FILE__) . '/wpfortai-security.php';
    
    // Remove the original activation hooks if possible
    $file = plugin_basename($main_plugin_file);
    remove_action('activate_' . $file, 'WPSEC_Firewall_Installer::install');
    
    // Add our improved activation hook
    register_activation_hook($main_plugin_file, 'wpsec_improved_activation');
    
    // Add action hooks for the deferred downloads
    add_action('wpsec_download_signatures_event', 'wpsec_get_signature_database');
    add_action('wpsec_download_patterns_event', 'wpsec_get_pattern_database');
}

// Run our fixes
add_action('plugins_loaded', 'wpsec_apply_activation_fixes', 5);
