<?php
/**
 * Admin Profil-Verwaltung
 * Professionelle Benutzerprofil-Verwaltung mit erweiterten Sicherheits- und UX-Features
 */

session_start();
require_once '../config/database.php';
require_once '../includes/security.php';
require_once '../includes/validation.php';
require_once '../includes/audit_logger.php';

// Sicherheitsprüfungen
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$current_user_id = $_SESSION['admin_user_id'] ?? null;
if (!$current_user_id) {
    header('Location: login.php');
    exit;
}

// CSRF Token generieren
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$db = new Database();
$conn = $db->getConnection();

// Fehlerbehandlung
$error_message = '';
$success_message = '';
$validation_errors = [];

// Formular-Verarbeitung mit erweiterten Sicherheits- und Validierungsfunktionen
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // CSRF Token validieren
        if (!SecurityManager::validateCSRFToken($_POST['csrf_token'] ?? '')) {
            throw new Exception('Ungültiger CSRF Token');
        }
        
        // Rate Limiting prüfen
        if (!SecurityManager::checkRateLimit('profile_update', 10, 300)) {
            throw new Exception('Zu viele Anfragen. Bitte warten Sie einen Moment.');
        }
        
        $audit_logger = new AuditLogger($conn);
        
        if (isset($_POST['action']) && $_POST['action'] === 'update_profile') {
            // Input sanitization
            $profile_data = [
                'admin_name' => SecurityManager::sanitizeInput($_POST['admin_name'] ?? ''),
                'admin_email' => SecurityManager::sanitizeInput($_POST['admin_email'] ?? '', 'email'),
                'admin_phone' => SecurityManager::sanitizeInput($_POST['admin_phone'] ?? ''),
                'admin_position' => SecurityManager::sanitizeInput($_POST['admin_position'] ?? ''),
                'admin_department' => SecurityManager::sanitizeInput($_POST['admin_department'] ?? ''),
                'admin_bio' => SecurityManager::sanitizeInput($_POST['admin_bio'] ?? ''),
                'admin_language' => SecurityManager::sanitizeInput($_POST['admin_language'] ?? 'de'),
                'admin_timezone' => SecurityManager::sanitizeInput($_POST['admin_timezone'] ?? 'Europe/Berlin'),
                'admin_notifications' => SecurityManager::sanitizeInput($_POST['admin_notifications'] ?? 'all'),
                'admin_theme' => SecurityManager::sanitizeInput($_POST['admin_theme'] ?? 'light')
            ];
            
            // Validierung
            $validation_errors = ValidationManager::validateProfileData($profile_data);
            
            // E-Mail-Eindeutigkeit prüfen
            if (!ValidationManager::isEmailUnique($profile_data['admin_email'], $current_user_id, $conn)) {
                $validation_errors['admin_email'] = 'Diese E-Mail-Adresse wird bereits verwendet';
            }
            
            if (!empty($validation_errors)) {
                $validation_errors = $validation_errors;
            } else {
                // Transaktion starten
                $conn->beginTransaction();
                
                try {
                    // Aktuelle Daten für Audit-Log abrufen
                    $stmt = $conn->prepare("SELECT * FROM admin_users WHERE id = ?");
                    $stmt->execute([$current_user_id]);
                    $old_user_data = $stmt->fetch(PDO::FETCH_ASSOC);
                    
                    // Admin-Users Tabelle aktualisieren
                    $stmt = $conn->prepare("
                        UPDATE admin_users 
                        SET full_name = ?, email = ?, department = ?, phone = ?, position = ?, 
                            bio = ?, language = ?, timezone = ?, notifications = ?, theme = ?, updated_at = NOW()
                        WHERE id = ?
                    ");
                    $stmt->execute([
                        $profile_data['admin_name'],
                        $profile_data['admin_email'],
                        $profile_data['admin_department'],
                        $profile_data['admin_phone'],
                        $profile_data['admin_position'],
                        $profile_data['admin_bio'],
                        $profile_data['admin_language'],
                        $profile_data['admin_timezone'],
                        $profile_data['admin_notifications'],
                        $profile_data['admin_theme'],
                        $current_user_id
                    ]);
                    
                    // Avatar-Upload verarbeiten
                    if (isset($_FILES['admin_avatar_file']) && $_FILES['admin_avatar_file']['error'] === UPLOAD_ERR_OK) {
                        $file_errors = SecurityManager::validateFileUpload($_FILES['admin_avatar_file']);
                        
                        if (empty($file_errors)) {
                            $uploadDir = '../assets/images/avatars/';
                            if (!is_dir($uploadDir)) {
                                mkdir($uploadDir, 0755, true);
                            }
                            
                            $fileExtension = pathinfo($_FILES['admin_avatar_file']['name'], PATHINFO_EXTENSION);
                            $fileName = 'admin-' . $current_user_id . '-' . time() . '.' . $fileExtension;
                            $uploadPath = $uploadDir . $fileName;
                            
                            if (move_uploaded_file($_FILES['admin_avatar_file']['tmp_name'], $uploadPath)) {
                                // Altes Avatar löschen
                                if (!empty($old_user_data['avatar']) && file_exists('../' . $old_user_data['avatar'])) {
                                    unlink('../' . $old_user_data['avatar']);
                                }
                                
                                // Neues Avatar in Datenbank speichern
                                $stmt = $conn->prepare("UPDATE admin_users SET avatar = ? WHERE id = ?");
                                $stmt->execute([$uploadPath, $current_user_id]);
                                
                                $audit_logger->logAvatarUpload($current_user_id, $fileName);
                            }
                        } else {
                            $validation_errors = array_merge($validation_errors, $file_errors);
                        }
                    }
                    
                    // Audit-Log erstellen
                    $audit_logger->logProfileUpdate($current_user_id, $old_user_data, $profile_data);
                    
                    $conn->commit();
                    $success_message = 'Profil erfolgreich aktualisiert';
                    
                } catch (Exception $e) {
                    $conn->rollBack();
                    throw $e;
                }
            }
        }
        
        if (isset($_POST['action']) && $_POST['action'] === 'change_password') {
            $password_data = [
                'current_password' => $_POST['current_password'] ?? '',
                'new_password' => $_POST['new_password'] ?? '',
                'confirm_password' => $_POST['confirm_password'] ?? ''
            ];
            
            $validation_errors = ValidationManager::validatePasswordChange($password_data);
            
            if (empty($validation_errors)) {
                // Aktuelles Passwort prüfen
                $stmt = $conn->prepare("SELECT password_hash FROM admin_users WHERE id = ?");
                $stmt->execute([$current_user_id]);
                $current_hash = $stmt->fetchColumn();
                
                if (password_verify($password_data['current_password'], $current_hash)) {
                    $new_hash = password_hash($password_data['new_password'], PASSWORD_DEFAULT);
                    $stmt = $conn->prepare("UPDATE admin_users SET password_hash = ?, updated_at = NOW() WHERE id = ?");
                    $stmt->execute([$new_hash, $current_user_id]);
                    
                    $audit_logger->logPasswordChange($current_user_id);
                    $success_message = 'Passwort erfolgreich geändert';
                } else {
                    $validation_errors['current_password'] = 'Aktuelles Passwort ist falsch';
                }
            }
        }
        
    } catch (Exception $e) {
        $error_message = 'Fehler beim Speichern: ' . $e->getMessage();
        error_log("Profile Update Error: " . $e->getMessage());
    }
}

// Profildaten abrufen mit optimierter Abfrage
try {
    $stmt = $conn->prepare("SELECT * FROM admin_users WHERE id = ?");
    $stmt->execute([$current_user_id]);
    $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user_data) {
        throw new Exception('Benutzer nicht gefunden');
    }
    
    // Zusätzliche Einstellungen aus admin_settings abrufen
    $stmt = $conn->prepare("SELECT setting_key, setting_value FROM admin_settings WHERE user_id = ?");
    $stmt->execute([$current_user_id]);
    $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    
    // Standardwerte definieren
    $defaults = [
        'admin_name' => $user_data['full_name'] ?? 'Administrator',
        'admin_email' => $user_data['email'] ?? 'admin@boxenstop.de',
        'admin_phone' => $user_data['phone'] ?? '',
        'admin_position' => $user_data['position'] ?? 'Systemadministrator',
        'admin_department' => $user_data['department'] ?? 'IT',
        'admin_avatar' => $user_data['avatar'] ?? 'assets/images/default-avatar.png',
        'admin_bio' => $user_data['bio'] ?? 'Verwalte das Boxenstop-System',
        'admin_language' => $user_data['language'] ?? 'de',
        'admin_timezone' => $user_data['timezone'] ?? 'Europe/Berlin',
        'admin_notifications' => $user_data['notifications'] ?? 'all',
        'admin_theme' => $user_data['theme'] ?? 'light'
    ];
    
    $profile = array_merge($defaults, $settings);
    $current_theme = $profile['admin_theme'];
    
    // Audit-Logs für den Benutzer abrufen (letzte 10 Einträge)
    $audit_logger = new AuditLogger($conn);
    $audit_logs = $audit_logger->getUserAuditLogs($current_user_id, 10);
    
} catch (Exception $e) {
    $error_message = 'Fehler beim Laden der Profildaten: ' . $e->getMessage();
    error_log("Profile Load Error: " . $e->getMessage());
    
    // Fallback-Werte
    $profile = [
        'admin_name' => 'Administrator',
        'admin_email' => 'admin@boxenstop.de',
        'admin_phone' => '',
        'admin_position' => 'Systemadministrator',
        'admin_department' => 'IT',
        'admin_avatar' => 'assets/images/default-avatar.png',
        'admin_bio' => 'Verwalte das Boxenstop-System',
        'admin_language' => 'de',
        'admin_timezone' => 'Europe/Berlin',
        'admin_notifications' => 'all',
        'admin_theme' => 'light'
    ];
    $current_theme = 'light';
    $audit_logs = [];
}

?>

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mein Profil - Boxenstop Admin</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/volvo-theme.css">
    <link rel="stylesheet" href="assets/css/admin.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body class="admin-body" data-theme="<?php echo htmlspecialchars($current_theme); ?>">
    <div class="admin-container">
        <!-- Sidebar -->
        <aside class="admin-sidebar">
            <div class="sidebar-header">
                <img src="../assets/images/volvo-logo.png" alt="Volvo" class="logo-img">
                <h2>Boxenstop Admin</h2>
            </div>
            
            <nav class="sidebar-nav">
                <a href="index.php" class="nav-item">
                    <i class="fas fa-tachometer-alt"></i>
                    <span>Dashboard</span>
                </a>
                <a href="events.php" class="nav-item">
                    <i class="fas fa-calendar-alt"></i>
                    <span>Events</span>
                </a>
                <a href="appointments.php" class="nav-item">
                    <i class="fas fa-calendar-check"></i>
                    <span>Termine</span>
                </a>
                <a href="storage.php" class="nav-item">
                    <i class="fas fa-warehouse"></i>
                    <span>Einlagerungen</span>
                </a>
                <!-- Theme Toggle -->
                <div class="theme-toggle-section">
                    <button class="theme-toggle-btn" id="theme-toggle-btn" title="Design wechseln">
                        <i class="fas fa-moon" id="theme-icon"></i>
                        <span id="theme-text">Dunkel</span>
                    </button>
                </div>
                
                <div class="nav-user-section">
                    <div class="user-menu">
                        <button class="user-menu-toggle">
                            <div class="user-avatar">
                                <i class="fas fa-user"></i>
                            </div>
                            <span class="user-name"><?php echo htmlspecialchars($user_data['full_name'] ?? $user_data['username'] ?? 'Benutzer'); ?></span>
                            <i class="fas fa-chevron-down"></i>
                        </button>
                        <div class="user-dropdown">
                            <a href="profile.php" class="user-dropdown-item active">
                                <i class="fas fa-user"></i>
                                <span>Mein Profil</span>
                            </a>
                            <a href="settings.php" class="user-dropdown-item">
                                <i class="fas fa-cog"></i>
                                <span>Einstellungen</span>
                            </a>
                            <a href="users.php" class="user-dropdown-item">
                                <i class="fas fa-users"></i>
                                <span>Benutzer</span>
                            </a>
                            <div class="user-dropdown-divider"></div>
                            <a href="logout.php" class="user-dropdown-item logout">
                                <i class="fas fa-sign-out-alt"></i>
                                <span>Abmelden</span>
                            </a>
                        </div>
                    </div>
                </div>
            </nav>
        </aside>

        <!-- Main Content -->
        <main class="admin-main">
            <!-- Header -->
            <header class="admin-header">
                <div class="header-content">
                    <h1><i class="fas fa-user"></i> Mein Profil</h1>
                    <div class="header-actions">
                        <button type="button" id="save-profile-btn" class="btn btn-primary">
                            <i class="fas fa-save"></i> Speichern
                        </button>
                    </div>
                </div>
            </header>

            <!-- Content -->
            <div class="admin-content">
                <!-- Erfolgs- und Fehlermeldungen -->
                <?php if (!empty($success_message)): ?>
                    <div class="alert alert-success" id="success-alert">
                        <i class="fas fa-check-circle"></i>
                        <span><?php echo htmlspecialchars($success_message); ?></span>
                        <button type="button" class="alert-close" onclick="this.parentElement.remove()">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                <?php endif; ?>

                <?php if (!empty($error_message)): ?>
                    <div class="alert alert-error" id="error-alert">
                        <i class="fas fa-exclamation-circle"></i>
                        <span><?php echo htmlspecialchars($error_message); ?></span>
                        <button type="button" class="alert-close" onclick="this.parentElement.remove()">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                <?php endif; ?>
                
                <!-- Validierungsfehler anzeigen -->
                <?php if (!empty($validation_errors)): ?>
                    <div class="alert alert-warning" id="validation-alert">
                        <i class="fas fa-exclamation-triangle"></i>
                        <div>
                            <strong>Bitte korrigieren Sie folgende Fehler:</strong>
                            <ul>
                                <?php foreach ($validation_errors as $field => $error): ?>
                                    <li><?php echo htmlspecialchars($error); ?></li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                        <button type="button" class="alert-close" onclick="this.parentElement.remove()">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                <?php endif; ?>

                <div class="profile-container">
                    <!-- Profile Overview -->
                    <div class="profile-overview">
                        <div class="profile-avatar">
                            <img src="../<?php echo htmlspecialchars($profile['admin_avatar']); ?>" alt="Profilbild" id="avatar-preview">
                            <div class="avatar-overlay">
                                <i class="fas fa-camera"></i>
                            </div>
                        </div>
                        <div class="profile-info">
                            <h2><?php echo htmlspecialchars($profile['admin_name']); ?></h2>
                            <p class="profile-position"><?php echo htmlspecialchars($profile['admin_position']); ?></p>
                            <p class="profile-department"><?php echo htmlspecialchars($profile['admin_department']); ?></p>
                            <div class="profile-stats">
                                <div class="stat-item">
                                    <i class="fas fa-calendar-check"></i>
                                    <span>Letzte Anmeldung: Heute</span>
                                </div>
                                <div class="stat-item">
                                    <i class="fas fa-clock"></i>
                                    <span>Mitglied seit: <?php echo date('M Y'); ?></span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Profile Forms -->
                    <div class="profile-forms">
                        <!-- Personal Information -->
                        <form method="POST" enctype="multipart/form-data" id="profile-form" class="profile-form" novalidate>
                            <input type="hidden" name="action" value="update_profile">
                            <input type="hidden" name="csrf_token" value="<?php echo SecurityManager::generateCSRFToken(); ?>">
                            
                            <div class="form-section">
                                <h3><i class="fas fa-user"></i> Persönliche Informationen</h3>
                                <div class="form-grid">
                                    <div class="form-group">
                                        <label for="admin_name">Vollständiger Name</label>
                                        <input type="text" id="admin_name" name="admin_name" 
                                               value="<?php echo htmlspecialchars($profile['admin_name']); ?>" required>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label for="admin_email">E-Mail-Adresse</label>
                                        <input type="email" id="admin_email" name="admin_email" 
                                               value="<?php echo htmlspecialchars($profile['admin_email']); ?>" required>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label for="admin_phone">Telefonnummer</label>
                                        <input type="tel" id="admin_phone" name="admin_phone" 
                                               value="<?php echo htmlspecialchars($profile['admin_phone']); ?>">
                                    </div>
                                    
                                    <div class="form-group">
                                        <label for="admin_position">Position</label>
                                        <input type="text" id="admin_position" name="admin_position" 
                                               value="<?php echo htmlspecialchars($profile['admin_position']); ?>">
                                    </div>
                                    
                                    <div class="form-group">
                                        <label for="admin_department">Abteilung</label>
                                        <input type="text" id="admin_department" name="admin_department" 
                                               value="<?php echo htmlspecialchars($profile['admin_department']); ?>">
                                    </div>
                                    
                                    <div class="form-group">
                                        <label for="admin_avatar_file">Profilbild</label>
                                        <input type="file" id="admin_avatar_file" name="admin_avatar_file" accept="image/*">
                                        <small class="text-muted">Max. 2MB, JPG/PNG empfohlen</small>
                                    </div>
                                    
                                    <div class="form-group full-width">
                                        <label for="admin_bio">Über mich</label>
                                        <textarea id="admin_bio" name="admin_bio" rows="4" 
                                                  placeholder="Kurze Beschreibung über sich..."><?php echo htmlspecialchars($profile['admin_bio']); ?></textarea>
                                    </div>
                                </div>
                            </div>

                            <div class="form-section">
                                <h3><i class="fas fa-cog"></i> Einstellungen</h3>
                                <div class="form-grid">
                                    <div class="form-group">
                                        <label for="admin_language">Sprache</label>
                                        <select id="admin_language" name="admin_language">
                                            <option value="de" <?php echo $profile['admin_language'] === 'de' ? 'selected' : ''; ?>>Deutsch</option>
                                            <option value="en" <?php echo $profile['admin_language'] === 'en' ? 'selected' : ''; ?>>English</option>
                                            <option value="fr" <?php echo $profile['admin_language'] === 'fr' ? 'selected' : ''; ?>>Français</option>
                                        </select>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label for="admin_timezone">Zeitzone</label>
                                        <select id="admin_timezone" name="admin_timezone">
                                            <option value="Europe/Berlin" <?php echo $profile['admin_timezone'] === 'Europe/Berlin' ? 'selected' : ''; ?>>Europa/Berlin</option>
                                            <option value="Europe/Vienna" <?php echo $profile['admin_timezone'] === 'Europe/Vienna' ? 'selected' : ''; ?>>Europa/Wien</option>
                                            <option value="Europe/Zurich" <?php echo $profile['admin_timezone'] === 'Europe/Zurich' ? 'selected' : ''; ?>>Europa/Zürich</option>
                                        </select>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label for="admin_notifications">Benachrichtigungen</label>
                                        <select id="admin_notifications" name="admin_notifications">
                                            <option value="all" <?php echo $profile['admin_notifications'] === 'all' ? 'selected' : ''; ?>>Alle</option>
                                            <option value="important" <?php echo $profile['admin_notifications'] === 'important' ? 'selected' : ''; ?>>Nur wichtige</option>
                                            <option value="none" <?php echo $profile['admin_notifications'] === 'none' ? 'selected' : ''; ?>>Keine</option>
                                        </select>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label for="admin_theme">Design</label>
                                        <select id="admin_theme" name="admin_theme">
                                            <option value="light" <?php echo $profile['admin_theme'] === 'light' ? 'selected' : ''; ?>>Hell</option>
                                            <option value="dark" <?php echo $profile['admin_theme'] === 'dark' ? 'selected' : ''; ?>>Dunkel</option>
                                            <option value="auto" <?php echo $profile['admin_theme'] === 'auto' ? 'selected' : ''; ?>>Automatisch</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="form-actions">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-save"></i> Profil speichern
                                    </button>
                                    <button type="button" class="btn btn-secondary" onclick="document.getElementById('profile-form').reset()">
                                        <i class="fas fa-undo"></i> Zurücksetzen
                                    </button>
                                </div>
                            </div>
                        </form>

                        <!-- Password Change -->
                        <form method="POST" id="password-form" class="password-form" novalidate>
                            <input type="hidden" name="action" value="change_password">
                            <input type="hidden" name="csrf_token" value="<?php echo SecurityManager::generateCSRFToken(); ?>">
                            
                            <div class="form-section">
                                <h3><i class="fas fa-lock"></i> Passwort ändern</h3>
                                <div class="form-grid">
                                    <div class="form-group">
                                        <label for="current_password">Aktuelles Passwort</label>
                                        <input type="password" id="current_password" name="current_password" required>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label for="new_password">Neues Passwort</label>
                                        <input type="password" id="new_password" name="new_password" required minlength="8">
                                    </div>
                                    
                                    <div class="form-group">
                                        <label for="confirm_password">Passwort bestätigen</label>
                                        <input type="password" id="confirm_password" name="confirm_password" required minlength="8">
                                    </div>
                                </div>
                                <button type="submit" class="btn btn-warning">
                                    <i class="fas fa-key"></i> Passwort ändern
                                </button>
                            </div>
                        </form>
                        
                        <!-- Audit Logs Sektion -->
                        <div class="audit-logs-section">
                            <div class="form-section">
                                <h3><i class="fas fa-history"></i> Letzte Aktivitäten</h3>
                                <div class="audit-logs-container">
                                    <?php if (!empty($audit_logs)): ?>
                                        <?php foreach ($audit_logs as $log): ?>
                                            <div class="audit-log-item">
                                                <div class="audit-log-icon">
                                                    <?php
                                                    $icon = 'fas fa-info-circle';
                                                    switch($log['action']) {
                                                        case 'PROFILE_UPDATE': $icon = 'fas fa-user-edit'; break;
                                                        case 'PASSWORD_CHANGE': $icon = 'fas fa-key'; break;
                                                        case 'AVATAR_UPLOAD': $icon = 'fas fa-image'; break;
                                                        case 'SETTINGS_UPDATE': $icon = 'fas fa-cog'; break;
                                                    }
                                                    ?>
                                                    <i class="<?php echo $icon; ?>"></i>
                                                </div>
                                                <div class="audit-log-content">
                                                    <div class="audit-log-action">
                                                        <?php
                                                        $action_text = $log['action'];
                                                        switch($log['action']) {
                                                            case 'PROFILE_UPDATE': $action_text = 'Profil aktualisiert'; break;
                                                            case 'PASSWORD_CHANGE': $action_text = 'Passwort geändert'; break;
                                                            case 'AVATAR_UPLOAD': $action_text = 'Avatar hochgeladen'; break;
                                                            case 'SETTINGS_UPDATE': $action_text = 'Einstellungen geändert'; break;
                                                        }
                                                        echo htmlspecialchars($action_text);
                                                        ?>
                                                    </div>
                                                    <div class="audit-log-time">
                                                        <?php echo date('d.m.Y H:i', strtotime($log['created_at'])); ?>
                                                    </div>
                                                    <div class="audit-log-ip">
                                                        IP: <?php echo htmlspecialchars($log['ip_address']); ?>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <div class="audit-log-empty">
                                            <i class="fas fa-info-circle"></i>
                                            <span>Noch keine Aktivitäten aufgezeichnet</span>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <script src="../assets/js/main.js"></script>
    <script src="assets/js/admin.js"></script>
    <script src="assets/js/theme.js"></script>
    
    <style>
        .profile-container {
            display: grid;
            grid-template-columns: 1fr 2fr;
            gap: 2rem;
            margin-top: 1rem;
        }
        
        .profile-overview {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            height: fit-content;
        }
        
        .profile-avatar {
            position: relative;
            width: 120px;
            height: 120px;
            margin: 0 auto 1.5rem;
            border-radius: 50%;
            overflow: hidden;
            border: 4px solid #e9ecef;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .profile-avatar:hover {
            border-color: #007bff;
            transform: scale(1.05);
        }
        
        .profile-avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .avatar-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        
        .profile-avatar:hover .avatar-overlay {
            opacity: 1;
        }
        
        .profile-info h2 {
            margin: 0 0 0.5rem 0;
            color: #2c3e50;
            text-align: center;
        }
        
        .profile-position {
            color: #007bff;
            font-weight: 500;
            text-align: center;
            margin: 0 0 0.25rem 0;
        }
        
        .profile-department {
            color: #6c757d;
            text-align: center;
            margin: 0 0 1.5rem 0;
        }
        
        .profile-stats {
            border-top: 1px solid #e9ecef;
            padding-top: 1rem;
        }
        
        .stat-item {
            display: flex;
            align-items: center;
            margin-bottom: 0.5rem;
            color: #6c757d;
            font-size: 0.9rem;
        }
        
        .stat-item i {
            margin-right: 0.5rem;
            width: 16px;
        }
        
        .profile-forms {
            display: flex;
            flex-direction: column;
            gap: 2rem;
        }
        
        .profile-form, .password-form {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .form-section {
            margin-bottom: 2rem;
        }
        
        .form-section:last-child {
            margin-bottom: 0;
        }
        
        .form-section h3 {
            margin: 0 0 1.5rem 0;
            color: #2c3e50;
            font-size: 1.2rem;
            border-bottom: 2px solid #e9ecef;
            padding-bottom: 0.5rem;
        }
        
        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1.5rem;
        }
        
        .form-group.full-width {
            grid-column: 1 / -1;
        }
        
        .form-group {
            display: flex;
            flex-direction: column;
        }
        
        .form-group label {
            font-weight: 500;
            color: #495057;
            margin-bottom: 0.5rem;
            font-size: 0.95rem;
        }
        
        .form-group input,
        .form-group select,
        .form-group textarea {
            padding: 0.75rem;
            border: 2px solid #dee2e6;
            border-radius: 6px;
            font-size: 1rem;
            transition: all 0.3s ease;
        }
        
        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
        }
        
        .text-muted {
            color: #6c757d;
            font-size: 0.85rem;
            margin-top: 0.25rem;
        }
        
        .btn {
            padding: 0.75rem 1.5rem;
            border: none;
            border-radius: 6px;
            font-size: 1rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .btn-primary {
            background: #007bff;
            color: white;
        }
        
        .btn-primary:hover {
            background: #0056b3;
        }
        
        .btn-warning {
            background: #ffc107;
            color: #212529;
        }
        
        .btn-warning:hover {
            background: #e0a800;
        }
        
        .alert {
            padding: 1rem;
            border-radius: 6px;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        @media (max-width: 768px) {
            .profile-container {
                grid-template-columns: 1fr;
            }
        }
        
        /* User Menu Styles */
        .nav-user-section {
            margin-top: auto;
            padding-top: 1rem;
            border-top: 1px solid #e9ecef;
        }
        
        .user-menu {
            position: relative;
        }
        
        .user-menu-toggle {
            width: 100%;
            background: none;
            border: none;
            padding: 0.75rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
            border-radius: 8px;
            transition: all 0.3s ease;
            cursor: pointer;
            color: #6c757d;
        }
        
        .user-menu-toggle:hover {
            background: #f8f9fa;
            color: #495057;
        }
        
        .user-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: #007bff;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.9rem;
        }
        
        .user-name {
            flex: 1;
            font-weight: 500;
            text-align: left;
        }
        
        .user-menu-toggle .fa-chevron-down {
            font-size: 0.8rem;
            transition: transform 0.3s ease;
        }
        
        .user-menu.active .fa-chevron-down {
            transform: rotate(180deg);
        }
        
        .user-dropdown {
            position: absolute;
            bottom: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            z-index: 1000;
            opacity: 0;
            visibility: hidden;
            transform: translateY(10px);
            transition: all 0.3s ease;
            margin-bottom: 0.5rem;
        }
        
        .user-menu.active .user-dropdown {
            opacity: 1;
            visibility: visible;
            transform: translateY(0);
        }
        
        .user-dropdown-item {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            padding: 0.75rem 1rem;
            color: #495057;
            text-decoration: none;
            transition: all 0.3s ease;
            border-bottom: 1px solid #f8f9fa;
        }
        
        .user-dropdown-item:last-child {
            border-bottom: none;
        }
        
        .user-dropdown-item:hover {
            background: #f8f9fa;
            color: #007bff;
            text-decoration: none;
        }
        
        .user-dropdown-item.active {
            background: #e3f2fd;
            color: #007bff;
        }
        
        .user-dropdown-item.logout:hover {
            color: #dc3545;
        }
        
        .user-dropdown-item i {
            width: 16px;
            font-size: 0.9rem;
        }
        
        .user-dropdown-divider {
            height: 1px;
            background: #e9ecef;
            margin: 0.25rem 0;
        }
        
        /* Theme Toggle Styles */
        .theme-toggle-section {
            margin: 1rem 0;
            padding: 0 1rem;
        }
        
        .theme-toggle-btn {
            width: 100%;
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 0.75rem 1rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
            cursor: pointer;
            transition: all 0.3s ease;
            color: #495057;
            font-weight: 500;
            font-size: 0.9rem;
        }
        
        .theme-toggle-btn:hover {
            background: #e9ecef;
            border-color: #adb5bd;
            transform: translateY(-1px);
        }
        
        .theme-toggle-btn i {
            font-size: 1rem;
            width: 16px;
            text-align: center;
        }
        
        /* Dark theme toggle styles */
        body.dark-theme .theme-toggle-btn {
            background: var(--dark-bg-tertiary);
            border-color: var(--dark-border);
            color: var(--dark-text-secondary);
        }
        
        body.dark-theme .theme-toggle-btn:hover {
            background: var(--dark-bg-secondary);
            border-color: var(--dark-accent-blue);
            color: var(--dark-text-primary);
        }
        
        /* Alert Styles */
        .alert {
            position: relative;
            padding: 1rem 3rem 1rem 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
            display: flex;
            align-items: flex-start;
            gap: 0.75rem;
            animation: slideIn 0.3s ease-out;
        }
        
        .alert-close {
            position: absolute;
            top: 0.75rem;
            right: 1rem;
            background: none;
            border: none;
            color: inherit;
            cursor: pointer;
            font-size: 1.2rem;
            opacity: 0.7;
            transition: opacity 0.3s ease;
        }
        
        .alert-close:hover {
            opacity: 1;
        }
        
        .alert-warning {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
        
        .alert-warning ul {
            margin: 0.5rem 0 0 0;
            padding-left: 1.5rem;
        }
        
        .alert-warning li {
            margin-bottom: 0.25rem;
        }
        
        /* Form Validation Styles */
        .form-group input.error,
        .form-group select.error,
        .form-group textarea.error {
            border-color: #dc3545;
            box-shadow: 0 0 0 3px rgba(220, 53, 69, 0.1);
        }
        
        .form-group input:valid,
        .form-group select:valid,
        .form-group textarea:valid {
            border-color: #28a745;
        }
        
        /* Audit Logs Styles */
        .audit-logs-section {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-top: 2rem;
        }
        
        .audit-logs-container {
            max-height: 400px;
            overflow-y: auto;
        }
        
        .audit-log-item {
            display: flex;
            align-items: center;
            gap: 1rem;
            padding: 1rem;
            border-bottom: 1px solid #e9ecef;
            transition: background-color 0.3s ease;
        }
        
        .audit-log-item:last-child {
            border-bottom: none;
        }
        
        .audit-log-item:hover {
            background: #f8f9fa;
        }
        
        .audit-log-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #e9ecef;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #6c757d;
            font-size: 1.1rem;
        }
        
        .audit-log-content {
            flex: 1;
        }
        
        .audit-log-action {
            font-weight: 500;
            color: #2c3e50;
            margin-bottom: 0.25rem;
        }
        
        .audit-log-time {
            font-size: 0.9rem;
            color: #6c757d;
            margin-bottom: 0.25rem;
        }
        
        .audit-log-ip {
            font-size: 0.8rem;
            color: #adb5bd;
        }
        
        .audit-log-empty {
            text-align: center;
            padding: 2rem;
            color: #6c757d;
        }
        
        .audit-log-empty i {
            font-size: 2rem;
            margin-bottom: 1rem;
            display: block;
        }
        
        /* Animations */
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        /* Loading States */
        .btn.loading {
            position: relative;
            color: transparent;
        }
        
        .btn.loading::after {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 20px;
            height: 20px;
            margin: -10px 0 0 -10px;
            border: 2px solid transparent;
            border-top: 2px solid currentColor;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* Form Actions */
        .form-actions {
            display: flex;
            gap: 1rem;
            margin-top: 2rem;
            padding-top: 1.5rem;
            border-top: 1px solid #e9ecef;
            justify-content: flex-end;
        }
        
        .form-actions .btn {
            min-width: 150px;
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #5a6268;
        }
        
        /* Field Error Styles */
        .field-error {
            color: #dc3545;
            font-size: 0.875rem;
            margin-top: 0.25rem;
            display: block;
        }
        
        /* Responsive Improvements */
        @media (max-width: 768px) {
            .profile-container {
                grid-template-columns: 1fr;
                gap: 1rem;
            }
            
            .profile-overview {
                padding: 1.5rem;
            }
            
            .profile-forms {
                gap: 1.5rem;
            }
            
            .form-grid {
                grid-template-columns: 1fr;
                gap: 1rem;
            }
            
            .audit-logs-section {
                padding: 1.5rem;
            }
            
            .form-actions {
                flex-direction: column;
                align-items: stretch;
            }
            
            .form-actions .btn {
                min-width: auto;
            }
        }
    </style>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Auto-hide alerts after 5 seconds
            setTimeout(function() {
                const alerts = document.querySelectorAll('.alert');
                alerts.forEach(function(alert) {
                    if (alert.id !== 'validation-alert') {
                        alert.style.opacity = '0';
                        setTimeout(function() {
                            alert.remove();
                        }, 300);
                    }
                });
            }, 5000);
            
            // Speichern-Button Funktionalität
            const saveProfileBtn = document.getElementById('save-profile-btn');
            if (saveProfileBtn) {
                saveProfileBtn.addEventListener('click', function() {
                    const profileForm = document.getElementById('profile-form');
                    if (profileForm) {
                        // Formular validieren
                        if (validateProfileForm()) {
                            profileForm.submit();
                        }
                    }
                });
            }
            
            // Formular-Validierung
            function validateProfileForm() {
                const requiredFields = ['admin_name', 'admin_email'];
                let isValid = true;
                
                requiredFields.forEach(function(fieldName) {
                    const field = document.querySelector('[name="' + fieldName + '"]');
                    if (field && !field.value.trim()) {
                        field.classList.add('error');
                        isValid = false;
                    } else if (field) {
                        field.classList.remove('error');
                    }
                });
                
                // E-Mail-Format prüfen
                const emailField = document.querySelector('[name="admin_email"]');
                if (emailField && emailField.value && !isValidEmail(emailField.value)) {
                    emailField.classList.add('error');
                    isValid = false;
                }
                
                if (!isValid) {
                    alert('Bitte füllen Sie alle Pflichtfelder korrekt aus.');
                }
                
                return isValid;
            }
            
            // E-Mail-Validierung
            function isValidEmail(email) {
                return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
            }
            
            // Theme toggle button
            const themeToggleBtn = document.getElementById('theme-toggle-btn');
            const themeIcon = document.getElementById('theme-icon');
            const themeText = document.getElementById('theme-text');
            
            if (themeToggleBtn) {
                themeToggleBtn.addEventListener('click', function() {
                    const currentTheme = window.themeManager ? window.themeManager.getTheme() : 'light';
                    const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
                    
                    // Update theme
                    if (window.themeManager) {
                        window.themeManager.setTheme(newTheme);
                    }
                    
                    // Update button appearance
                    updateThemeToggleButton(newTheme);
                    
                    // Update form select if it exists
                    const themeSelect = document.getElementById('admin_theme');
                    if (themeSelect) {
                        themeSelect.value = newTheme;
                    }
                });
                
                // Update button appearance on page load
                const currentTheme = window.themeManager ? window.themeManager.getTheme() : 'light';
                updateThemeToggleButton(currentTheme);
            }
            
            function updateThemeToggleButton(theme) {
                if (themeIcon && themeText) {
                    if (theme === 'dark') {
                        themeIcon.className = 'fas fa-sun';
                        themeText.textContent = 'Hell';
                    } else {
                        themeIcon.className = 'fas fa-moon';
                        themeText.textContent = 'Dunkel';
                    }
                }
            }
            
            // Avatar preview with validation
            const avatarInput = document.getElementById('admin_avatar_file');
            const avatarPreview = document.getElementById('avatar-preview');
            
            if (avatarInput) {
                avatarInput.addEventListener('change', function(e) {
                    const file = e.target.files[0];
                    if (file) {
                        // File size validation (2MB max)
                        if (file.size > 2 * 1024 * 1024) {
                            alert('Datei ist zu groß. Maximum: 2MB');
                            e.target.value = '';
                            return;
                        }
                        
                        // File type validation
                        const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
                        if (!allowedTypes.includes(file.type)) {
                            alert('Ungültiger Dateityp. Nur JPG, PNG und GIF erlaubt.');
                            e.target.value = '';
                            return;
                        }
                        
                        const reader = new FileReader();
                        reader.onload = function(e) {
                            avatarPreview.src = e.target.result;
                        };
                        reader.readAsDataURL(file);
                    }
                });
            }
            
            // Enhanced password validation
            const newPassword = document.getElementById('new_password');
            const confirmPassword = document.getElementById('confirm_password');
            
            function validatePassword() {
                const password = newPassword.value;
                const confirm = confirmPassword.value;
                
                // Clear previous custom validity
                newPassword.setCustomValidity('');
                confirmPassword.setCustomValidity('');
                
                // Check password strength
                if (password.length < 8) {
                    newPassword.setCustomValidity('Passwort muss mindestens 8 Zeichen lang sein');
                    return;
                }
                
                if (!/(?=.*[a-z])/.test(password)) {
                    newPassword.setCustomValidity('Passwort muss mindestens einen Kleinbuchstaben enthalten');
                    return;
                }
                
                if (!/(?=.*[A-Z])/.test(password)) {
                    newPassword.setCustomValidity('Passwort muss mindestens einen Großbuchstaben enthalten');
                    return;
                }
                
                if (!/(?=.*\d)/.test(password)) {
                    newPassword.setCustomValidity('Passwort muss mindestens eine Zahl enthalten');
                    return;
                }
                
                if (!/(?=.*[^a-zA-Z\d])/.test(password)) {
                    newPassword.setCustomValidity('Passwort muss mindestens ein Sonderzeichen enthalten');
                    return;
                }
                
                // Check password confirmation
                if (password !== confirm) {
                    confirmPassword.setCustomValidity('Passwörter stimmen nicht überein');
                }
            }
            
            if (newPassword) newPassword.addEventListener('input', validatePassword);
            if (confirmPassword) confirmPassword.addEventListener('input', validatePassword);
            
            // Form validation
            const profileForm = document.getElementById('profile-form');
            if (profileForm) {
                profileForm.addEventListener('submit', function(e) {
                    const requiredFields = profileForm.querySelectorAll('[required]');
                    let isValid = true;
                    
                    requiredFields.forEach(function(field) {
                        if (!field.value.trim()) {
                            field.classList.add('error');
                            isValid = false;
                        } else {
                            field.classList.remove('error');
                        }
                    });
                    
                    if (!isValid) {
                        e.preventDefault();
                        alert('Bitte füllen Sie alle Pflichtfelder aus.');
                    }
                });
            }
            
            // User menu toggle
            const userMenuToggle = document.querySelector('.user-menu-toggle');
            const userMenu = document.querySelector('.user-menu');
            
            if (userMenuToggle && userMenu) {
                userMenuToggle.addEventListener('click', function(e) {
                    e.preventDefault();
                    userMenu.classList.toggle('active');
                });
                
                // Close menu when clicking outside
                document.addEventListener('click', function(e) {
                    if (!userMenu.contains(e.target)) {
                        userMenu.classList.remove('active');
                    }
                });
            }
            
            // Real-time form validation
            const inputs = document.querySelectorAll('input, select, textarea');
            inputs.forEach(function(input) {
                input.addEventListener('blur', function() {
                    if (this.hasAttribute('required') && !this.value.trim()) {
                        this.classList.add('error');
                    } else {
                        this.classList.remove('error');
                    }
                    
                    // E-Mail-Validierung
                    if (this.type === 'email' && this.value && !isValidEmail(this.value)) {
                        this.classList.add('error');
                    }
                });
                
                input.addEventListener('input', function() {
                    this.classList.remove('error');
                });
            });
            
            // Formular-Submit-Validierung
            const profileForm = document.getElementById('profile-form');
            if (profileForm) {
                profileForm.addEventListener('submit', function(e) {
                    if (!validateProfileForm()) {
                        e.preventDefault();
                    }
                });
            }
            
            // Passwort-Validierung
            const newPassword = document.getElementById('new_password');
            const confirmPassword = document.getElementById('confirm_password');
            
            if (newPassword && confirmPassword) {
                function validatePasswords() {
                    const password = newPassword.value;
                    const confirm = confirmPassword.value;
                    
                    // Clear previous errors
                    newPassword.classList.remove('error');
                    confirmPassword.classList.remove('error');
                    
                    if (password && password.length < 8) {
                        newPassword.classList.add('error');
                        return false;
                    }
                    
                    if (password && confirm && password !== confirm) {
                        confirmPassword.classList.add('error');
                        return false;
                    }
                    
                    return true;
                }
                
                newPassword.addEventListener('input', validatePasswords);
                confirmPassword.addEventListener('input', validatePasswords);
                
                // Passwort-Formular-Validierung
                const passwordForm = document.getElementById('password-form');
                if (passwordForm) {
                    passwordForm.addEventListener('submit', function(e) {
                        if (!validatePasswords()) {
                            e.preventDefault();
                            alert('Bitte korrigieren Sie die Passwort-Eingaben.');
                        }
                    });
                }
            }
            
            // Avatar-Preview
            const avatarInput = document.getElementById('admin_avatar_file');
            const avatarPreview = document.getElementById('avatar-preview');
            
            if (avatarInput && avatarPreview) {
                avatarInput.addEventListener('change', function(e) {
                    const file = e.target.files[0];
                    if (file) {
                        // File validation
                        if (file.size > 2 * 1024 * 1024) {
                            alert('Datei ist zu groß. Maximum: 2MB');
                            e.target.value = '';
                            return;
                        }
                        
                        const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
                        if (!allowedTypes.includes(file.type)) {
                            alert('Ungültiger Dateityp. Nur JPG, PNG und GIF erlaubt.');
                            e.target.value = '';
                            return;
                        }
                        
                        const reader = new FileReader();
                        reader.onload = function(e) {
                            avatarPreview.src = e.target.result;
                        };
                        reader.readAsDataURL(file);
                    }
                });
            }
        });
    </script>
</body>
</html>
