<?php
/**
 * System-Diagnose Tool
 * Zeigt PHP-Konfiguration, Server-Info und Datenbank-Status
 */

require_once __DIR__ . '/../db.php';

// Nur für eingeloggte Admins
if (!isLoggedIn() || !isAdmin()) {
    header('Location: ../login.php');
    exit;
}

$pageTitle = 'System-Diagnose';
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - Wertsachen Inventar</title>
    <link rel="stylesheet" href="../css/<?php echo $_SESSION['theme'] ?? 'cloud'; ?>.css">
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }
        .container { max-width: 1200px; margin: 0 auto; background: white; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        h1 { color: #2c3e50; border-bottom: 3px solid #3498db; padding-bottom: 10px; }
        h2 { color: #34495e; margin-top: 30px; border-left: 4px solid #3498db; padding-left: 15px; }
        .section { margin: 20px 0; padding: 20px; background: #f8f9fa; border-radius: 5px; }
        .info-table { width: 100%; border-collapse: collapse; margin: 15px 0; }
        .info-table td { padding: 10px; border: 1px solid #ddd; }
        .info-table td:first-child { font-weight: bold; background: #ecf0f1; width: 250px; }
        .status-ok { color: #27ae60; font-weight: bold; }
        .status-warning { color: #f39c12; font-weight: bold; }
        .status-error { color: #e74c3c; font-weight: bold; }
        .back-link { display: inline-block; margin-bottom: 20px; padding: 10px 20px; background: #3498db; color: white; text-decoration: none; border-radius: 5px; }
        .back-link:hover { background: #2980b9; }
        pre { background: #2c3e50; color: #ecf0f1; padding: 15px; border-radius: 5px; overflow-x: auto; }
    </style>
</head>
<body>
    <div class="container">
        <a href="../backend/index.php" class="back-link">← Zurück zum Backend</a>
        
        <h1>🔧 System-Diagnose</h1>
        <p>Generiert am: <strong><?php echo date('d.m.Y H:i:s'); ?></strong></p>
        
        <!-- PHP Information -->
        <div class="section">
            <h2>📋 PHP Information</h2>
            <table class="info-table">
                <tr>
                    <td>PHP Version</td>
                    <td><?php echo phpversion(); ?></td>
                </tr>
                <tr>
                    <td>Server Software</td>
                    <td><?php echo $_SERVER['SERVER_SOFTWARE'] ?? 'Unbekannt'; ?></td>
                </tr>
                <tr>
                    <td>Document Root</td>
                    <td><?php echo $_SERVER['DOCUMENT_ROOT'] ?? 'Unbekannt'; ?></td>
                </tr>
                <tr>
                    <td>Script Filename</td>
                    <td><?php echo __FILE__; ?></td>
                </tr>
                <tr>
                    <td>Memory Limit</td>
                    <td><?php echo ini_get('memory_limit'); ?></td>
                </tr>
                <tr>
                    <td>Max Execution Time</td>
                    <td><?php echo ini_get('max_execution_time'); ?> Sekunden</td>
                </tr>
                <tr>
                    <td>Upload Max Filesize</td>
                    <td><?php echo ini_get('upload_max_filesize'); ?></td>
                </tr>
                <tr>
                    <td>Post Max Size</td>
                    <td><?php echo ini_get('post_max_size'); ?></td>
                </tr>
            </table>
        </div>
        
        <!-- Datenbank Status -->
        <div class="section">
            <h2>🗄️ Datenbank Status</h2>
            <table class="info-table">
                <?php
                try {
                    $dbVersion = $pdo->query("SELECT VERSION()")->fetchColumn();
                    echo "<tr><td>MySQL Version</td><td class='status-ok'>✓ $dbVersion</td></tr>";
                    
                    $dbSize = $pdo->query("SELECT 
                        ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) as size_mb 
                        FROM information_schema.TABLES 
                        WHERE table_schema = DATABASE()")->fetchColumn();
                    echo "<tr><td>Datenbank Größe</td><td>$dbSize MB</td></tr>";
                    
                    $tables = [
                        'users' => 'Benutzer',
                        'wertsachen' => 'Gegenstände',
                        'kategorien' => 'Kategorien',
                        'orte' => 'Orte',
                        'activity_log' => 'Aktivitäten',
                        'login_attempts' => 'Login-Versuche'
                    ];
                    
                    foreach ($tables as $table => $label) {
                        try {
                            $count = $pdo->query("SELECT COUNT(*) FROM $table")->fetchColumn();
                            echo "<tr><td>$label ($table)</td><td class='status-ok'>✓ $count Einträge</td></tr>";
                        } catch (Exception $e) {
                            echo "<tr><td>$label ($table)</td><td class='status-error'>✗ Fehler: {$e->getMessage()}</td></tr>";
                        }
                    }
                } catch (Exception $e) {
                    echo "<tr><td colspan='2' class='status-error'>Datenbankfehler: " . htmlspecialchars($e->getMessage()) . "</td></tr>";
                }
                ?>
            </table>
        </div>
        
        <!-- PHP Extensions -->
        <div class="section">
            <h2>🔌 PHP Extensions</h2>
            <table class="info-table">
                <?php
                $required_extensions = [
                    'pdo' => 'PDO',
                    'pdo_mysql' => 'PDO MySQL',
                    'gd' => 'GD (Bilder)',
                    'mbstring' => 'Multibyte String',
                    'json' => 'JSON',
                    'session' => 'Session',
                    'fileinfo' => 'FileInfo'
                ];
                
                foreach ($required_extensions as $ext => $name) {
                    $loaded = extension_loaded($ext);
                    $status = $loaded ? "<span class='status-ok'>✓ Geladen</span>" : "<span class='status-error'>✗ Nicht verfügbar</span>";
                    echo "<tr><td>$name</td><td>$status</td></tr>";
                }
                ?>
            </table>
        </div>
        
        <!-- Dateisystem -->
        <div class="section">
            <h2>📁 Dateisystem</h2>
            <table class="info-table">
                <?php
                $dirs = [
                    '../upload' => 'Upload-Verzeichnis',
                    '../css' => 'CSS-Verzeichnis',
                    '../js' => 'JavaScript-Verzeichnis',
                    '../backend' => 'Backend-Verzeichnis'
                ];
                
                foreach ($dirs as $dir => $name) {
                    $path = realpath(__DIR__ . '/' . $dir);
                    if ($path && is_dir($path)) {
                        $writable = is_writable($path);
                        $status = $writable ? "<span class='status-ok'>✓ Beschreibbar</span>" : "<span class='status-warning'>⚠ Nur lesbar</span>";
                        echo "<tr><td>$name</td><td>$status ($path)</td></tr>";
                    } else {
                        echo "<tr><td>$name</td><td class='status-error'>✗ Nicht gefunden</td></tr>";
                    }
                }
                
                // Upload-Verzeichnis Größe
                $uploadsPath = realpath(__DIR__ . '/../upload');
                if ($uploadsPath) {
                    $size = 0;
                    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($uploadsPath));
                    foreach ($files as $file) {
                        if ($file->isFile()) {
                            $size += $file->getSize();
                        }
                    }
                    $sizeMB = round($size / 1024 / 1024, 2);
                    echo "<tr><td>Upload-Verzeichnis Größe</td><td>$sizeMB MB</td></tr>";
                }
                ?>
            </table>
        </div>
        
        <!-- Session Information -->
        <div class="section">
            <h2>🔐 Session Information</h2>
            <table class="info-table">
                <tr>
                    <td>Session ID</td>
                    <td><?php echo session_id(); ?></td>
                </tr>
                <tr>
                    <td>Session Name</td>
                    <td><?php echo session_name(); ?></td>
                </tr>
                <tr>
                    <td>Session Status</td>
                    <td><?php echo session_status() === PHP_SESSION_ACTIVE ? '<span class="status-ok">✓ Aktiv</span>' : '<span class="status-error">✗ Inaktiv</span>'; ?></td>
                </tr>
                <tr>
                    <td>Angemeldeter Benutzer</td>
                    <td><?php echo $_SESSION['username'] ?? 'Nicht angemeldet'; ?></td>
                </tr>
                <tr>
                    <td>Benutzer-Rolle</td>
                    <td><?php echo $_SESSION['role'] ?? 'Unbekannt'; ?></td>
                </tr>
            </table>
        </div>
        
        <!-- phpinfo() -->
        <div class="section">
            <h2>ℹ️ Vollständige PHP-Konfiguration</h2>
            <p>Für detaillierte PHP-Informationen siehe unten:</p>
            <details>
                <summary style="cursor: pointer; padding: 10px; background: #3498db; color: white; border-radius: 5px; margin: 10px 0;">
                    <strong>▶ phpinfo() anzeigen</strong>
                </summary>
                <div style="margin-top: 20px;">
                    <?php 
                    ob_start();
                    phpinfo();
                    $phpinfo = ob_get_clean();
                    
                    // Entferne HTML-Wrapper
                    $phpinfo = preg_replace('%^.*<body>(.*)</body>.*$%ms', '$1', $phpinfo);
                    echo $phpinfo;
                    ?>
                </div>
            </details>
        </div>
        
    </div>
</body>
</html>
