<?php
defined('ABSPATH') || exit;

// Define plugin version if not already defined
if (!defined('WPSEC_VERSION')) {
    define('WPSEC_VERSION', '1.0.0');
}

/**
 * Fetch malware signatures from the remote server and save locally.
 */
function wpsec_get_signature_database() {
    $local_path = WP_CONTENT_DIR . '/uploads/wpsec-signatures.json';
    $url = 'https://server.wpfort.ai:8443/signatures.json';
    $backup_url = 'http://95.179.233.162:8082/signatures.json';

    wpsec_debug_log('🌐 Attempting to download malware signatures', 'info');

    // Try cached version first if it exists and is less than 24 hours old
    if (file_exists($local_path)) {
        $cache_age = time() - filemtime($local_path);
        if ($cache_age < 86400) { // 24 hours
            $cached = wpsec_use_cached_database('signatures');
            if ($cached) {
                wpsec_debug_log('✅ Using valid cached signatures (age: ' . round($cache_age / 3600, 1) . ' hours)', 'info');
                return $cached;
            }
        }
    }

    // Ensure the directory exists
    $dir = dirname($local_path);
    // Initialize WordPress Filesystem
    global $wp_filesystem;
    if (empty($wp_filesystem)) {
        require_once(ABSPATH . '/wp-admin/includes/file.php');
        WP_Filesystem();
    }
    
    if (!file_exists($dir)) {
        wpsec_debug_log('📁 Directory not found. Creating: ' . $dir, 'info');
        if (!wp_mkdir_p($dir)) {
            wpsec_debug_log('❗ Failed to create directory: ' . $dir, 'info');
            return wpsec_use_cached_database('signatures');
        }
    }

    // Try primary URL first
    $signatures = wpsec_fetch_remote_database($url);
    
    // If primary fails, try backup URL
    if (!$signatures) {
        wpsec_debug_log('⚠️ Primary URL failed, trying backup URL', 'warning');
        $signatures = wpsec_fetch_remote_database($backup_url);
    }
    
    // If both fail, try cached version
    if (!$signatures) {
        return wpsec_use_cached_database('signatures');
    }

    // Validate signature format
    if (!wpsec_validate_signature_database($signatures)) {
        wpsec_debug_log('❗ Invalid signature database format', 'info');
        return wpsec_use_cached_database('signatures');
    }

    // Save signatures locally
    if (file_put_contents($local_path, json_encode($signatures, JSON_PRETTY_PRINT)) === false) {
        wpsec_debug_log('❌ Failed to save signatures to ' . $local_path, 'error');
        return $signatures; // Still return the valid signatures even if we couldn't cache them
    }

    wpsec_debug_log('✅ Signatures saved to: ' . $local_path, 'info');
    wpsec_debug_log('📋 MD5 signatures: ' . count($signatures['md5_sigs']) . ' | SHA1 signatures: ' . count($signatures['sha1_sigs']), 'info');
    return $signatures;
}

/**
 * Helper function to fetch remote database with proper error handling
 */
function wpsec_fetch_remote_database($url) {
    $args = [
        'timeout' => 60, // Increased timeout for slow connections
        'sslverify' => false, // Not needed for HTTP
        'headers' => [
            'User-Agent' => 'WordPress/' . get_bloginfo('version') . '; ' . get_bloginfo('url'),
            'X-WPSec-Version' => WPSEC_VERSION
        ],
        'httpversion' => '1.1',
        'blocking' => true
    ];

    wpsec_debug_log('🔄 Fetching database from: ' . $url, 'info');
    $start_time = microtime(true);
    
    $response = wp_remote_get($url, $args);
    
    $duration = round((microtime(true) - $start_time) * 1000);
    wpsec_debug_log("⏱️ Request took {$duration}ms", 'info');

    if (is_wp_error($response)) {
        wpsec_debug_log('❌ Failed to fetch database: ' . $response->get_error_message(), 'error');
        return null;
    }

    $status_code = wp_remote_retrieve_response_code($response);
    if ($status_code !== 200) {
        wpsec_debug_log('❗ Unexpected HTTP response code: ' . $status_code, 'info');
        return null;
    }

    $body = wp_remote_retrieve_body($response);
    if (!$body) {
        wpsec_debug_log('❗ Empty response from API', 'info');
        return null;
    }

    $data = json_decode($body, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        wpsec_debug_log('❗ JSON decode error: ' . json_last_error_msg(), 'error');
        return null;
    }

    return $data;
}

/**
 * Fetch malware patterns from the remote server and save locally.
 */
function wpsec_get_pattern_database() {
    $local_path = WP_CONTENT_DIR . '/uploads/wpsec-patterns.json';
    $url = 'https://server.wpfort.ai:8443/patterns.json';
    $backup_url = 'http://95.179.233.162:8082/patterns.json';

    wpsec_debug_log('🌐 Attempting to download malware patterns', 'info');

    // Try cached version first if it exists and is less than 24 hours old
    if (file_exists($local_path)) {
        $cache_age = time() - filemtime($local_path);
        if ($cache_age < 86400) { // 24 hours
            $cached = wpsec_use_cached_database('patterns');
            if ($cached) {
                wpsec_debug_log('✅ Using valid cached patterns (age: ' . round($cache_age / 3600, 1) . ' hours)', 'info');
                return $cached;
            }
        }
    }

    // Ensure the directory exists
    $dir = dirname($local_path);
    // Make sure WordPress Filesystem is initialized
    global $wp_filesystem;
    if (empty($wp_filesystem)) {
        require_once(ABSPATH . '/wp-admin/includes/file.php');
        WP_Filesystem();
    }
    
    if (!file_exists($dir)) {
        wpsec_debug_log('📁 Directory not found. Creating: ' . $dir, 'info');
        if (!wp_mkdir_p($dir)) {
            wpsec_debug_log('❗ Failed to create directory: ' . $dir, 'info');
            return wpsec_use_cached_database('patterns');
        }
    }

    // Try primary URL first
    $patterns = wpsec_fetch_remote_database($url);
    
    // If primary fails, try backup URL
    if (!$patterns) {
        wpsec_debug_log('⚠️ Primary URL failed, trying backup URL', 'warning');
        $patterns = wpsec_fetch_remote_database($backup_url);
    }
    
    // If both fail, try cached version
    if (!$patterns) {
        return wpsec_use_cached_database('patterns');
    }

    // Validate pattern format
    if (!wpsec_validate_pattern_database($patterns)) {
        wpsec_debug_log('❗ Invalid pattern database format', 'info');
        return wpsec_use_cached_database('patterns');
    }

    // Save patterns locally
    if (file_put_contents($local_path, json_encode($patterns, JSON_PRETTY_PRINT)) === false) {
        wpsec_debug_log('❌ Failed to save patterns to ' . $local_path, 'error');
        return $patterns; // Still return the valid patterns even if we couldn't cache them
    }

    wpsec_debug_log('✅ Patterns saved to: ' . $local_path, 'info');
    wpsec_debug_log('📋 PHP patterns: ' . count($patterns['php']) . ' | JS patterns: ' . count($patterns['js']) . ' | HTML patterns: ' . count($patterns['html']), 'info');
    return $patterns;
}

// Schedule daily signature and pattern updates
if (!wp_next_scheduled('wpsec_daily_malware_db_update')) {
    wp_schedule_event(time(), 'daily', 'wpsec_daily_malware_db_update');
}

add_action('wpsec_daily_malware_db_update', function() {
    wpsec_debug_log('🔄 Running scheduled malware database update', 'info');
    wpsec_get_signature_database();
    wpsec_get_pattern_database();
});

function wpsec_use_cached_database($type) {
    $local_path = WP_CONTENT_DIR . '/uploads/wpsec-' . $type . '.json';
    if (file_exists($local_path)) {
        $data = json_decode(file_get_contents($local_path), true);
        if ($data) {
            return $data;
        }
    }
    return null;
}

function wpsec_validate_signature_database($signatures) {
    if (!$signatures || !isset($signatures['md5_sigs']) || !isset($signatures['sha1_sigs'])) {
        return false;
    }
    return true;
}

function wpsec_validate_pattern_database($patterns) {
    if (!$patterns || !isset($patterns['php']) || !isset($patterns['js']) || !isset($patterns['html'])) {
        return false;
    }
    return true;
}