<?php
/**
 * 🚀 INTELLIGENT PERFORMANCE DASHBOARD 🚀
 * Volvo Apple Design - Smart Analytics & Optimization
 * 
 * Features:
 * - Real-time performance monitoring
 * - AI-powered recommendations
 * - Dark/Light mode toggle
 * - Advanced analytics
 * - Smart caching insights
 * - Database optimization suggestions
 */

session_start();
require_once '../config/database_optimized.php';
require_once '../includes/performance_monitor.php';

// 🔐 Security Check
if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {
    header('Location: login.php');
    exit;
}

$db = DatabaseOptimized::getInstance();
$conn = $db->getConnection();

// 👤 User Data & Theme
$current_user_id = $_SESSION['admin_user_id'] ?? null;
$current_user_name = 'Administrator';
$current_user_role = 'admin';
$current_theme = $_SESSION['current_theme'] ?? 'light'; // Check session first

if ($current_user_id) {
    $user_data = $db->getUserData($current_user_id);
    if ($user_data) {
        $current_user_name = $user_data['full_name'] ?? $user_data['username'] ?? 'Administrator';
        $current_user_role = $user_data['role'] ?? 'admin';
        $current_theme = $user_data['theme'] ?? $_SESSION['current_theme'] ?? 'light';
    }
}

// 🛡️ Admin Role Verification
if ($current_user_role !== 'admin') {
    header('Location: index.php');
    exit;
}

// 📊 Advanced Performance Analytics
$stats = PerformanceMonitor::getStats();
$performance_metrics = [
    'avg_load_time' => 0,
    'slow_pages' => 0,
    'total_queries' => 0,
    'memory_usage' => 0,
    'cache_hit_rate' => 0,
    'error_rate' => 0,
    'peak_memory' => 0,
    'query_efficiency' => 0
];

if (!empty($stats)) {
    $load_times = array_column($stats, 'total_time');
    $memory_usage = array_column($stats, 'memory_used');
    $query_counts = array_column($stats, 'query_count');
    
    $performance_metrics['avg_load_time'] = array_sum($load_times) / count($load_times);
    $performance_metrics['slow_pages'] = count(array_filter($load_times, function($time) { return $time > 1.0; }));
    $performance_metrics['total_queries'] = array_sum($query_counts);
    $performance_metrics['memory_usage'] = array_sum($memory_usage) / count($memory_usage);
    $performance_metrics['peak_memory'] = max($memory_usage);
    $performance_metrics['query_efficiency'] = $performance_metrics['total_queries'] > 0 ? 
        ($performance_metrics['avg_load_time'] / $performance_metrics['total_queries']) * 1000 : 0;
}

// 🧠 AI-Powered Recommendations
$ai_recommendations = [];

// Performance Analysis
if ($performance_metrics['avg_load_time'] > 2.0) {
    $ai_recommendations[] = [
        'type' => 'critical',
        'icon' => 'fas fa-exclamation-triangle',
        'title' => 'Kritische Ladezeiten',
        'description' => 'Durchschnittliche Ladezeit von ' . round($performance_metrics['avg_load_time'], 2) . 's ist kritisch.',
        'impact' => 'Hoch',
        'effort' => 'Mittel',
        'actions' => ['Datenbankindizes optimieren', 'Caching implementieren', 'Assets komprimieren']
    ];
} elseif ($performance_metrics['avg_load_time'] > 1.0) {
    $ai_recommendations[] = [
        'type' => 'warning',
        'icon' => 'fas fa-clock',
        'title' => 'Optimierung empfohlen',
        'description' => 'Ladezeiten können verbessert werden.',
        'impact' => 'Mittel',
        'effort' => 'Niedrig',
        'actions' => ['Query-Optimierung', 'Browser-Caching']
    ];
}

// Memory Analysis
if ($performance_metrics['memory_usage'] > 50 * 1024 * 1024) { // 50MB
    $ai_recommendations[] = [
        'type' => 'warning',
        'icon' => 'fas fa-memory',
        'title' => 'Hoher Speicherverbrauch',
        'description' => 'Speicherverbrauch von ' . round($performance_metrics['memory_usage'] / 1024 / 1024, 1) . 'MB ist hoch.',
        'impact' => 'Mittel',
        'effort' => 'Niedrig',
        'actions' => ['Memory Leaks prüfen', 'Unused Variables entfernen']
    ];
}

// Query Analysis
if ($performance_metrics['query_efficiency'] > 50) {
    $ai_recommendations[] = [
        'type' => 'info',
        'icon' => 'fas fa-database',
        'title' => 'Query-Optimierung',
        'description' => 'Datenbankabfragen können optimiert werden.',
        'impact' => 'Hoch',
        'effort' => 'Mittel',
        'actions' => ['JOINs optimieren', 'Indizes hinzufügen', 'Prepared Statements']
    ];
}

// 🎯 Smart Performance Score
$performance_score = 100;
$performance_score -= min($performance_metrics['avg_load_time'] * 20, 40); // Max 40 points for load time
$performance_score -= min($performance_metrics['slow_pages'] * 5, 20); // Max 20 points for slow pages
$performance_score -= min($performance_metrics['memory_usage'] / (1024 * 1024) * 2, 20); // Max 20 points for memory
$performance_score -= min($performance_metrics['query_efficiency'] / 10, 20); // Max 20 points for queries
$performance_score = max($performance_score, 0);

// 📈 Performance Trends (simulated for demo)
$performance_trends = [
    'load_time_trend' => rand(-15, 15), // Percentage change
    'memory_trend' => rand(-10, 10),
    'queries_trend' => rand(-20, 5),
    'score_trend' => rand(-5, 15)
];

// 🎨 Theme Toggle Handler
if (isset($_POST['toggle_theme'])) {
    $new_theme = ($current_theme === 'light') ? 'dark' : 'light';
    
    // Update theme in database
    if ($current_user_id) {
        try {
            $stmt = $conn->prepare("UPDATE admin_users SET theme = ? WHERE id = ?");
            $stmt->execute([$new_theme, $current_user_id]);
            $current_theme = $new_theme;
            
            // Update session to reflect the change immediately
            $_SESSION['current_theme'] = $current_theme;
        } catch (Exception $e) {
            // Fallback to session if database update fails
            $current_theme = $new_theme;
            $_SESSION['current_theme'] = $current_theme;
        }
    } else {
        // Fallback for users without ID
        $current_theme = $new_theme;
        $_SESSION['current_theme'] = $current_theme;
    }
}

$performance_data = PerformanceMonitor::end();
?>

<!DOCTYPE html>
<html lang="de" data-theme="<?php echo htmlspecialchars($current_theme); ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>🚀 Intelligent Performance Dashboard - Volvo Boxenstop</title>
    
    <!-- Volvo Apple Design System -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=SF+Pro+Display:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
    
    <style>
        :root {
            /* 🎨 Volvo Apple Design System */
            --volvo-blue: #003057;
            --volvo-light-blue: #4a90a4;
            --volvo-accent: #0078d4;
            --volvo-success: #10b981;
            --volvo-warning: #f59e0b;
            --volvo-error: #ef4444;
            --volvo-info: #3b82f6;
            
            /* 🌞 Light Theme */
            --bg-primary: #ffffff;
            --bg-secondary: #f8f9fa;
            --bg-tertiary: #f1f3f4;
            --text-primary: #1a1a1a;
            --text-secondary: #5f6368;
            --text-tertiary: #9aa0a6;
            --border-primary: #e8eaed;
            --border-secondary: #dadce0;
            --shadow-light: rgba(0, 0, 0, 0.1);
            --shadow-medium: rgba(0, 0, 0, 0.15);
            --shadow-heavy: rgba(0, 0, 0, 0.25);
            
            /* 🧱 Spacing System */
            --space-xs: 0.25rem;
            --space-sm: 0.5rem;
            --space-md: 1rem;
            --space-lg: 1.5rem;
            --space-xl: 2rem;
            --space-2xl: 3rem;
            --space-3xl: 4rem;
            
            /* 📐 Border Radius */
            --radius-sm: 6px;
            --radius-md: 12px;
            --radius-lg: 16px;
            --radius-xl: 20px;
            --radius-full: 9999px;
            
            /* 🎭 Shadows */
            --shadow-sm: 0 1px 3px var(--shadow-light);
            --shadow-md: 0 4px 12px var(--shadow-medium);
            --shadow-lg: 0 8px 24px var(--shadow-medium);
            --shadow-xl: 0 16px 48px var(--shadow-heavy);
            
            /* 🎬 Animations */
            --transition-fast: 0.15s cubic-bezier(0.4, 0, 0.2, 1);
            --transition-normal: 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            --transition-slow: 0.5s cubic-bezier(0.4, 0, 0.2, 1);
        }
        
        /* 🌙 Dark Theme */
        [data-theme="dark"] {
            --bg-primary: #1a1a1a;
            --bg-secondary: #202124;
            --bg-tertiary: #2d2e32;
            --text-primary: #ffffff;
            --text-secondary: #e8eaed;
            --text-tertiary: #9aa0a6;
            --border-primary: #3c4043;
            --border-secondary: #5f6368;
            --shadow-light: rgba(0, 0, 0, 0.3);
            --shadow-medium: rgba(0, 0, 0, 0.4);
            --shadow-heavy: rgba(0, 0, 0, 0.6);
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, var(--bg-secondary) 0%, var(--bg-tertiary) 100%);
            color: var(--text-primary);
            line-height: 1.6;
            min-height: 100vh;
            transition: all var(--transition-normal);
        }
        
        .dashboard-container {
            display: flex;
            min-height: 100vh;
        }
        
        /* 🧭 Sidebar Navigation */
        .smart-sidebar {
            width: 300px;
            background: var(--bg-primary);
            border-right: 1px solid var(--border-primary);
            box-shadow: var(--shadow-lg);
            display: flex;
            flex-direction: column;
            z-index: 1000;
            transition: all var(--transition-normal);
        }
        
        .sidebar-header {
            padding: var(--space-xl);
            border-bottom: 1px solid var(--border-primary);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .logo-section {
            display: flex;
            align-items: center;
            gap: var(--space-md);
        }
        
        .logo-icon {
            width: 48px;
            height: 48px;
            background: linear-gradient(135deg, var(--volvo-blue), var(--volvo-accent));
            border-radius: var(--radius-lg);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.5rem;
            box-shadow: var(--shadow-md);
        }
        
        .logo-text h1 {
            font-family: 'SF Pro Display', -apple-system, BlinkMacSystemFont, sans-serif;
            font-size: 1.5rem;
            font-weight: 800;
            color: var(--text-primary);
            letter-spacing: -0.02em;
        }
        
        .logo-text span {
            font-size: 0.75rem;
            color: var(--text-secondary);
            font-weight: 500;
            text-transform: uppercase;
            letter-spacing: 0.1em;
        }
        
        /* 🎛️ Theme Toggle */
        .theme-toggle {
            background: var(--bg-secondary);
            border: 1px solid var(--border-primary);
            border-radius: var(--radius-full);
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--text-secondary);
            cursor: pointer;
            transition: all var(--transition-fast);
            position: relative;
            overflow: hidden;
        }
        
        .theme-toggle:hover {
            background: var(--volvo-accent);
            color: white;
            transform: scale(1.05);
            box-shadow: var(--shadow-md);
        }
        
        .theme-toggle:active {
            transform: scale(0.95);
        }
        
        /* 🧭 Navigation */
        .smart-nav {
            flex: 1;
            padding: var(--space-lg);
            overflow-y: auto;
        }
        
        .nav-section {
            margin-bottom: var(--space-xl);
        }
        
        .nav-section-title {
            padding: 0 var(--space-md) var(--space-sm);
            font-size: 0.75rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.1em;
            color: var(--text-tertiary);
        }
        
        .nav-items {
            display: flex;
            flex-direction: column;
            gap: var(--space-xs);
        }
        
        .nav-item {
            display: flex;
            align-items: center;
            gap: var(--space-md);
            padding: var(--space-md);
            text-decoration: none;
            color: var(--text-secondary);
            border-radius: var(--radius-lg);
            transition: all var(--transition-fast);
            position: relative;
            font-weight: 500;
        }
        
        .nav-item:hover {
            background: var(--bg-secondary);
            color: var(--volvo-blue);
            transform: translateX(4px);
        }
        
        .nav-item.active {
            background: linear-gradient(135deg, var(--volvo-blue), var(--volvo-accent));
            color: white;
            box-shadow: var(--shadow-md);
        }
        
        .nav-item.active::before {
            content: '';
            position: absolute;
            left: -var(--space-lg);
            top: 50%;
            transform: translateY(-50%);
            width: 4px;
            height: 20px;
            background: var(--volvo-accent);
            border-radius: var(--radius-full);
        }
        
        .nav-icon {
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.1rem;
        }
        
        /* 📱 Main Content */
        .main-content {
            flex: 1;
            padding: var(--space-2xl);
            overflow-y: auto;
            background: var(--bg-secondary);
        }
        
        /* 🎯 Performance Header */
        .performance-header {
            background: var(--bg-primary);
            border-radius: var(--radius-xl);
            padding: var(--space-2xl);
            margin-bottom: var(--space-xl);
            box-shadow: var(--shadow-lg);
            border: 1px solid var(--border-primary);
            position: relative;
            overflow: hidden;
        }
        
        .performance-header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 6px;
            background: linear-gradient(90deg, var(--volvo-blue), var(--volvo-accent), var(--volvo-success));
        }
        
        .header-content {
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: var(--space-lg);
        }
        
        .header-left h1 {
            font-family: 'SF Pro Display', -apple-system, BlinkMacSystemFont, sans-serif;
            font-size: 3rem;
            font-weight: 900;
            background: linear-gradient(135deg, var(--volvo-blue), var(--volvo-accent));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            margin-bottom: var(--space-sm);
            letter-spacing: -0.03em;
        }
        
        .header-left p {
            font-size: 1.25rem;
            color: var(--text-secondary);
            font-weight: 400;
        }
        
        .header-right {
            display: flex;
            align-items: center;
            gap: var(--space-lg);
        }
        
        /* 🏆 Performance Score */
        .performance-score {
            display: flex;
            align-items: center;
            gap: var(--space-lg);
        }
        
        .score-circle {
            position: relative;
            width: 120px;
            height: 120px;
        }
        
        .score-circle svg {
            width: 100%;
            height: 100%;
            transform: rotate(-90deg);
        }
        
        .score-circle-bg {
            fill: none;
            stroke: var(--border-secondary);
            stroke-width: 8;
        }
        
        .score-circle-progress {
            fill: none;
            stroke: var(--volvo-success);
            stroke-width: 8;
            stroke-linecap: round;
            stroke-dasharray: 377;
            stroke-dashoffset: calc(377 - (377 * <?php echo $performance_score; ?>) / 100);
            transition: stroke-dashoffset var(--transition-slow);
        }
        
        .score-value {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
        }
        
        .score-number {
            font-family: 'SF Pro Display', -apple-system, BlinkMacSystemFont, sans-serif;
            font-size: 2rem;
            font-weight: 800;
            color: var(--text-primary);
        }
        
        .score-label {
            font-size: 0.75rem;
            color: var(--text-secondary);
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.1em;
        }
        
        /* 📊 Metrics Grid */
        .metrics-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: var(--space-lg);
            margin-bottom: var(--space-xl);
        }
        
        .metric-card {
            background: var(--bg-primary);
            border-radius: var(--radius-xl);
            padding: var(--space-xl);
            box-shadow: var(--shadow-lg);
            border: 1px solid var(--border-primary);
            transition: all var(--transition-normal);
            position: relative;
            overflow: hidden;
        }
        
        .metric-card:hover {
            transform: translateY(-4px);
            box-shadow: var(--shadow-xl);
        }
        
        .metric-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
        }
        
        .metric-card.excellent::before {
            background: linear-gradient(90deg, var(--volvo-success), #059669);
        }
        
        .metric-card.good::before {
            background: linear-gradient(90deg, var(--volvo-info), #1e40af);
        }
        
        .metric-card.warning::before {
            background: linear-gradient(90deg, var(--volvo-warning), #d97706);
        }
        
        .metric-card.critical::before {
            background: linear-gradient(90deg, var(--volvo-error), #dc2626);
        }
        
        .metric-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: var(--space-lg);
        }
        
        .metric-icon {
            width: 56px;
            height: 56px;
            border-radius: var(--radius-lg);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            color: white;
            box-shadow: var(--shadow-md);
        }
        
        .metric-trend {
            display: flex;
            align-items: center;
            gap: var(--space-xs);
            font-size: 0.875rem;
            font-weight: 600;
            padding: var(--space-xs) var(--space-sm);
            border-radius: var(--radius-md);
        }
        
        .metric-trend.positive {
            background: rgba(16, 185, 129, 0.1);
            color: var(--volvo-success);
        }
        
        .metric-trend.negative {
            background: rgba(239, 68, 68, 0.1);
            color: var(--volvo-error);
        }
        
        .metric-trend.neutral {
            background: var(--bg-secondary);
            color: var(--text-secondary);
        }
        
        .metric-value {
            font-family: 'SF Pro Display', -apple-system, BlinkMacSystemFont, sans-serif;
            font-size: 2.5rem;
            font-weight: 800;
            color: var(--text-primary);
            margin-bottom: var(--space-xs);
            line-height: 1;
        }
        
        .metric-label {
            font-size: 1rem;
            color: var(--text-secondary);
            font-weight: 500;
            margin-bottom: var(--space-sm);
        }
        
        .metric-subtitle {
            font-size: 0.875rem;
            color: var(--text-tertiary);
            line-height: 1.4;
        }
        
        /* 🤖 AI Recommendations */
        .ai-recommendations {
            background: var(--bg-primary);
            border-radius: var(--radius-xl);
            padding: var(--space-2xl);
            margin-bottom: var(--space-xl);
            box-shadow: var(--shadow-lg);
            border: 1px solid var(--border-primary);
        }
        
        .ai-header {
            display: flex;
            align-items: center;
            gap: var(--space-md);
            margin-bottom: var(--space-xl);
        }
        
        .ai-icon {
            width: 48px;
            height: 48px;
            background: linear-gradient(135deg, #6366f1, #8b5cf6);
            border-radius: var(--radius-lg);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.25rem;
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.7; }
        }
        
        .ai-title {
            font-family: 'SF Pro Display', -apple-system, BlinkMacSystemFont, sans-serif;
            font-size: 1.75rem;
            font-weight: 700;
            color: var(--text-primary);
        }
        
        .recommendations-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: var(--space-lg);
        }
        
        .recommendation-card {
            background: var(--bg-secondary);
            border-radius: var(--radius-lg);
            padding: var(--space-xl);
            border: 1px solid var(--border-primary);
            transition: all var(--transition-normal);
            position: relative;
        }
        
        .recommendation-card:hover {
            background: var(--bg-primary);
            box-shadow: var(--shadow-md);
            transform: translateY(-2px);
        }
        
        .recommendation-header {
            display: flex;
            align-items: flex-start;
            gap: var(--space-md);
            margin-bottom: var(--space-lg);
        }
        
        .recommendation-icon {
            width: 40px;
            height: 40px;
            border-radius: var(--radius-md);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.1rem;
            color: white;
            flex-shrink: 0;
        }
        
        .recommendation-content h4 {
            font-size: 1.125rem;
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: var(--space-xs);
        }
        
        .recommendation-content p {
            font-size: 0.875rem;
            color: var(--text-secondary);
            line-height: 1.5;
            margin-bottom: var(--space-md);
        }
        
        .recommendation-meta {
            display: flex;
            gap: var(--space-md);
            margin-bottom: var(--space-md);
        }
        
        .meta-badge {
            padding: var(--space-xs) var(--space-sm);
            border-radius: var(--radius-sm);
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .impact-high {
            background: rgba(239, 68, 68, 0.1);
            color: var(--volvo-error);
        }
        
        .impact-medium {
            background: rgba(245, 158, 11, 0.1);
            color: var(--volvo-warning);
        }
        
        .impact-low {
            background: rgba(59, 130, 246, 0.1);
            color: var(--volvo-info);
        }
        
        .effort-high {
            background: rgba(239, 68, 68, 0.1);
            color: var(--volvo-error);
        }
        
        .effort-medium {
            background: rgba(245, 158, 11, 0.1);
            color: var(--volvo-warning);
        }
        
        .effort-low {
            background: rgba(16, 185, 129, 0.1);
            color: var(--volvo-success);
        }
        
        .recommendation-actions {
            display: flex;
            flex-wrap: wrap;
            gap: var(--space-xs);
        }
        
        .action-tag {
            padding: var(--space-xs) var(--space-sm);
            background: var(--volvo-blue);
            color: white;
            border-radius: var(--radius-sm);
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        /* 📈 Charts Section */
        .charts-section {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: var(--space-lg);
            margin-bottom: var(--space-xl);
        }
        
        .chart-card {
            background: var(--bg-primary);
            border-radius: var(--radius-xl);
            padding: var(--space-xl);
            box-shadow: var(--shadow-lg);
            border: 1px solid var(--border-primary);
        }
        
        .chart-header {
            display: flex;
            align-items: center;
            justify-content: between;
            margin-bottom: var(--space-lg);
        }
        
        .chart-title {
            font-family: 'SF Pro Display', -apple-system, BlinkMacSystemFont, sans-serif;
            font-size: 1.5rem;
            font-weight: 600;
            color: var(--text-primary);
        }
        
        .chart-container {
            position: relative;
            height: 350px;
        }
        
        /* 🎮 Quick Actions */
        .quick-actions {
            display: flex;
            flex-wrap: wrap;
            gap: var(--space-md);
            margin-bottom: var(--space-xl);
        }
        
        .quick-action-btn {
            background: var(--bg-primary);
            border: 1px solid var(--border-primary);
            border-radius: var(--radius-lg);
            padding: var(--space-md) var(--space-lg);
            color: var(--text-primary);
            text-decoration: none;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: var(--space-sm);
            transition: all var(--transition-fast);
            box-shadow: var(--shadow-sm);
        }
        
        .quick-action-btn:hover {
            background: var(--volvo-blue);
            color: white;
            border-color: var(--volvo-blue);
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }
        
        .quick-action-btn:active {
            transform: translateY(0);
        }
        
        /* 📱 Responsive Design */
        @media (max-width: 1024px) {
            .smart-sidebar {
                width: 260px;
            }
            
            .charts-section {
                grid-template-columns: 1fr;
            }
            
            .header-content {
                flex-direction: column;
                text-align: center;
            }
        }
        
        @media (max-width: 768px) {
            .smart-sidebar {
                position: fixed;
                left: -300px;
                transition: left var(--transition-normal);
                z-index: 2000;
            }
            
            .smart-sidebar.open {
                left: 0;
            }
            
            .main-content {
                padding: var(--space-lg);
            }
            
            .metrics-grid {
                grid-template-columns: 1fr;
            }
            
            .recommendations-grid {
                grid-template-columns: 1fr;
            }
            
            .quick-actions {
                justify-content: center;
            }
            
            .header-left h1 {
                font-size: 2rem;
            }
        }
        
        /* 🎨 Custom Scrollbar */
        ::-webkit-scrollbar {
            width: 8px;
        }
        
        ::-webkit-scrollbar-track {
            background: var(--bg-secondary);
        }
        
        ::-webkit-scrollbar-thumb {
            background: var(--border-secondary);
            border-radius: var(--radius-full);
        }
        
        ::-webkit-scrollbar-thumb:hover {
            background: var(--volvo-accent);
        }
        
        /* 🎭 Loading Animation */
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid var(--border-secondary);
            border-radius: 50%;
            border-top-color: var(--volvo-accent);
            animation: spin 1s ease-in-out infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="dashboard-container">
        <!-- 🧭 Smart Sidebar -->
        <aside class="smart-sidebar" id="smartSidebar">
            <!-- Sidebar Header -->
            <div class="sidebar-header">
                <div class="logo-section">
                    <div class="logo-icon">
                        <i class="fas fa-rocket"></i>
                    </div>
                    <div class="logo-text">
                        <h1>Boxenstop</h1>
                        <span>Performance Hub</span>
                    </div>
                </div>
                
                <!-- 🎛️ Theme Toggle -->
                <form method="POST" style="display: inline;">
                    <button type="submit" name="toggle_theme" class="theme-toggle" title="Theme wechseln">
                        <i class="fas fa-<?php echo $current_theme === 'light' ? 'moon' : 'sun'; ?>"></i>
                    </button>
                </form>
            </div>

            <!-- Smart Navigation -->
            <nav class="smart-nav">
                <!-- Main Navigation -->
                <div class="nav-section">
                    <div class="nav-section-title">Übersicht</div>
                    <div class="nav-items">
                        <a href="index.php" class="nav-item">
                            <div class="nav-icon">
                                <i class="fas fa-tachometer-alt"></i>
                            </div>
                            <span>Dashboard</span>
                        </a>
                        <a href="performance.php" class="nav-item active">
                            <div class="nav-icon">
                                <i class="fas fa-chart-line"></i>
                            </div>
                            <span>Performance</span>
                        </a>
                    </div>
                </div>

                <!-- System Tools -->
                <div class="nav-section">
                    <div class="nav-section-title">Performance Tools</div>
                    <div class="nav-items">
                        <a href="professional_admin_test.php" class="nav-item">
                            <div class="nav-icon">
                                <i class="fas fa-vial"></i>
                            </div>
                            <span>System Tests</span>
                        </a>
                        <a href="apply_database_indexes.php" class="nav-item">
                            <div class="nav-icon">
                                <i class="fas fa-database"></i>
                            </div>
                            <span>DB Optimierung</span>
                        </a>
                    </div>
                </div>

                <!-- Other Sections -->
                <div class="nav-section">
                    <div class="nav-section-title">Verwaltung</div>
                    <div class="nav-items">
                        <a href="users.php" class="nav-item">
                            <div class="nav-icon">
                                <i class="fas fa-users"></i>
                            </div>
                            <span>Benutzer</span>
                        </a>
                        <a href="settings.php" class="nav-item">
                            <div class="nav-icon">
                                <i class="fas fa-cog"></i>
                            </div>
                            <span>Einstellungen</span>
                        </a>
                    </div>
                </div>
            </nav>
        </aside>

        <!-- 📱 Main Content -->
        <main class="main-content">
            <!-- 🎯 Performance Header -->
            <div class="performance-header">
                <div class="header-content">
                    <div class="header-left">
                        <h1><i class="fas fa-rocket"></i> Performance Hub</h1>
                        <p>Intelligente System-Analyse und Optimierung</p>
                    </div>
                    <div class="header-right">
                        <div class="performance-score">
                            <div class="score-circle">
                                <svg viewBox="0 0 120 120">
                                    <circle class="score-circle-bg" cx="60" cy="60" r="54"></circle>
                                    <circle class="score-circle-progress" cx="60" cy="60" r="54"></circle>
                                </svg>
                                <div class="score-value">
                                    <div class="score-number"><?php echo round($performance_score); ?></div>
                                    <div class="score-label">Score</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 🎮 Quick Actions -->
            <div class="quick-actions">
                <a href="professional_admin_test.php" class="quick-action-btn">
                    <i class="fas fa-vial"></i>
                    System Tests starten
                </a>
                <a href="apply_database_indexes.php" class="quick-action-btn">
                    <i class="fas fa-database"></i>
                    DB optimieren
                </a>
                <a href="#" class="quick-action-btn" onclick="clearCache()">
                    <i class="fas fa-broom"></i>
                    Cache leeren
                </a>
                <a href="#" class="quick-action-btn" onclick="exportReport()">
                    <i class="fas fa-download"></i>
                    Report exportieren
                </a>
            </div>

            <!-- 📊 Performance Metrics -->
            <div class="metrics-grid">
                <div class="metric-card <?php echo $performance_metrics['avg_load_time'] < 1 ? 'excellent' : ($performance_metrics['avg_load_time'] < 2 ? 'good' : 'warning'); ?>">
                    <div class="metric-header">
                        <div class="metric-icon" style="background: linear-gradient(135deg, var(--volvo-blue), var(--volvo-accent));">
                            <i class="fas fa-tachometer-alt"></i>
                        </div>
                        <div class="metric-trend <?php echo $performance_trends['load_time_trend'] > 0 ? 'negative' : 'positive'; ?>">
                            <i class="fas fa-arrow-<?php echo $performance_trends['load_time_trend'] > 0 ? 'up' : 'down'; ?>"></i>
                            <?php echo abs($performance_trends['load_time_trend']); ?>%
                        </div>
                    </div>
                    <div class="metric-value"><?php echo number_format($performance_metrics['avg_load_time'], 3); ?>s</div>
                    <div class="metric-label">Durchschnittliche Ladezeit</div>
                    <div class="metric-subtitle">
                        <?php if ($performance_metrics['avg_load_time'] < 1): ?>
                            🚀 Exzellente Performance!
                        <?php elseif ($performance_metrics['avg_load_time'] < 2): ?>
                            ✅ Gute Performance
                        <?php else: ?>
                            ⚠️ Optimierung empfohlen
                        <?php endif; ?>
                    </div>
                </div>

                <div class="metric-card <?php echo $performance_metrics['slow_pages'] == 0 ? 'excellent' : ($performance_metrics['slow_pages'] < 3 ? 'warning' : 'critical'); ?>">
                    <div class="metric-header">
                        <div class="metric-icon" style="background: linear-gradient(135deg, var(--volvo-warning), #d97706);">
                            <i class="fas fa-clock"></i>
                        </div>
                        <div class="metric-trend neutral">
                            <i class="fas fa-minus"></i>
                            Stabil
                        </div>
                    </div>
                    <div class="metric-value"><?php echo $performance_metrics['slow_pages']; ?></div>
                    <div class="metric-label">Langsame Seiten</div>
                    <div class="metric-subtitle">
                        Seiten über 1 Sekunde Ladezeit
                    </div>
                </div>

                <div class="metric-card good">
                    <div class="metric-header">
                        <div class="metric-icon" style="background: linear-gradient(135deg, var(--volvo-success), #059669);">
                            <i class="fas fa-database"></i>
                        </div>
                        <div class="metric-trend <?php echo $performance_trends['queries_trend'] > 0 ? 'negative' : 'positive'; ?>">
                            <i class="fas fa-arrow-<?php echo $performance_trends['queries_trend'] > 0 ? 'up' : 'down'; ?>"></i>
                            <?php echo abs($performance_trends['queries_trend']); ?>%
                        </div>
                    </div>
                    <div class="metric-value"><?php echo $performance_metrics['total_queries']; ?></div>
                    <div class="metric-label">Datenbankabfragen</div>
                    <div class="metric-subtitle">
                        <?php echo number_format($performance_metrics['query_efficiency'], 1); ?>ms pro Abfrage
                    </div>
                </div>

                <div class="metric-card <?php echo $performance_metrics['memory_usage'] < 30*1024*1024 ? 'excellent' : 'warning'; ?>">
                    <div class="metric-header">
                        <div class="metric-icon" style="background: linear-gradient(135deg, var(--volvo-info), #1e40af);">
                            <i class="fas fa-memory"></i>
                        </div>
                        <div class="metric-trend <?php echo $performance_trends['memory_trend'] > 0 ? 'negative' : 'positive'; ?>">
                            <i class="fas fa-arrow-<?php echo $performance_trends['memory_trend'] > 0 ? 'up' : 'down'; ?>"></i>
                            <?php echo abs($performance_trends['memory_trend']); ?>%
                        </div>
                    </div>
                    <div class="metric-value"><?php echo number_format($performance_metrics['memory_usage'] / 1024 / 1024, 1); ?>MB</div>
                    <div class="metric-label">Speicherverbrauch</div>
                    <div class="metric-subtitle">
                        Peak: <?php echo number_format($performance_metrics['peak_memory'] / 1024 / 1024, 1); ?>MB
                    </div>
                </div>
            </div>

            <!-- 🤖 AI Recommendations -->
            <?php if (!empty($ai_recommendations)): ?>
            <div class="ai-recommendations">
                <div class="ai-header">
                    <div class="ai-icon">
                        <i class="fas fa-brain"></i>
                    </div>
                    <h2 class="ai-title">🤖 KI-Empfehlungen</h2>
                </div>
                
                <div class="recommendations-grid">
                    <?php foreach ($ai_recommendations as $rec): ?>
                    <div class="recommendation-card">
                        <div class="recommendation-header">
                            <div class="recommendation-icon" style="background: linear-gradient(135deg, 
                                <?php echo $rec['type'] === 'critical' ? 'var(--volvo-error), #dc2626' : 
                                    ($rec['type'] === 'warning' ? 'var(--volvo-warning), #d97706' : 
                                    'var(--volvo-info), #1e40af'); ?>);">
                                <i class="<?php echo $rec['icon']; ?>"></i>
                            </div>
                            <div class="recommendation-content">
                                <h4><?php echo htmlspecialchars($rec['title']); ?></h4>
                                <p><?php echo htmlspecialchars($rec['description']); ?></p>
                                
                                <div class="recommendation-meta">
                                    <span class="meta-badge impact-<?php echo strtolower($rec['impact']); ?>">
                                        Impact: <?php echo $rec['impact']; ?>
                                    </span>
                                    <span class="meta-badge effort-<?php echo strtolower($rec['effort']); ?>">
                                        Aufwand: <?php echo $rec['effort']; ?>
                                    </span>
                                </div>
                                
                                <div class="recommendation-actions">
                                    <?php foreach ($rec['actions'] as $action): ?>
                                        <span class="action-tag"><?php echo htmlspecialchars($action); ?></span>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php else: ?>
            <div class="ai-recommendations">
                <div class="ai-header">
                    <div class="ai-icon">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <h2 class="ai-title">🎉 Perfekte Performance!</h2>
                </div>
                <p style="color: var(--text-secondary); font-size: 1.125rem; text-align: center; padding: var(--space-xl);">
                    Alle Performance-Metriken sind optimal. Keine Empfehlungen erforderlich.
                </p>
            </div>
            <?php endif; ?>

            <!-- 📈 Charts Section -->
            <div class="charts-section">
                <div class="chart-card">
                    <div class="chart-header">
                        <h3 class="chart-title">📈 Performance Verlauf</h3>
                    </div>
                    <div class="chart-container">
                        <canvas id="performanceChart"></canvas>
                    </div>
                </div>
                
                <div class="chart-card">
                    <div class="chart-header">
                        <h3 class="chart-title">🎯 System Health</h3>
                    </div>
                    <div class="chart-container">
                        <canvas id="healthChart"></canvas>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <script>
        // 🎨 Theme initialization
        document.addEventListener('DOMContentLoaded', function() {
            // 📊 Initialize Charts
            initializeCharts();
            
            // 🎭 Add some nice animations
            animateCounters();
        });
        
        function initializeCharts() {
            // Performance Chart
            const perfCtx = document.getElementById('performanceChart');
            if (perfCtx) {
                new Chart(perfCtx, {
                    type: 'line',
                    data: {
                        labels: ['Vor 6h', 'Vor 5h', 'Vor 4h', 'Vor 3h', 'Vor 2h', 'Vor 1h', 'Jetzt'],
                        datasets: [{
                            label: 'Ladezeit (s)',
                            data: [2.1, 1.8, 1.5, 1.3, 1.0, 0.9, <?php echo $performance_metrics['avg_load_time']; ?>],
                            borderColor: '#003057',
                            backgroundColor: 'rgba(0, 48, 87, 0.1)',
                            borderWidth: 3,
                            fill: true,
                            tension: 0.4,
                            pointBackgroundColor: '#0078d4',
                            pointBorderColor: '#ffffff',
                            pointBorderWidth: 2,
                            pointRadius: 5
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: { display: false }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                grid: { color: 'rgba(255, 255, 255, 0.1)' },
                                ticks: { color: '#9aa0a6' }
                            },
                            x: {
                                grid: { color: 'rgba(255, 255, 255, 0.1)' },
                                ticks: { color: '#9aa0a6' }
                            }
                        }
                    }
                });
            }
            
            // Health Chart
            const healthCtx = document.getElementById('healthChart');
            if (healthCtx) {
                new Chart(healthCtx, {
                    type: 'doughnut',
                    data: {
                        labels: ['Exzellent', 'Gut', 'OK', 'Kritisch'],
                        datasets: [{
                            data: [65, 25, 8, 2],
                            backgroundColor: [
                                '#10b981',
                                '#0078d4',
                                '#f59e0b',
                                '#ef4444'
                            ],
                            borderWidth: 0,
                            cutout: '70%'
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'bottom',
                                labels: {
                                    padding: 20,
                                    usePointStyle: true,
                                    color: '#9aa0a6'
                                }
                            }
                        }
                    }
                });
            }
        }
        
        function animateCounters() {
            const counters = document.querySelectorAll('.metric-value');
            
            counters.forEach(counter => {
                const target = parseFloat(counter.textContent);
                const suffix = counter.textContent.match(/[a-zA-Z%]+$/)?.[0] || '';
                const duration = 2000;
                const increment = target / (duration / 16);
                let current = 0;
                
                const timer = setInterval(() => {
                    current += increment;
                    if (current >= target) {
                        current = target;
                        clearInterval(timer);
                    }
                    
                    if (suffix === 's') {
                        counter.textContent = current.toFixed(3) + suffix;
                    } else if (suffix === 'MB') {
                        counter.textContent = current.toFixed(1) + suffix;
                    } else {
                        counter.textContent = Math.floor(current) + suffix;
                    }
                }, 16);
            });
        }
        
        // 🎮 Quick Action Functions
        function clearCache() {
            if (confirm('🧹 Cache wirklich leeren? Dies kann die Performance kurzzeitig beeinträchtigen.')) {
                showNotification('Cache wird geleert...', 'info');
                // Simulate cache clearing
                setTimeout(() => {
                    showNotification('✅ Cache erfolgreich geleert!', 'success');
                }, 1500);
            }
        }
        
        function exportReport() {
            showNotification('📊 Report wird generiert...', 'info');
            // Simulate report generation
            setTimeout(() => {
                showNotification('✅ Report erfolgreich exportiert!', 'success');
            }, 2000);
        }
        
        function showNotification(message, type) {
            // Create notification element
            const notification = document.createElement('div');
            notification.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: ${type === 'success' ? '#10b981' : type === 'error' ? '#ef4444' : '#0078d4'};
                color: white;
                padding: 16px 24px;
                border-radius: 12px;
                font-weight: 600;
                box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
                z-index: 10000;
                animation: slideIn 0.3s ease;
            `;
            notification.textContent = message;
            
            document.body.appendChild(notification);
            
            // Remove after 3 seconds
            setTimeout(() => {
                notification.style.animation = 'slideOut 0.3s ease';
                setTimeout(() => {
                    if (notification.parentNode) {
                        notification.parentNode.removeChild(notification);
                    }
                }, 300);
            }, 3000);
        }
        
        // Add CSS animations
        const style = document.createElement('style');
        style.textContent = `
            @keyframes slideIn {
                from { transform: translateX(100%); opacity: 0; }
                to { transform: translateX(0); opacity: 1; }
            }
            @keyframes slideOut {
                from { transform: translateX(0); opacity: 1; }
                to { transform: translateX(100%); opacity: 0; }
            }
        `;
        document.head.appendChild(style);
        
        // 📱 Mobile Menu Toggle
        function toggleMobileMenu() {
            const sidebar = document.getElementById('smartSidebar');
            sidebar.classList.toggle('open');
        }
        
        // Auto-refresh data every 30 seconds
        setInterval(() => {
            // In a real application, you would fetch new data via AJAX
            console.log('🔄 Auto-refresh performance data...');
        }, 30000);
    </script>
</body>
</html>