<?php
session_start();
require_once '../config/database.php';

// Check if user is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

// Get current user ID
$current_user_id = $_SESSION['admin_user_id'] ?? null;
$current_user_name = 'Administrator';
$current_user_role = 'admin'; // Default role
if (!$current_user_id) {
    header('Location: login.php');
    exit;
}

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

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['action']) && $_POST['action'] === 'update_profile') {
            // First, check if admin_settings table exists, if not create it
            $conn->exec("
                CREATE TABLE IF NOT EXISTS admin_settings (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    user_id INT NOT NULL,
                    setting_key VARCHAR(100) NOT NULL,
                    setting_value TEXT,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                    UNIQUE KEY unique_user_setting (user_id, setting_key),
                    FOREIGN KEY (user_id) REFERENCES admin_users(id) ON DELETE CASCADE
                )
            ");
            
            // Check if admin_users table has the required columns, if not add them
            $columns_to_add = [
                'full_name' => 'VARCHAR(100)',
                'department' => 'VARCHAR(100)',
                'phone' => 'VARCHAR(20)',
                'position' => 'VARCHAR(100)',
                'bio' => 'TEXT',
                'avatar' => 'VARCHAR(255)',
                'language' => 'VARCHAR(10) DEFAULT "de"',
                'timezone' => 'VARCHAR(50) DEFAULT "Europe/Berlin"',
                'notifications' => 'VARCHAR(20) DEFAULT "all"',
                'theme' => 'VARCHAR(20) DEFAULT "light"'
            ];
            
            foreach ($columns_to_add as $column => $definition) {
                try {
                    $conn->exec("ALTER TABLE admin_users ADD COLUMN $column $definition");
                } catch (PDOException $e) {
                    // Column might already exist, ignore error
                }
            }
            
            // Update user profile in admin_users table
            $stmt = $conn->prepare("
                UPDATE admin_users 
                SET email = ?, full_name = ?, department = ?, phone = ?, position = ?, bio = ?, 
                    language = ?, timezone = ?, notifications = ?, theme = ?
                WHERE id = ?
            ");
            $stmt->execute([
                $_POST['admin_email'],
                $_POST['admin_name'],
                $_POST['admin_department'],
                $_POST['admin_phone'],
                $_POST['admin_position'],
                $_POST['admin_bio'] ?? null,
                $_POST['admin_language'],
                $_POST['admin_timezone'],
                $_POST['admin_notifications'] ?? 'all',
                $_POST['admin_theme'] ?? 'light',
                $current_user_id
            ]);
            
            // Handle avatar upload
            if (isset($_FILES['admin_avatar_file']) && $_FILES['admin_avatar_file']['error'] === UPLOAD_ERR_OK) {
                $uploadDir = '../assets/images/avatars/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }
                $fileName = 'admin-' . time() . '.' . pathinfo($_FILES['admin_avatar_file']['name'], PATHINFO_EXTENSION);
                $uploadPath = $uploadDir . $fileName;
                
                if (move_uploaded_file($_FILES['admin_avatar_file']['tmp_name'], $uploadPath)) {
                    $stmt = $conn->prepare("UPDATE admin_users SET avatar = ? WHERE id = ?");
                    $stmt->execute([$uploadPath, $current_user_id]);
                }
            }
            
            // Debug: Check if update was successful
            $affected_rows = $stmt->rowCount();
            if ($affected_rows > 0) {
                $_SESSION['success_message'] = 'Profil erfolgreich aktualisiert';
            } else {
                $_SESSION['error_message'] = 'Keine Änderungen vorgenommen oder Benutzer nicht gefunden';
            }
            header('Location: profile.php');
            exit;
        }
        
        if (isset($_POST['action']) && $_POST['action'] === 'change_password') {
            $current_password = $_POST['current_password'];
            $new_password = $_POST['new_password'];
            $confirm_password = $_POST['confirm_password'];
            
            if ($new_password !== $confirm_password) {
                $_SESSION['error_message'] = 'Neue Passwörter stimmen nicht überein';
            } else {
                // Get current password hash
                $stmt = $conn->prepare("SELECT password_hash FROM admin_users WHERE id = ?");
                $stmt->execute([$current_user_id]);
                $current_hash = $stmt->fetchColumn();
                
                if (password_verify($current_password, $current_hash)) {
                    $new_hash = password_hash($new_password, PASSWORD_DEFAULT);
                    $stmt = $conn->prepare("UPDATE admin_users SET password_hash = ? WHERE id = ?");
                    $stmt->execute([$new_hash, $current_user_id]);
                    $_SESSION['success_message'] = 'Passwort erfolgreich geändert';
                } else {
                    $_SESSION['error_message'] = 'Aktuelles Passwort ist falsch';
                }
            }
            header('Location: profile.php');
            exit;
        }
    } catch (Exception $e) {
        $_SESSION['error_message'] = 'Fehler beim Speichern: ' . $e->getMessage();
    }
}

// Get current profile data
$stmt = $conn->prepare("SELECT * FROM admin_users WHERE id = ?");
$stmt->execute([$current_user_id]);
$user_data = $stmt->fetch(PDO::FETCH_ASSOC);

$current_user_name = $user_data['username'] ?? 'Administrator';
$current_user_role = $user_data['role'] ?? 'admin'; // Setze die Rolle aus der Datenbank

$current_theme = $user_data['theme'] ?? 'light';

$defaults = [
    'admin_name' => $user_data['full_name'] ?? 'Administrator',
    'admin_email' => $user_data['email'] ?? 'admin@boxenstop.de',
    'admin_phone' => $user_data['phone'] ?? '+49 123 456789',
    '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 = $defaults;
?>

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>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 rel="stylesheet" href="assets/css/global-dark-theme.css">
    <link rel="stylesheet" href="assets/css/unified-sidebar.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&family=SF+Pro+Display:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        /* Volvo-Apple Hybrid Design System */
        :root {
            /* Volvo Brand Colors */
            --volvo-blue: #0066CC;
            --volvo-blue-dark: #004C99;
            --volvo-blue-light: #E6F2FF;
            --volvo-gray: #2C3E50;
            --volvo-gray-light: #ECF0F1;
            --volvo-accent: #F39C12;
            
            /* Apple-inspired Neutrals */
            --apple-white: #FFFFFF;
            --apple-gray-1: #F2F2F7;
            --apple-gray-2: #E5E5EA;
            --apple-gray-3: #C7C7CC;
            --apple-gray-4: #8E8E93;
            --apple-gray-5: #636366;
            --apple-gray-6: #48484A;
            --apple-black: #1C1C1E;
            
            /* Design System */
            --color-primary: var(--volvo-blue);
            --color-primary-hover: var(--volvo-blue-dark);
            --color-primary-light: var(--volvo-blue-light);
            --color-secondary: var(--apple-gray-5);
            --color-accent: var(--volvo-accent);
            --color-success: #34C759;
            --color-warning: #FF9500;
            --color-error: #FF3B30;
            
            /* Surfaces */
            --surface-primary: var(--apple-white);
            --surface-secondary: var(--apple-gray-1);
            --surface-tertiary: var(--apple-gray-2);
            --surface-elevated: var(--apple-white);
            
            /* Text */
            --text-primary: var(--apple-black);
            --text-secondary: var(--apple-gray-5);
            --text-tertiary: var(--apple-gray-4);
            
            /* Borders & Radii */
            --border-color: var(--apple-gray-3);
            --border-radius: 12px;
            --border-radius-large: 20px;
            
            /* Spacing (Apple's 8pt grid system) */
            --spacing-xs: 4px;
            --spacing-sm: 8px;
            --spacing-md: 16px;
            --spacing-lg: 24px;
            --spacing-xl: 32px;
            --spacing-xxl: 48px;
            
            /* Typography (SF Pro Display inspired) */
            --font-family: 'SF Pro Display', 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            --font-size-xs: 12px;
            --font-size-sm: 14px;
            --font-size-md: 16px;
            --font-size-lg: 18px;
            --font-size-xl: 24px;
            --font-size-xxl: 32px;
            --font-weight-regular: 400;
            --font-weight-medium: 500;
            --font-weight-semibold: 600;
            --font-weight-bold: 700;
            --font-weight-heavy: 800;
            
            /* Shadows (Subtle Apple-style) */
            --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.04), 0 1px 2px rgba(0, 0, 0, 0.06);
            --shadow-md: 0 4px 6px rgba(0, 0, 0, 0.04), 0 2px 4px rgba(0, 0, 0, 0.06);
            --shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.04), 0 4px 6px rgba(0, 0, 0, 0.05);
            --shadow-xl: 0 20px 25px rgba(0, 0, 0, 0.04), 0 10px 10px rgba(0, 0, 0, 0.04);
            
            /* Transitions (Apple's ease curves) */
            --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 Variables */
        [data-theme="dark"] {
            --surface-primary: #1C1C1E;
            --surface-secondary: #2C2C2E;
            --surface-tertiary: #3A3A3C;
            --surface-elevated: #2C2C2E;
            --text-primary: #FFFFFF;
            --text-secondary: #8E8E93;
            --text-tertiary: #636366;
            --border-color: #48484A;
            --color-primary: #0A84FF;
            --color-primary-hover: #0051D5;
            --color-primary-light: rgba(10, 132, 255, 0.1);
        }

        /* Global Reset & Base Styles */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: var(--font-family);
            background: var(--surface-secondary);
            color: var(--text-primary);
            line-height: 1.6;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
        }

        /* Layout */
        .profile-main {
            margin-left: 280px;
            transition: margin-left var(--transition-normal);
            min-height: 100vh;
            background: var(--surface-secondary);
        }

        .modern-sidebar.collapsed + .profile-main {
            margin-left: 80px;
        }

        /* Profile Header with Hero Section */
        .profile-header {
            position: relative;
            background: var(--surface-primary);
            border-bottom: 1px solid var(--border-color);
        }

        .profile-hero {
            position: relative;
            padding: var(--spacing-xxl) var(--spacing-xl);
            background: linear-gradient(135deg, var(--color-primary) 0%, var(--volvo-blue-dark) 100%);
            overflow: hidden;
        }

        .profile-hero::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grid" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M 10 0 L 0 0 0 10" fill="none" stroke="rgba(255,255,255,0.05)" stroke-width="0.5"/></pattern></defs><rect width="100" height="100" fill="url(%23grid)"/></svg>');
            opacity: 0.3;
        }

        .profile-hero-content {
            position: relative;
            display: flex;
            align-items: center;
            justify-content: space-between;
            max-width: 1200px;
            margin: 0 auto;
            z-index: 1;
        }

        .profile-avatar-section {
            display: flex;
            align-items: center;
            gap: var(--spacing-lg);
        }

        .profile-avatar-container {
            position: relative;
            width: 120px;
            height: 120px;
            border-radius: 50%;
            border: 4px solid rgba(255, 255, 255, 0.2);
            overflow: hidden;
            cursor: pointer;
            transition: all var(--transition-normal);
            backdrop-filter: blur(10px);
        }

        .profile-avatar-container:hover {
            border-color: rgba(255, 255, 255, 0.4);
            transform: scale(1.05);
        }

        .profile-avatar-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .avatar-upload-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.6);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            color: white;
            opacity: 0;
            transition: opacity var(--transition-normal);
            font-size: var(--font-size-sm);
            font-weight: var(--font-weight-medium);
        }

        .avatar-upload-overlay i {
            font-size: var(--font-size-lg);
            margin-bottom: var(--spacing-xs);
        }

        .profile-avatar-container:hover .avatar-upload-overlay {
            opacity: 1;
        }

        .profile-identity {
            color: white;
        }

        .profile-name {
            font-size: var(--font-size-xxl);
            font-weight: var(--font-weight-bold);
            margin-bottom: var(--spacing-xs);
            color: white;
        }

        .profile-role {
            font-size: var(--font-size-lg);
            font-weight: var(--font-weight-medium);
            color: rgba(255, 255, 255, 0.9);
            margin-bottom: var(--spacing-md);
        }

        .profile-meta {
            display: flex;
            flex-direction: column;
            gap: var(--spacing-sm);
        }

        .meta-item {
            display: flex;
            align-items: center;
            gap: var(--spacing-sm);
            color: rgba(255, 255, 255, 0.8);
            font-size: var(--font-size-sm);
        }

        .meta-item i {
            width: 16px;
            text-align: center;
        }

        .profile-actions {
            display: flex;
            gap: var(--spacing-md);
        }

        /* Modern Button System */
        .btn-primary,
        .btn-secondary {
            display: inline-flex;
            align-items: center;
            gap: var(--spacing-sm);
            padding: var(--spacing-md) var(--spacing-lg);
            border: none;
            border-radius: var(--border-radius);
            font-family: var(--font-family);
            font-size: var(--font-size-md);
            font-weight: var(--font-weight-semibold);
            text-decoration: none;
            cursor: pointer;
            transition: all var(--transition-normal);
            white-space: nowrap;
            position: relative;
            overflow: hidden;
        }

        .btn-primary {
            background: white;
            color: var(--color-primary);
            box-shadow: var(--shadow-md);
        }

        .btn-primary:hover {
            background: var(--apple-gray-1);
            transform: translateY(-2px);
            box-shadow: var(--shadow-lg);
        }

        .btn-secondary {
            background: var(--color-primary);
            color: white;
            box-shadow: var(--shadow-md);
        }

        .btn-secondary:hover {
            background: var(--color-primary-hover);
            transform: translateY(-2px);
            box-shadow: var(--shadow-lg);
        }

        /* Profile Content */
        .profile-content {
            padding: var(--spacing-xl);
            max-width: 1200px;
            margin: 0 auto;
        }

        /* Alert System */
        .alert {
            display: flex;
            align-items: flex-start;
            gap: var(--spacing-md);
            padding: var(--spacing-md) var(--spacing-lg);
            margin-bottom: var(--spacing-lg);
            border-radius: var(--border-radius);
            border: 1px solid;
            position: relative;
            backdrop-filter: blur(10px);
        }

        .alert-success {
            background: rgba(52, 199, 89, 0.1);
            border-color: var(--color-success);
            color: var(--color-success);
        }

        .alert-error {
            background: rgba(255, 59, 48, 0.1);
            border-color: var(--color-error);
            color: var(--color-error);
        }

        .alert-icon {
            flex-shrink: 0;
            margin-top: 2px;
        }

        .alert-content {
            flex: 1;
        }

        .alert-content p {
            margin: 0;
            font-weight: var(--font-weight-medium);
        }

        .alert-dismiss {
            position: absolute;
            top: var(--spacing-md);
            right: var(--spacing-md);
            background: none;
            border: none;
            color: inherit;
            cursor: pointer;
            padding: var(--spacing-xs);
            border-radius: 4px;
            transition: background var(--transition-fast);
        }

        .alert-dismiss:hover {
            background: rgba(0, 0, 0, 0.1);
        }

        /* Card-Based Layout System */
        .profile-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
            gap: var(--spacing-xl);
        }

        .profile-card {
            background: var(--surface-primary);
            border-radius: var(--border-radius-large);
            border: 1px solid var(--border-color);
            box-shadow: var(--shadow-sm);
            overflow: hidden;
            transition: all var(--transition-normal);
            position: relative;
        }

        .profile-card:hover {
            box-shadow: var(--shadow-md);
            transform: translateY(-2px);
        }

        .card-header {
            padding: var(--spacing-lg);
            border-bottom: 1px solid var(--border-color);
            background: var(--surface-secondary);
        }

        .card-title {
            display: flex;
            align-items: center;
            gap: var(--spacing-md);
        }

        .card-title i {
            color: var(--color-primary);
            font-size: var(--font-size-lg);
        }

        .card-title h2 {
            font-size: var(--font-size-lg);
            font-weight: var(--font-weight-semibold);
            color: var(--text-primary);
        }

        .card-content {
            padding: var(--spacing-lg);
        }

        /* Form System */
        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: var(--spacing-lg);
            margin-bottom: var(--spacing-lg);
        }

        .form-group {
            display: flex;
            flex-direction: column;
            gap: var(--spacing-sm);
        }

        .form-group label {
            font-size: var(--font-size-sm);
            font-weight: var(--font-weight-semibold);
            color: var(--text-primary);
        }

        .form-input,
        .form-select,
        .form-textarea {
            padding: var(--spacing-md);
            border: 2px solid var(--border-color);
            border-radius: var(--border-radius);
            font-family: var(--font-family);
            font-size: var(--font-size-md);
            background: var(--surface-primary);
            color: var(--text-primary);
            transition: all var(--transition-normal);
        }

        .form-input:focus,
        .form-select:focus,
        .form-textarea:focus {
            outline: none;
            border-color: var(--color-primary);
            box-shadow: 0 0 0 3px var(--color-primary-light);
        }

        .bio-group {
            grid-column: 1 / -1;
        }

        .form-textarea {
            resize: vertical;
            min-height: 120px;
        }

        /* File Input Enhancement */
        .file-input-group {
            grid-column: 1 / -1;
        }

        .file-input-wrapper {
            position: relative;
            border: 2px dashed var(--border-color);
            border-radius: var(--border-radius);
            transition: all var(--transition-normal);
            cursor: pointer;
        }

        .file-input-wrapper:hover {
            border-color: var(--color-primary);
            background: var(--color-primary-light);
        }

        .file-input {
            position: absolute;
            opacity: 0;
            width: 100%;
            height: 100%;
            cursor: pointer;
        }

        .file-input-display {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: var(--spacing-xl);
            text-align: center;
            color: var(--text-secondary);
        }

        .file-input-display i {
            font-size: var(--font-size-xxl);
            color: var(--color-primary);
            margin-bottom: var(--spacing-md);
        }

        .file-input-display span {
            font-weight: var(--font-weight-medium);
            margin-bottom: var(--spacing-sm);
        }

        .file-input-display small {
            font-size: var(--font-size-xs);
            color: var(--text-tertiary);
        }

        /* Responsive Design */
        @media (max-width: 1024px) {
            .profile-main {
                margin-left: 0;
            }
            
            .profile-grid {
                grid-template-columns: 1fr;
            }
            
            .form-grid {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 768px) {
            .profile-hero {
                padding: var(--spacing-lg);
            }
            
            .profile-hero-content {
                flex-direction: column;
                gap: var(--spacing-lg);
                text-align: center;
            }
            
            .profile-avatar-section {
                flex-direction: column;
                text-align: center;
            }
            
            .profile-content {
                padding: var(--spacing-lg);
            }
            
            .card-content {
                padding: var(--spacing-md);
            }
        }

        /* Animations */
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .profile-card {
            animation: fadeInUp 0.6s ease-out;
        }

        .profile-card:nth-child(1) { animation-delay: 0.1s; }
        .profile-card:nth-child(2) { animation-delay: 0.2s; }
        .profile-card:nth-child(3) { animation-delay: 0.3s; }
        .profile-card:nth-child(4) { animation-delay: 0.4s; }
    </style>
</head>
<body class="admin-body" data-theme="<?php echo htmlspecialchars($current_theme); ?>">
    <div class="admin-container">
        <!-- Include Unified Sidebar -->
        <?php include 'includes/sidebar.php'; ?>

        <!-- Main Content -->
        <main class="admin-main profile-main">
            <!-- Profile Header with Hero -->
            <header class="profile-header">
                <div class="profile-hero">
                    <div class="profile-hero-content">
                        <div class="profile-avatar-section">
                            <div class="profile-avatar-container">
                                <img src="../<?php echo htmlspecialchars($profile['admin_avatar']); ?>" 
                                     alt="Profilbild" id="avatar-preview" class="profile-avatar-image">
                                <div class="avatar-upload-overlay">
                                    <i class="fas fa-camera"></i>
                                    <span>Foto ändern</span>
                                </div>
                            </div>
                            <div class="profile-identity">
                                <h1 class="profile-name"><?php echo htmlspecialchars($profile['admin_name']); ?></h1>
                                <p class="profile-role"><?php echo htmlspecialchars($profile['admin_position']); ?></p>
                                <div class="profile-meta">
                                    <span class="meta-item">
                                        <i class="fas fa-building"></i>
                                        <?php echo htmlspecialchars($profile['admin_department']); ?>
                                    </span>
                                    <span class="meta-item">
                                        <i class="fas fa-envelope"></i>
                                        <?php echo htmlspecialchars($profile['admin_email']); ?>
                                    </span>
                                </div>
                            </div>
                        </div>
                        <div class="profile-actions">
                            <button type="submit" form="profile-form" class="btn-primary">
                                <i class="fas fa-save"></i>
                                <span>Änderungen speichern</span>
                            </button>
                        </div>
                    </div>
                </div>
            </header>

            <!-- Profile Content -->
            <div class="profile-content">
                <!-- Success/Error Messages -->
                <?php if (isset($_SESSION['success_message'])): ?>
                    <div class="alert alert-success">
                        <div class="alert-icon">
                            <i class="fas fa-check-circle"></i>
                        </div>
                        <div class="alert-content">
                            <p><?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?></p>
                        </div>
                        <button class="alert-dismiss">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                <?php endif; ?>

                <?php if (isset($_SESSION['error_message'])): ?>
                    <div class="alert alert-error">
                        <div class="alert-icon">
                            <i class="fas fa-exclamation-triangle"></i>
                        </div>
                        <div class="alert-content">
                            <p><?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?></p>
                        </div>
                        <button class="alert-dismiss">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                <?php endif; ?>

                <!-- Profile Cards Grid -->
                <div class="profile-grid">
                    <!-- Personal Information Card -->
                    <div class="profile-card">
                        <div class="card-header">
                            <div class="card-title">
                                <i class="fas fa-user"></i>
                                <h2>Persönliche Informationen</h2>
                            </div>
                        </div>
                        
                        <form method="POST" enctype="multipart/form-data" id="profile-form" class="card-content">
                            <input type="hidden" name="action" value="update_profile">
                            
                            <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 class="form-input">
                                </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 class="form-input">
                                </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']); ?>" 
                                           class="form-input">
                                </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']); ?>" 
                                           class="form-input">
                                </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']); ?>" 
                                           class="form-input">
                                </div>
                                
                                <div class="form-group file-input-group">
                                    <label for="admin_avatar_file">Profilbild</label>
                                    <div class="file-input-wrapper">
                                        <input type="file" id="admin_avatar_file" name="admin_avatar_file" 
                                               accept="image/*" class="file-input">
                                        <div class="file-input-display">
                                            <i class="fas fa-cloud-upload-alt"></i>
                                            <span>Foto auswählen oder hierher ziehen</span>
                                            <small>Max. 5MB, JPG/PNG empfohlen</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="form-group bio-group">
                                <label for="admin_bio">Über mich</label>
                                <textarea id="admin_bio" name="admin_bio" rows="4" 
                                          placeholder="Erzählen Sie etwas über sich..." 
                                          class="form-textarea"><?php echo htmlspecialchars($profile['admin_bio']); ?></textarea>
                            </div>
                        </form>
                    </div>

                    <!-- Preferences Card -->
                    <div class="profile-card">
                        <div class="card-header">
                            <div class="card-title">
                                <i class="fas fa-sliders-h"></i>
                                <h2>Einstellungen</h2>
                            </div>
                        </div>
                        
                        <div class="card-content">
                            <div class="form-grid">
                                <div class="form-group">
                                    <label for="admin_language">Sprache</label>
                                    <select id="admin_language" name="admin_language" form="profile-form" class="form-select">
                                        <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" form="profile-form" class="form-select">
                                        <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" form="profile-form" class="form-select">
                                        <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" form="profile-form" class="form-select">
                                        <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>
                    </div>

                    <!-- Security Card -->
                    <div class="profile-card">
                        <div class="card-header">
                            <div class="card-title">
                                <i class="fas fa-shield-alt"></i>
                                <h2>Sicherheit</h2>
                            </div>
                        </div>
                        
                        <div class="card-content">
                            <form method="POST" id="password-form">
                                <input type="hidden" name="action" value="change_password">
                                
                                <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 class="form-input">
                                    </div>
                                    
                                    <div class="form-group">
                                        <label for="new_password">Neues Passwort</label>
                                        <input type="password" id="new_password" name="new_password" 
                                               required minlength="8" class="form-input">
                                    </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" class="form-input">
                                    </div>
                                </div>
                                
                                <div style="margin-top: var(--spacing-lg);">
                                    <button type="submit" class="btn-secondary">
                                        <i class="fas fa-key"></i>
                                        <span>Passwort ändern</span>
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <script src="../assets/js/main.js"></script>
    <script src="assets/js/admin.js"></script>
    <script src="assets/js/unified-sidebar.js"></script>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Update theme form select when theme changes
            const themeSelect = document.getElementById('admin_theme');
            if (themeSelect) {
                const savedTheme = localStorage.getItem('admin-theme') || '<?php echo $current_theme; ?>';
                themeSelect.value = savedTheme;
            }
            
            // Avatar upload handling
            const avatarInput = document.getElementById('admin_avatar_file');
            const avatarPreview = document.getElementById('avatar-preview');
            const avatarContainer = document.querySelector('.profile-avatar-container');
            
            if (avatarInput && avatarPreview) {
                avatarInput.addEventListener('change', function(e) {
                    const file = e.target.files[0];
                    if (file) {
                        const reader = new FileReader();
                        reader.onload = function(e) {
                            avatarPreview.src = e.target.result;
                        };
                        reader.readAsDataURL(file);
                    }
                });
                
                if (avatarContainer) {
                    avatarContainer.addEventListener('click', function() {
                        avatarInput.click();
                    });
                }
            }
            
            // Password validation
            const newPassword = document.getElementById('new_password');
            const confirmPassword = document.getElementById('confirm_password');
            
            function validatePassword() {
                if (newPassword && confirmPassword) {
                    if (newPassword.value !== confirmPassword.value) {
                        confirmPassword.setCustomValidity('Passwörter stimmen nicht überein');
                    } else {
                        confirmPassword.setCustomValidity('');
                    }
                }
            }
            
            if (newPassword && confirmPassword) {
                newPassword.addEventListener('input', validatePassword);
                confirmPassword.addEventListener('input', validatePassword);
            }
            
            // Alert dismissal
            const alertDismissButtons = document.querySelectorAll('.alert-dismiss');
            alertDismissButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const alert = this.closest('.alert');
                    alert.style.opacity = '0';
                    alert.style.transform = 'translateY(-10px)';
                    setTimeout(() => {
                        alert.remove();
                    }, 300);
                });
            });
            
            // File input enhancement
            const fileInputWrapper = document.querySelector('.file-input-wrapper');
            const fileInput = document.querySelector('.file-input');
            const fileInputDisplay = document.querySelector('.file-input-display span');
            
            if (fileInput && fileInputDisplay) {
                fileInput.addEventListener('change', function() {
                    if (this.files && this.files[0]) {
                        fileInputDisplay.textContent = this.files[0].name;
                    } else {
                        fileInputDisplay.textContent = 'Foto auswählen oder hierher ziehen';
                    }
                });
                
                // Drag and drop
                if (fileInputWrapper) {
                    ['dragover', 'dragenter'].forEach(eventName => {
                        fileInputWrapper.addEventListener(eventName, function(e) {
                            e.preventDefault();
                            this.style.borderColor = 'var(--color-primary)';
                            this.style.background = 'var(--color-primary-light)';
                        });
                    });
                    
                    ['dragleave', 'dragend'].forEach(eventName => {
                        fileInputWrapper.addEventListener(eventName, function(e) {
                            e.preventDefault();
                            this.style.borderColor = 'var(--border-color)';
                            this.style.background = 'transparent';
                        });
                    });
                    
                    fileInputWrapper.addEventListener('drop', function(e) {
                        e.preventDefault();
                        this.style.borderColor = 'var(--border-color)';
                        this.style.background = 'transparent';
                        
                        const files = e.dataTransfer.files;
                        if (files.length > 0) {
                            fileInput.files = files;
                            fileInputDisplay.textContent = files[0].name;
                            
                            // Trigger avatar preview
                            const reader = new FileReader();
                            reader.onload = function(e) {
                                if (avatarPreview) {
                                    avatarPreview.src = e.target.result;
                                }
                            };
                            reader.readAsDataURL(files[0]);
                        }
                    });
                }
            }
        });
    </script>
</body>
</html>
