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

/**
 * WPFort Security - Uptime Monitoring
 * 
 * Provides lightweight uptime monitoring functionality with minimal server impact.
 * Designed to work across all hosting environments including shared hosting.
 */

/**
 * Get critical system status data for uptime monitoring
 *
 * Collects essential metrics while minimizing resource usage.
 * This function is optimized for quick execution even on limited hosting environments.
 * 
 * @return array System status data
 */
function wpsec_get_uptime_status() {
    global $wpdb;
    
    // Start measuring response time
    $start_time = microtime(true);
    
    // Basic WordPress status - extremely lightweight check
    $wp_status = array(
        'is_wp_error' => false,
    );
    
    // Check if there are fatal PHP errors in the error log (if accessible)
    $has_fatal_errors = false;
    $error_log_path = ini_get('error_log');
    if ($error_log_path && @is_readable($error_log_path)) {
        // Use efficient file reading to check only recent entries
        $log_data = @file_get_contents($error_log_path, false, null, -8192); // Read last 8KB only
        if ($log_data !== false) {
            // Check for fatal errors in the last 8KB of the log
            $has_fatal_errors = (strpos($log_data, 'Fatal error') !== false || 
                                 strpos($log_data, 'Uncaught Error') !== false);
        }
    }
    
    // Check database connectivity with minimal query
    $db_status = array(
        'connected' => false,
        'error' => null
    );
    
    try {
        // Extremely lightweight query to verify database connection
        $result = $wpdb->get_var("SELECT 1");
        $db_status['connected'] = ($result === '1' || $result === 1);
    } catch (Exception $e) {
        $db_status['error'] = 'Database connection error';
    }
    
    // Check site accessibility by testing if we can load wp-includes
    $files_accessible = @is_readable(ABSPATH . 'wp-includes/version.php');
    
    // Check if the site is in maintenance mode
    $maintenance_mode = file_exists(ABSPATH . '.maintenance');
    
    // Check memory usage - important for detecting potential issues
    $memory_status = array(
        'usage' => memory_get_usage(true),
        'limit' => wpsec_convert_hr_to_bytes(ini_get('memory_limit')),
        'usage_percent' => 0
    );
    
    if ($memory_status['limit'] > 0) {
        $memory_status['usage_percent'] = round(($memory_status['usage'] / $memory_status['limit']) * 100, 1);
    }
    
    // Check if any critical plugin functions are failing
    $plugin_status = array(
        'active' => is_plugin_active('wpfortai-security/wpfortai-security.php'),
        'malware_db_accessible' => false
    );
    
    // Verify access to malware signatures (very lightweight check - just file existence)
    $local_path = WP_CONTENT_DIR . '/uploads/wpsec-signatures.json';
    $plugin_status['malware_db_accessible'] = @file_exists($local_path);
    
    // Add processing time
    $processing_time = round((microtime(true) - $start_time) * 1000, 2); // in ms
    
    // Determine overall health status based on key metrics
    $is_healthy = $db_status['connected'] && 
                 $files_accessible && 
                 !$maintenance_mode && 
                 $plugin_status['active'] && 
                 !$has_fatal_errors && 
                 $memory_status['usage_percent'] < 90;
    
    // Return concise status information
    return array(
        'status' => $is_healthy ? 'healthy' : 'unhealthy',
        'timestamp' => time(),
        'response_time' => $processing_time,
        'wp_version' => get_bloginfo('version'),
        'wpsec_version' => defined('WPSEC_VERSION') ? WPSEC_VERSION : 'unknown',
        'maintenance_mode' => $maintenance_mode,
        'database' => $db_status,
        'memory' => array(
            'usage_percent' => $memory_status['usage_percent'],
            'critical' => $memory_status['usage_percent'] > 85
        ),
        'filesystem' => array(
            'accessible' => $files_accessible
        ),
        'has_fatal_errors' => $has_fatal_errors,
        'plugin_status' => $plugin_status['active']
    );
}

/**
 * Utility function to convert memory string (e.g., '256M') to bytes
 * 
 * @param string $value Memory value with unit
 * @return int Value in bytes
 */
function wpsec_convert_hr_to_bytes($value) {
    $value = strtolower(trim($value));
    $bytes = (int) $value;
    
    if (strpos($value, 'g') !== false) {
        $bytes *= 1024 * 1024 * 1024;
    } elseif (strpos($value, 'm') !== false) {
        $bytes *= 1024 * 1024;
    } elseif (strpos($value, 'k') !== false) {
        $bytes *= 1024;
    }
    
    return $bytes;
}

/**
 * Get monitor interval in seconds based on the tier level
 * 
 * Tier 1: Every 10 minutes
 * Tier 2: Every 5 minutes
 * Tier 3: Every 2 minutes  
 * Tier 4: Every 1 minute
 * 
 * @param int $tier Tier level (1-4)
 * @return int Interval in seconds
 */
function wpsec_get_monitor_interval($tier = 1) {
    $tier = min(4, max(1, (int) $tier)); // Ensure tier is between 1-4
    
    switch ($tier) {
        case 4:
            return 60; // 1 minute
        case 3:
            return 120; // 2 minutes
        case 2:
            return 300; // 5 minutes
        case 1:
        default:
            return 600; // 10 minutes
    }
}

/**
 * Get the tier level from the license data
 * 
 * @return int Tier level (1-4)
 */
function wpsec_get_tier_level() {
    // This would normally come from your license system
    // For now, we'll have a placeholder that reads from options
    $tier = get_option('wpsec_license_tier', 1);
    return min(4, max(1, (int) $tier));
}

/**
 * Get monitor interval as a readable string
 * 
 * @param int $tier Tier level
 * @return string Human-readable interval
 */
function wpsec_get_monitor_interval_text($tier = 1) {
    $seconds = wpsec_get_monitor_interval($tier);
    
    if ($seconds < 60) {
        return $seconds . ' seconds';
    } elseif ($seconds == 60) {
        return '1 minute';
    } else {
        return ($seconds / 60) . ' minutes';
    }
}

/**
 * Helper function to log uptime checks for debugging purposes
 * 
 * @param array $status Status data
 * @param string $result Check result
 * @return void
 */
function wpsec_log_uptime_check($status, $result = 'completed') {
    if (defined('WP_DEBUG') && WP_DEBUG) {
        wpsec_debug_log(sprintf(
            'WPSEC Uptime check %s: Status=%s, Time=%sms, Memory=%s%%',
            $result,
            $status['status'],
            $status['response_time'],
            $status['memory']['usage_percent']
        ), 'info');
    }
}
