<?php
/**
 * Name: Performance Monitor
 * Description: Display site performance metrics including page load time, memory usage, database queries, and render time in admin bar for developers monitoring site speed
 * Category: Utilities
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Identify Performance Bottlenecks",
 *     "description": "See real-time page load time, memory usage, and database queries in admin bar to spot pages generating 100+ queries."
 *   },
 *   {
 *     "title": "Development Optimization",
 *     "description": "Monitor performance metrics while developing to ensure code changes don't slow down site before going live."
 *   },
 *   {
 *     "title": "Quick Diagnostics",
 *     "description": "Check environment details (PHP version, MySQL version, memory limits) without accessing phpinfo or server settings."
 *   }
 * ]
 * Added: 2025-06-28
 * Tags: performance, speed, monitoring, queries, memory
 * WhereToFind: {
 *   "location": "Admin Bar",
 *   "url": "admin.php",
 *   "instructions": "Performance metrics display in admin bar",
 *   "newTab": false
 * }
 */

// Prevent direct access
if (!defined('ABSPATH')) exit;

class SwitchboardPerformanceMonitor {
    
    private $start_time;
    private $start_memory;
    
    public function __construct() {
        // Capture start time and memory
        $this->start_time = microtime(true);
        $this->start_memory = memory_get_usage();
        
        add_action('admin_bar_menu', [$this, 'add_admin_bar_menu'], 999);
        add_action('wp_enqueue_scripts', [$this, 'enqueue_styles']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_styles']);
    }
    
    public function enqueue_styles() {
        if (!is_admin_bar_showing()) return;
        
        wp_add_inline_style('admin-bar', '
            #wp-admin-bar-switchboard-performance .ab-item {
                font-family: "Monaco", "Menlo", "Consolas", monospace;
                font-size: 11px;
            }
            #wp-admin-bar-switchboard-performance .perf-metric {
                display: inline-block;
                padding: 0 8px;
                border-right: 1px solid rgba(255,255,255,0.2);
            }
            #wp-admin-bar-switchboard-performance .perf-metric:last-child {
                border-right: none;
            }
            #wp-admin-bar-switchboard-performance .perf-label {
                opacity: 0.7;
                margin-right: 4px;
            }
            #wp-admin-bar-switchboard-performance .perf-value {
                font-weight: 600;
            }
            #wp-admin-bar-switchboard-performance .perf-good { color: #46b450; }
            #wp-admin-bar-switchboard-performance .perf-warning { color: #ffb900; }
            #wp-admin-bar-switchboard-performance .perf-bad { color: #dc3232; }
            #wp-admin-bar-switchboard-performance .ab-submenu {
                background: #23282d !important;
                padding: 0 !important;
                border-radius: 4px;
                box-shadow: 0 3px 5px rgba(0,0,0,0.2);
            }
            #wp-admin-bar-switchboard-performance .ab-submenu .ab-item {
                background: #23282d !important;
                color: #eee !important;
                padding: 0 !important;
                border-radius: 4px;
            }
            #wp-admin-bar-switchboard-performance .ab-submenu .ab-item > div {
                background: #23282d !important;
                border-radius: 4px;
            }
            #wp-admin-bar-switchboard-performance .ab-submenu strong {
                color: #fff !important;
            }
            #wp-admin-bar-switchboard-performance .ab-submenu span {
                color: #a0a5aa !important;
            }
        ');
    }
    
    public function add_admin_bar_menu($wp_admin_bar) {
        if (!current_user_can('manage_options')) return;
        
        // Calculate metrics
        $load_time = microtime(true) - $this->start_time;
        $memory_used = memory_get_usage() - $this->start_memory;
        $memory_peak = memory_get_peak_usage();
        $queries = get_num_queries();
        
        // Format values
        $load_time_formatted = number_format($load_time, 3);
        $memory_used_formatted = $this->format_bytes($memory_used);
        $memory_peak_formatted = $this->format_bytes($memory_peak);
        
        // Determine status colors
        $time_class = $load_time < 1 ? 'perf-good' : ($load_time < 3 ? 'perf-warning' : 'perf-bad');
        $query_class = $queries < 50 ? 'perf-good' : ($queries < 100 ? 'perf-warning' : 'perf-bad');
        $memory_class = $memory_peak < 32 * 1024 * 1024 ? 'perf-good' : ($memory_peak < 64 * 1024 * 1024 ? 'perf-warning' : 'perf-bad');
        
        $content = sprintf(
            '<span class="perf-metric"><span class="perf-label">%s</span><span class="perf-value %s">%ss</span></span>' .
            '<span class="perf-metric"><span class="perf-label">%s</span><span class="perf-value %s">%d</span></span>' .
            '<span class="perf-metric"><span class="perf-label">%s</span><span class="perf-value %s">%s</span></span>',
            esc_html__('Time:', 'wpswitchboard'), $time_class, $load_time_formatted,
            esc_html__('Queries:', 'wpswitchboard'), $query_class, $queries,
            esc_html__('Memory:', 'wpswitchboard'), $memory_class, $memory_peak_formatted
        );
        
        $wp_admin_bar->add_node([
            'id'    => 'switchboard-performance',
            'title' => $content,
            'href'  => false,
        ]);
        
        // Add submenu with full details
        $server_software = isset($_SERVER['SERVER_SOFTWARE']) ? sanitize_text_field(wp_unslash($_SERVER['SERVER_SOFTWARE'])) : 'Unknown';
        $mysql_version = $GLOBALS['wpdb']->db_version();
        
        $wp_admin_bar->add_node([
            'parent' => 'switchboard-performance',
            'id'     => 'switchboard-perf-details',
            'title'  => sprintf(
                '<div style="padding: 12px; line-height: 1.8; font-size: 12px;">' .
                '<strong style="display: block; margin-bottom: 8px; font-size: 13px; border-bottom: 1px solid #ddd; padding-bottom: 6px;">%s</strong>' .
                '<div style="display: grid; grid-template-columns: 140px 1fr; gap: 6px;">' .
                '<span style="color: #666;">%s</span><strong>%ss</strong>' .
                '<span style="color: #666;">%s</span><strong>%d %s</strong>' .
                '<span style="color: #666;">%s</span><strong>%s</strong>' .
                '<span style="color: #666;">%s</span><strong>%s</strong>' .
                '<span style="color: #666;">%s</span><strong>%s</strong>' .
                '</div>' .
                '<strong style="display: block; margin: 12px 0 8px 0; font-size: 13px; border-bottom: 1px solid #ddd; padding-bottom: 6px;">%s</strong>' .
                '<div style="display: grid; grid-template-columns: 140px 1fr; gap: 6px;">' .
                '<span style="color: #666;">%s</span><strong>%s</strong>' .
                '<span style="color: #666;">%s</span><strong>%s</strong>' .
                '<span style="color: #666;">%s</span><strong>%s</strong>' .
                '<span style="color: #666;">%s</span><strong style="font-size: 10px;">%s</strong>' .
                '</div>' .
                '</div>',
                esc_html__('Performance Details', 'wpswitchboard'),
                esc_html__('Load Time:', 'wpswitchboard'), $load_time_formatted,
                esc_html__('Database Queries:', 'wpswitchboard'), $queries, esc_html__('queries', 'wpswitchboard'),
                esc_html__('Memory Used:', 'wpswitchboard'), $memory_used_formatted,
                esc_html__('Peak Memory:', 'wpswitchboard'), $memory_peak_formatted,
                esc_html__('Memory Limit:', 'wpswitchboard'), ini_get('memory_limit'),
                esc_html__('Environment', 'wpswitchboard'),
                esc_html__('PHP Version:', 'wpswitchboard'), PHP_VERSION,
                esc_html__('MySQL Version:', 'wpswitchboard'), $mysql_version,
                esc_html__('WordPress:', 'wpswitchboard'), get_bloginfo('version'),
                esc_html__('Server:', 'wpswitchboard'), esc_html($server_software)
            ),
            'href'   => false,
        ]);
    }
    
    private function format_bytes($bytes, $precision = 2) {
        $units = ['B', 'KB', 'MB', 'GB'];
        $bytes = max($bytes, 0);
        $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
        $pow = min($pow, count($units) - 1);
        $bytes /= pow(1024, $pow);
        return round($bytes, $precision) . $units[$pow];
    }

    /**
     * Register data locations for cleanup system
     *
     * @return array Data storage locations
     */
    public function register_data_locations() {
        return [
            'options' => [],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
        ];
    }
}

// Initialize and register with data system
$switchboard_instance = new SwitchboardPerformanceMonitor();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
