<?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;
}

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

// Get current user data
$current_user_id = $_SESSION['admin_user_id'] ?? null;
$current_user_name = 'Admin';
$current_user_role = 'admin';
if ($current_user_id) {
    $stmt = $conn->prepare("SELECT full_name, username, role FROM admin_users WHERE id = ?");
    $stmt->execute([$current_user_id]);
    $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
    $current_user_name = $user_data['full_name'] ?? $user_data['username'] ?? 'Benutzer';
    $current_user_role = $user_data['role'] ?? 'admin';
}

// Get user theme preference
$current_theme = 'light';
if ($current_user_id) {
    $stmt = $conn->prepare("SELECT theme FROM admin_users WHERE id = ?");
    $stmt->execute([$current_user_id]);
    $theme_result = $stmt->fetch();
    $current_theme = $theme_result['theme'] ?? 'light';
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['action']) && $_POST['action'] === 'create_user') {
            $username = $_POST['username'];
            $email = $_POST['email'];
            $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
            $role = $_POST['role'];
            $full_name = $_POST['full_name'];
            $department = $_POST['department'];
            $autohaus_id = $_POST['autohaus_id'] ?: null;
            $can_switch_autohaus = isset($_POST['can_switch_autohaus']) ? 1 : 0;
            
            $stmt = $conn->prepare("
                INSERT INTO admin_users (username, email, password_hash, role, full_name, department, autohaus_id, can_switch_autohaus, is_active, needs_dashboard_setup, created_at) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, 1, NOW())
            ");
            $stmt->execute([$username, $email, $password, $role, $full_name, $department, $autohaus_id, $can_switch_autohaus]);
            
            $_SESSION['success_message'] = 'Benutzer erfolgreich erstellt';
            header('Location: users.php');
            exit;
        }
        
        if (isset($_POST['action']) && $_POST['action'] === 'update_user') {
            $user_id = $_POST['user_id'];
            $username = $_POST['username'];
            $email = $_POST['email'];
            $role = $_POST['role'];
            $full_name = $_POST['full_name'];
            $department = $_POST['department'];
            $status = $_POST['status'];
            $autohaus_id = $_POST['autohaus_id'] ?: null;
            $can_switch_autohaus = isset($_POST['can_switch_autohaus']) ? 1 : 0;
            
            $stmt = $conn->prepare("
                UPDATE admin_users 
                SET username = ?, email = ?, role = ?, full_name = ?, department = ?, autohaus_id = ?, can_switch_autohaus = ?, is_active = ?, updated_at = NOW()
                WHERE id = ?
            ");
            $is_active = $status === 'active' ? 1 : 0;
            $stmt->execute([$username, $email, $role, $full_name, $department, $autohaus_id, $can_switch_autohaus, $is_active, $user_id]);
            
            $_SESSION['success_message'] = 'Benutzer erfolgreich aktualisiert';
            header('Location: users.php');
            exit;
        }
        
        if (isset($_POST['action']) && $_POST['action'] === 'delete_user') {
            $user_id = $_POST['user_id'];
            
            $stmt = $conn->prepare("DELETE FROM admin_users WHERE id = ?");
            $stmt->execute([$user_id]);
            
            $_SESSION['success_message'] = 'Benutzer erfolgreich gelöscht';
            header('Location: users.php');
            exit;
        }
    } catch (Exception $e) {
        $_SESSION['error_message'] = 'Fehler: ' . $e->getMessage();
    }
}

// Get all users with autohaus information
$stmt = $conn->prepare("
    SELECT u.*, a.name as autohaus_name, a.short_name as autohaus_short_name
    FROM admin_users u
    LEFT JOIN autohaus a ON u.autohaus_id = a.id
    ORDER BY u.created_at DESC
");
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get all autohauser for forms
$stmt = $conn->prepare("SELECT * FROM autohaus WHERE is_active = 1 ORDER BY name ASC");
$stmt->execute();
$autohauser = $stmt->fetchAll();

?>

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Benutzerverwaltung - 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&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">
        <!-- Include Unified Sidebar -->
        <?php include 'includes/sidebar.php'; ?>

        <!-- Main Content -->
        <main class="admin-main">
            <!-- Header -->
            <header class="admin-header">
                <div class="header-content">
                    <h1><i class="fas fa-users"></i> Benutzerverwaltung</h1>
                </div>
            </header>

            <!-- Content -->
            <div class="admin-content">
                <!-- Action Bar -->
                <div class="action-bar">
                    <div class="action-bar-content">
                        <div class="action-bar-left">
                            <h2>Alle Benutzer</h2>
                            <span class="user-count"><?php echo count($users); ?> Benutzer</span>
                        </div>
                        <div class="action-bar-right">
                            <button class="btn btn-primary btn-large" onclick="openCreateUserModal()">
                                <i class="fas fa-plus"></i>
                                <span>Neuer Benutzer</span>
                            </button>
                        </div>
                    </div>
                </div>

                <?php if (isset($_SESSION['success_message'])): ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle"></i>
                        <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
                    </div>
                <?php endif; ?>

                <?php if (isset($_SESSION['error_message'])): ?>
                    <div class="alert alert-error">
                        <i class="fas fa-exclamation-circle"></i>
                        <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
                    </div>
                <?php endif; ?>

                <!-- Users Table -->
                <div class="users-table-container">
                    <table class="users-table">
                        <thead>
                            <tr>
                                <th>Benutzer</th>
                                <th>E-Mail</th>
                                <th>Rolle</th>
                                <th>Autohaus</th>
                                <th>Abteilung</th>
                                <th>Status</th>
                                <th>Erstellt</th>
                                <th>Aktionen</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($users as $user): ?>
                            <tr>
                                <td>
                                    <div class="user-info">
                                        <div class="user-avatar">
                                            <i class="fas fa-user"></i>
                                        </div>
                                        <div class="user-details">
                                            <div class="user-name"><?php echo htmlspecialchars($user['full_name']); ?></div>
                                            <div class="user-username">@<?php echo htmlspecialchars($user['username']); ?></div>
                                        </div>
                                    </div>
                                </td>
                                <td><?php echo htmlspecialchars($user['email']); ?></td>
                                <td>
                                    <span class="role-badge role-<?php echo $user['role']; ?>">
                                        <?php echo ucfirst($user['role']); ?>
                                    </span>
                                </td>
                                <td>
                                    <?php if ($user['autohaus_name']): ?>
                                        <span class="autohaus-badge">
                                            <i class="fas fa-building"></i>
                                            <?php echo htmlspecialchars($user['autohaus_name']); ?>
                                        </span>
                                    <?php else: ?>
                                        <span class="text-muted">Kein Autohaus</span>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo htmlspecialchars($user['department']); ?></td>
                                <td>
                                    <span class="status-badge status-<?php echo $user['is_active'] ? 'active' : 'inactive'; ?>">
                                        <?php echo $user['is_active'] ? 'Aktiv' : 'Inaktiv'; ?>
                                    </span>
                                </td>
                                <td><?php echo date('d.m.Y', strtotime($user['created_at'])); ?></td>
                                <td>
                                    <div class="action-buttons">
                                        <button class="btn btn-sm btn-secondary" onclick="editUser(<?php echo $user['id']; ?>)">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="btn btn-sm btn-danger" onclick="deleteUser(<?php echo $user['id']; ?>)">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </main>
    </div>

    <!-- Create User Modal -->
    <div id="createUserModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Neuen Benutzer erstellen</h3>
                <button class="modal-close" onclick="closeCreateUserModal()">&times;</button>
            </div>
            <form method="POST" class="modal-form">
                <input type="hidden" name="action" value="create_user">
                <div class="form-grid">
                    <div class="form-group">
                        <label for="username">Benutzername</label>
                        <input type="text" id="username" name="username" required>
                    </div>
                    <div class="form-group">
                        <label for="email">E-Mail</label>
                        <input type="email" id="email" name="email" required>
                    </div>
                    <div class="form-group">
                        <label for="password">Passwort</label>
                        <input type="password" id="password" name="password" required minlength="8">
                    </div>
                    <div class="form-group">
                        <label for="full_name">Vollständiger Name</label>
                        <input type="text" id="full_name" name="full_name" required>
                    </div>
                    <div class="form-group">
                        <label for="role">Rolle</label>
                        <select id="role" name="role" required>
                            <option value="admin">Administrator</option>
                            <option value="manager">Manager</option>
                            <option value="employee">Mitarbeiter</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="autohaus_id">Autohaus</label>
                        <select id="autohaus_id" name="autohaus_id">
                            <option value="">Kein Autohaus zugeordnet</option>
                            <?php foreach ($autohauser as $autohaus): ?>
                                <option value="<?php echo $autohaus['id']; ?>">
                                    <?php echo htmlspecialchars($autohaus['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="department">Abteilung</label>
                        <input type="text" id="department" name="department">
                    </div>
                    <div class="form-group full-width">
                        <label class="checkbox-label">
                            <input type="checkbox" name="can_switch_autohaus" value="1">
                            <span>Kann zwischen Autohäusern wechseln (nur für Admins)</span>
                        </label>
                    </div>
                </div>
                <div class="modal-actions">
                    <button type="button" class="btn btn-secondary" onclick="closeCreateUserModal()">Abbrechen</button>
                    <button type="submit" class="btn btn-primary">Erstellen</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Edit User Modal -->
    <div id="editUserModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Benutzer bearbeiten</h3>
                <button class="modal-close" onclick="closeEditUserModal()">&times;</button>
            </div>
            <form method="POST" class="modal-form">
                <input type="hidden" name="action" value="update_user">
                <input type="hidden" name="user_id" id="edit_user_id">
                <div class="form-grid">
                    <div class="form-group">
                        <label for="edit_username">Benutzername</label>
                        <input type="text" id="edit_username" name="username" required>
                    </div>
                    <div class="form-group">
                        <label for="edit_email">E-Mail</label>
                        <input type="email" id="edit_email" name="email" required>
                    </div>
                    <div class="form-group">
                        <label for="edit_full_name">Vollständiger Name</label>
                        <input type="text" id="edit_full_name" name="full_name" required>
                    </div>
                    <div class="form-group">
                        <label for="edit_role">Rolle</label>
                        <select id="edit_role" name="role" required>
                            <option value="admin">Administrator</option>
                            <option value="manager">Manager</option>
                            <option value="employee">Mitarbeiter</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="edit_autohaus_id">Autohaus</label>
                        <select id="edit_autohaus_id" name="autohaus_id">
                            <option value="">Kein Autohaus zugeordnet</option>
                            <?php foreach ($autohauser as $autohaus): ?>
                                <option value="<?php echo $autohaus['id']; ?>">
                                    <?php echo htmlspecialchars($autohaus['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="edit_department">Abteilung</label>
                        <input type="text" id="edit_department" name="department">
                    </div>
                    <div class="form-group">
                        <label for="edit_status">Status</label>
                        <select id="edit_status" name="status" required>
                            <option value="active">Aktiv</option>
                            <option value="inactive">Inaktiv</option>
                        </select>
                    </div>
                    <div class="form-group full-width">
                        <label class="checkbox-label">
                            <input type="checkbox" name="can_switch_autohaus" id="edit_can_switch_autohaus" value="1">
                            <span>Kann zwischen Autohäusern wechseln (nur für Admins)</span>
                        </label>
                    </div>
                </div>
                <div class="modal-actions">
                    <button type="button" class="btn btn-secondary" onclick="closeEditUserModal()">Abbrechen</button>
                    <button type="submit" class="btn btn-primary">Aktualisieren</button>
                </div>
            </form>
        </div>
    </div>

    <script src="../assets/js/main.js"></script>
    <script src="assets/js/admin.js"></script>
    
    <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 */
        .admin-main {
            margin-left: 280px;
            transition: margin-left var(--transition-normal);
            min-height: 100vh;
            background: var(--surface-secondary);
        }

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

        /* Header */
        .admin-header {
            background: var(--surface-primary);
            border-bottom: 1px solid var(--border-color);
            padding: var(--spacing-xl);
        }

        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            max-width: 1200px;
            margin: 0 auto;
        }

        .admin-header h1 {
            font-size: var(--font-size-xl);
            font-weight: var(--font-weight-bold);
            color: var(--text-primary);
            display: flex;
            align-items: center;
            gap: var(--spacing-md);
        }

        .admin-header h1 i {
            color: var(--color-primary);
        }

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

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

        /* Action Bar */
        .action-bar {
            background: var(--surface-primary);
            border-radius: var(--border-radius-large);
            border: 1px solid var(--border-color);
            box-shadow: var(--shadow-sm);
            margin-bottom: var(--spacing-xl);
            transition: all var(--transition-normal);
        }

        .action-bar:hover {
            box-shadow: var(--shadow-md);
        }

        .action-bar-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: var(--spacing-xl);
        }

        .action-bar-left {
            display: flex;
            flex-direction: column;
            gap: var(--spacing-xs);
        }

        .action-bar-left h2 {
            font-size: var(--font-size-xl);
            font-weight: var(--font-weight-bold);
            color: var(--text-primary);
            margin: 0;
        }

        .user-count {
            font-size: var(--font-size-sm);
            color: var(--text-tertiary);
            font-weight: var(--font-weight-medium);
        }

        .action-bar-right {
            display: flex;
            gap: var(--spacing-md);
        }

        .btn-large {
            padding: var(--spacing-md) var(--spacing-xl);
            font-size: var(--font-size-md);
            font-weight: var(--font-weight-semibold);
            border-radius: var(--border-radius);
            box-shadow: var(--shadow-md);
        }

        .btn-large:hover {
            transform: translateY(-3px);
            box-shadow: var(--shadow-lg);
        }

        /* 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);
        }

        /* Users Table Container */
        .users-table-container {
            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);
        }

        .users-table-container:hover {
            box-shadow: var(--shadow-md);
        }

        .users-table {
            width: 100%;
            border-collapse: collapse;
        }

        .users-table th,
        .users-table td {
            padding: var(--spacing-lg);
            text-align: left;
            border-bottom: 1px solid var(--border-color);
        }

        .users-table th {
            background: var(--surface-secondary);
            font-weight: var(--font-weight-semibold);
            color: var(--text-primary);
            font-size: var(--font-size-sm);
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }

        .users-table tbody tr {
            transition: all var(--transition-normal);
        }

        .users-table tbody tr:hover {
            background: var(--surface-secondary);
            transform: translateX(4px);
        }

        /* User Info */
        .user-info {
            display: flex;
            align-items: center;
            gap: var(--spacing-md);
        }

        .user-avatar {
            width: 48px;
            height: 48px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--color-primary), var(--color-primary-hover));
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: var(--font-size-lg);
            font-weight: var(--font-weight-semibold);
            box-shadow: var(--shadow-sm);
        }

        .user-details {
            display: flex;
            flex-direction: column;
            gap: var(--spacing-xs);
        }

        .user-name {
            font-weight: var(--font-weight-semibold);
            color: var(--text-primary);
            font-size: var(--font-size-md);
        }

        .user-username {
            font-size: var(--font-size-sm);
            color: var(--text-tertiary);
            font-weight: var(--font-weight-medium);
        }

        /* Badges */
        .role-badge {
            padding: var(--spacing-sm) var(--spacing-md);
            border-radius: var(--border-radius-large);
            font-size: var(--font-size-xs);
            font-weight: var(--font-weight-bold);
            text-transform: uppercase;
            letter-spacing: 0.05em;
            box-shadow: var(--shadow-sm);
            transition: all var(--transition-normal);
        }

        .role-badge:hover {
            transform: translateY(-1px);
            box-shadow: var(--shadow-md);
        }

        .role-admin {
            background: linear-gradient(135deg, #FF3B30, #D70015);
            color: white;
        }

        .role-manager {
            background: linear-gradient(135deg, #FF9500, #FF6B00);
            color: white;
        }

        .role-employee {
            background: linear-gradient(135deg, var(--apple-gray-5), var(--apple-gray-6));
            color: white;
        }

        .autohaus-badge {
            display: inline-flex;
            align-items: center;
            gap: var(--spacing-sm);
            padding: var(--spacing-sm) var(--spacing-md);
            background: var(--color-primary-light);
            color: var(--color-primary);
            border-radius: var(--border-radius-large);
            font-size: var(--font-size-xs);
            font-weight: var(--font-weight-semibold);
            box-shadow: var(--shadow-sm);
            transition: all var(--transition-normal);
        }

        .autohaus-badge:hover {
            transform: translateY(-1px);
            box-shadow: var(--shadow-md);
        }

        .autohaus-badge i {
            font-size: var(--font-size-xs);
        }

        .text-muted {
            color: var(--text-tertiary);
            font-style: italic;
            font-size: var(--font-size-sm);
        }

        .status-badge {
            padding: var(--spacing-sm) var(--spacing-md);
            border-radius: var(--border-radius-large);
            font-size: var(--font-size-xs);
            font-weight: var(--font-weight-bold);
            text-transform: uppercase;
            letter-spacing: 0.05em;
            box-shadow: var(--shadow-sm);
            transition: all var(--transition-normal);
        }

        .status-badge:hover {
            transform: translateY(-1px);
            box-shadow: var(--shadow-md);
        }

        .status-active {
            background: linear-gradient(135deg, var(--color-success), #28A745);
            color: white;
        }

        .status-inactive {
            background: linear-gradient(135deg, var(--color-error), #DC3545);
            color: white;
        }

        /* Action Buttons */
        .action-buttons {
            display: flex;
            gap: var(--spacing-sm);
        }

        .btn {
            padding: var(--spacing-sm) var(--spacing-md);
            border: none;
            border-radius: var(--border-radius);
            font-size: var(--font-size-sm);
            font-weight: var(--font-weight-semibold);
            cursor: pointer;
            transition: all var(--transition-normal);
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: var(--spacing-sm);
            position: relative;
            overflow: hidden;
        }

        .btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
            transition: left 0.5s;
        }

        .btn:hover::before {
            left: 100%;
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--color-primary), var(--color-primary-hover));
            color: white;
            box-shadow: var(--shadow-sm);
        }

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

        .btn-secondary {
            background: linear-gradient(135deg, var(--apple-gray-5), var(--apple-gray-6));
            color: white;
            box-shadow: var(--shadow-sm);
        }

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

        .btn-danger {
            background: linear-gradient(135deg, var(--color-error), #DC3545);
            color: white;
            box-shadow: var(--shadow-sm);
        }

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

        .btn-sm {
            padding: var(--spacing-xs) var(--spacing-sm);
            font-size: var(--font-size-xs);
        }

        /* Modal System */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            backdrop-filter: blur(10px);
        }

        .modal-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: var(--surface-primary);
            border-radius: var(--border-radius-large);
            border: 1px solid var(--border-color);
            width: 90%;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: var(--shadow-xl);
            animation: modalSlideIn 0.3s ease-out;
        }

        @keyframes modalSlideIn {
            from {
                opacity: 0;
                transform: translate(-50%, -60%);
            }
            to {
                opacity: 1;
                transform: translate(-50%, -50%);
            }
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: var(--spacing-xl);
            border-bottom: 1px solid var(--border-color);
            background: var(--surface-secondary);
        }

        .modal-header h3 {
            margin: 0;
            color: var(--text-primary);
            font-size: var(--font-size-lg);
            font-weight: var(--font-weight-semibold);
        }

        .modal-close {
            background: none;
            border: none;
            font-size: var(--font-size-xl);
            cursor: pointer;
            color: var(--text-tertiary);
            transition: color var(--transition-fast);
            padding: var(--spacing-sm);
            border-radius: var(--border-radius);
        }

        .modal-close:hover {
            color: var(--text-primary);
            background: var(--surface-tertiary);
        }

        .modal-form {
            padding: var(--spacing-xl);
        }

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

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

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

        .form-group input,
        .form-group select {
            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-group input:focus,
        .form-group select:focus {
            outline: none;
            border-color: var(--color-primary);
            box-shadow: 0 0 0 3px var(--color-primary-light);
        }

        .checkbox-label {
            display: flex;
            align-items: center;
            gap: var(--spacing-sm);
            cursor: pointer;
            font-weight: var(--font-weight-medium);
        }

        .checkbox-label input[type="checkbox"] {
            margin: 0;
            transform: scale(1.2);
        }

        .modal-actions {
            display: flex;
            justify-content: flex-end;
            gap: var(--spacing-md);
        }

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

        @media (max-width: 768px) {
            .admin-header {
                padding: var(--spacing-lg);
            }
            
            .header-content {
                flex-direction: column;
                gap: var(--spacing-lg);
                text-align: center;
            }
            
            .admin-content {
                padding: var(--spacing-lg);
            }
            
            .action-bar-content {
                flex-direction: column;
                gap: var(--spacing-lg);
                text-align: center;
            }
            
            .action-bar-right {
                width: 100%;
                justify-content: center;
            }
            
            .btn-large {
                width: 100%;
                justify-content: center;
            }
            
            .modal-content {
                width: 95%;
            }
            
            .modal-form {
                padding: var(--spacing-lg);
            }
        }
    </style>
    
    <script>
        function openCreateUserModal() {
            document.getElementById('createUserModal').style.display = 'block';
        }
        
        function closeCreateUserModal() {
            document.getElementById('createUserModal').style.display = 'none';
        }
        
        function editUser(userId) {
            // Lade Benutzerdaten
            fetch(`api/get_user.php?id=${userId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const user = data.user;
                        
                        // Fülle das Edit-Formular
                        document.getElementById('edit_user_id').value = user.id;
                        document.getElementById('edit_username').value = user.username;
                        document.getElementById('edit_email').value = user.email;
                        document.getElementById('edit_full_name').value = user.full_name;
                        document.getElementById('edit_role').value = user.role;
                        document.getElementById('edit_autohaus_id').value = user.autohaus_id || '';
                        document.getElementById('edit_department').value = user.department;
                        document.getElementById('edit_status').value = user.is_active ? 'active' : 'inactive';
                        document.getElementById('edit_can_switch_autohaus').checked = user.can_switch_autohaus == 1;
                        
                        // Zeige das Edit-Modal
                        document.getElementById('editUserModal').style.display = 'block';
                    } else {
                        alert('Fehler beim Laden der Benutzerdaten: ' + data.error);
                    }
                })
                .catch(error => {
                    console.error('Fehler:', error);
                    alert('Fehler beim Laden der Benutzerdaten');
                });
        }
        
        function closeEditUserModal() {
            document.getElementById('editUserModal').style.display = 'none';
        }
        
        function deleteUser(userId) {
            if (confirm('Möchten Sie diesen Benutzer wirklich löschen?')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="delete_user">
                    <input type="hidden" name="user_id" value="${userId}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }
        
        // Close modal when clicking outside
        window.onclick = function(event) {
            const modal = document.getElementById('createUserModal');
            if (event.target === modal) {
                closeCreateUserModal();
            }
        }
        
        // User menu toggle
        document.addEventListener('DOMContentLoaded', function() {
            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');
                    }
                });
            }
        });
    </script>
    
    <script src="../assets/js/main.js"></script>
    <script src="assets/js/admin.js"></script>
    <script src="assets/js/unified-sidebar.js"></script>
    
</body>
</html>
