<?php
/**
 * Professional Performance Testing Suite - Volvo Apple Design
 * Admin-only comprehensive system analysis
 */

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

// Enhanced admin validation
if (!isset($_SESSION["admin_logged_in"]) || !$_SESSION["admin_logged_in"]) {
    header("Location: login.php");
    exit;
}

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

// Verify admin role in database
$current_user_id = $_SESSION["admin_user_id"] ?? null;
if (!$current_user_id) {
    header("Location: login.php");
    exit;
}

$user_data = $db->getUserData($current_user_id);
if (!$user_data || $user_data["role"] !== "admin") {
    die("<div style=\"font-family: Inter, sans-serif; text-align: center; padding: 50px; color: #dc3545;\">
        <h2> Zugriff verweigert</h2>
        <p>Nur Administratoren haben Zugriff auf das Performance Testing Suite.</p>
        <a href=\"index.php\" style=\"color: #007bff;\"> Zurück zum Dashboard</a>
    </div>");
}

$current_user_name = $user_data["full_name"] ?? $user_data["username"] ?? "Admin";
$current_theme = $user_data["theme"] ?? "light";

// Comprehensive Performance Analysis
$stats = PerformanceMonitor::getStats();
$avg_load_time = 0;
$slow_pages = 0;
$total_queries = 0;
$performance_score = 0;

if (!empty($stats)) {
    $load_times = array_column($stats, "total_time");
    $avg_load_time = array_sum($load_times) / count($load_times);
    $slow_pages = count(array_filter($load_times, function($time) { return $time > 1.0; }));
    $total_queries = array_sum(array_column($stats, "query_count"));
    
    // Calculate performance score (0-100)
    $performance_score = max(0, 100 - ($avg_load_time * 50) - ($slow_pages * 10));
}

// Database Performance Tests
$db_tests = [];
$test_start = microtime(true);

// Test 1: Simple COUNT
$start = microtime(true);
$db_tests["simple_count"] = $db->fetchColumn("SELECT COUNT(*) FROM events WHERE is_active = 1");
$db_tests["simple_count_time"] = (microtime(true) - $start) * 1000;

// Test 2: Complex JOIN
$start = microtime(true);
$db_tests["complex_join"] = $db->fetchAll("
    SELECT a.*, e.name as event_name, ah.name as autohaus_name
    FROM appointments a
    JOIN events e ON a.event_id = e.id
    LEFT JOIN autohaus ah ON a.autohaus_id = ah.id
    ORDER BY a.created_at DESC
    LIMIT 10
");
$db_tests["complex_join_time"] = (microtime(true) - $start) * 1000;

// Test 3: Dashboard Stats (Cached)
$start = microtime(true);
$db_tests["dashboard_stats"] = $db->getDashboardStats();
$db_tests["dashboard_stats_time"] = (microtime(true) - $start) * 1000;

// Test 4: User Data (Cached)
$start = microtime(true);
$db_tests["user_data"] = $db->getUserData($current_user_id);
$db_tests["user_data_time"] = (microtime(true) - $start) * 1000;

$total_test_time = microtime(true) - $test_start;

// System Information
$system_info = [
    "php_version" => PHP_VERSION,
    "memory_limit" => ini_get("memory_limit"),
    "max_execution_time" => ini_get("max_execution_time"),
    "database_queries" => $db->getQueryCount(),
    "cache_hits" => count($db->cache ?? []),
    "server_time" => date("Y-m-d H:i:s")
];

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