<?php
// views/admin.php - Admin backend console
require_once __DIR__ . '/../auth.php';
require_role('admin');

$success_msg = '';
$error_msg = '';

if (isset($_GET['success'])) {
    if ($_GET['success'] === 'settings') $success_msg = 'Branding-Einstellungen erfolgreich aktualisiert!';
    if ($_GET['success'] === 'license') $success_msg = 'Lizenzen erfolgreich aktualisiert!';
    if ($_GET['success'] === 'user_created') $success_msg = 'Mitglied erfolgreich angelegt!';
    if ($_GET['success'] === 'permissions_updated') $success_msg = 'Berechtigungen erfolgreich gespeichert!';
    if ($_GET['success'] === 'user_deleted') $success_msg = 'Benutzer erfolgreich gelöscht!';
    if ($_GET['success'] === 'visibility') $success_msg = 'Menü-Sichtbarkeit erfolgreich aktualisiert!';
    if ($_GET['success'] === 'role_created') $success_msg = 'Neue Vereinsrolle erfolgreich angelegt!';
    if ($_GET['success'] === 'role_deleted') $success_msg = 'Vereinsrolle erfolgreich gelöscht!';
}

// 1. Save Branding & General Settings
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_settings') {
    $c_name = trim($_POST['club_name'] ?? '');
    $p_color = trim($_POST['primary_color'] ?? '');
    $s_color = trim($_POST['secondary_color'] ?? '');
    $allow_clothing = isset($_POST['allow_clothing_requests']) ? '1' : '0';

    if (!empty($c_name)) {
        set_setting('club_name', $c_name);
        set_setting('primary_color', $p_color);
        set_setting('secondary_color', $s_color);
        set_setting('allow_clothing_requests', $allow_clothing);

        // Font Upload
        if (isset($_FILES['custom_font']) && $_FILES['custom_font']['error'] === UPLOAD_ERR_OK) {
            $font_name = $_FILES['custom_font']['name'];
            $font_tmp = $_FILES['custom_font']['tmp_name'];
            $font_ext = strtolower(pathinfo($font_name, PATHINFO_EXTENSION));
            $font_title = trim($_POST['custom_font_name'] ?? '');
            
            if (empty($font_title)) {
                $font_title = pathinfo($font_name, PATHINFO_FILENAME);
            }
            
            $allowed_font_exts = ['ttf', 'woff', 'woff2', 'otf'];
            if (in_array($font_ext, $allowed_font_exts)) {
                $font_dir = __DIR__ . '/../uploads/fonts';
                if (!file_exists($font_dir)) {
                    mkdir($font_dir, 0777, true);
                }
                
                $clean_filename = preg_replace('/[^a-zA-Z0-9_-]/', '', $font_title) . '.' . $font_ext;
                $dest_path = 'uploads/fonts/' . $clean_filename;
                
                if (move_uploaded_file($font_tmp, __DIR__ . '/../' . $dest_path)) {
                    $fonts = json_decode(get_setting('uploaded_fonts', '[]'), true) ?: [];
                    $fonts[$font_title] = $dest_path;
                    set_setting('uploaded_fonts', json_encode($fonts));
                }
            } else {
                $error_msg = 'Ungültiges Schriftart-Dateiformat. Erlaubt sind TTF, WOFF, WOFF2 und OTF.';
            }
        }

        // Logo Upload
        if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
            $logo_name = $_FILES['logo']['name'];
            $logo_tmp = $_FILES['logo']['tmp_name'];
            $logo_ext = strtolower(pathinfo($logo_name, PATHINFO_EXTENSION));
            
            $allowed_exts = ['png', 'jpg', 'jpeg', 'svg', 'gif'];
            if (in_array($logo_ext, $allowed_exts)) {
                $dest_path = 'uploads/logo.' . $logo_ext;
                
                // Delete old logo
                $old_logo = get_setting('logo_path', '');
                if (!empty($old_logo) && file_exists(__DIR__ . '/../' . $old_logo)) {
                    @unlink(__DIR__ . '/../' . $old_logo);
                }
                
                if (move_uploaded_file($logo_tmp, __DIR__ . '/../' . $dest_path)) {
                    set_setting('logo_path', $dest_path);
                }
            } else {
                $error_msg = 'Ungültiges Logo-Dateiformat. Erlaubt sind JPG, PNG, SVG und GIF.';
            }
        }

        if (empty($error_msg)) {
            header("Location: index.php?view=admin&success=settings");
            exit;
        }
    } else {
        $error_msg = 'Vereinsname darf nicht leer sein.';
    }
}

// 2. Save Module Licenses
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_licenses') {
    set_setting('forum_license', trim($_POST['forum_license'] ?? ''));
    header("Location: index.php?view=admin&success=license");
    exit;
}

// 2.5 Save Menu Visibility
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_menu_visibility') {
    $visibility = $_POST['visibility'] ?? [];
    
    $menus = ['chat', 'forum', 'trainer', 'kassenwart', 'vorstand', 'inventory'];
    $cleaned_visibility = [];
    foreach ($menus as $m) {
        $roles = $visibility[$m] ?? [];
        if (!in_array('admin', $roles)) {
            $roles[] = 'admin';
        }
        $cleaned_visibility[$m] = $roles;
    }
    
    set_setting('menu_visibility', json_encode($cleaned_visibility));
    header("Location: index.php?view=admin&success=visibility");
    exit;
}

// 2.7 Create Custom Role
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'create_custom_role') {
    $role_name = trim($_POST['role_name'] ?? '');
    if (!empty($role_name)) {
        $clean_role = preg_replace('/[^a-zA-Z0-9_\-\s]/', '', $role_name);
        if (!empty($clean_role)) {
            $custom_roles = json_decode(get_setting('custom_roles', '[]'), true) ?: [];
            if (!in_array($clean_role, $custom_roles)) {
                $custom_roles[] = $clean_role;
                set_setting('custom_roles', json_encode($custom_roles));
            }
            header("Location: index.php?view=admin&success=role_created");
            exit;
        }
    }
}

// 2.8 Delete Custom Role
if (isset($_GET['delete_role'])) {
    $role_to_delete = trim($_GET['delete_role']);
    $custom_roles = json_decode(get_setting('custom_roles', '[]'), true) ?: [];
    if (in_array($role_to_delete, $custom_roles)) {
        $custom_roles = array_values(array_diff($custom_roles, [$role_to_delete]));
        set_setting('custom_roles', json_encode($custom_roles));
        header("Location: index.php?view=admin&success=role_deleted");
        exit;
    }
}

// 3. User Creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'create_user') {
    $uname = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $pwd = $_POST['password'] ?? '';
    $fname = trim($_POST['first_name'] ?? '');
    $lname = trim($_POST['last_name'] ?? '');
    $role = $_POST['role'] ?? 'member';

    if (empty($uname) || empty($email) || empty($pwd) || empty($fname) || empty($lname)) {
        $error_msg = 'Bitte füllen Sie alle Benutzer-Felder aus.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error_msg = 'Geben Sie eine gültige E-Mail-Adresse ein.';
    } else {
        try {
            $pdo->beginTransaction();

            $pwd_hash = password_hash($pwd, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO users (username, password_hash, email, first_name, last_name, role) VALUES (:uname, :pwd_hash, :email, :fname, :lname, :role)");
            $stmt->execute([
                ':uname' => $uname,
                ':pwd_hash' => $pwd_hash,
                ':email' => $email,
                ':fname' => $fname,
                ':lname' => $lname,
                ':role' => $role
            ]);
            $new_uid = $pdo->lastInsertId();

            // Permissions entry
            $stmt = $pdo->prepare("INSERT INTO permissions (user_id) VALUES (:user_id)");
            $stmt->execute([':user_id' => $new_uid]);

            $pdo->commit();
            header("Location: index.php?view=admin&success=user_created");
            exit;
        } catch (PDOException $e) {
            $pdo->rollBack();
            $error_msg = 'Fehler beim Anlegen des Benutzers: ' . (strpos($e->getMessage(), 'UNIQUE') !== false ? 'Benutzername oder E-Mail bereits vergeben.' : $e->getMessage());
        }
    }
}

// 4. Update Permissions & Role override
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_permissions') {
    $user_id = intval($_POST['user_id'] ?? 0);
    $role = $_POST['role'] ?? 'member';
    $can_edit = isset($_POST['can_edit_pages']) ? 1 : 0;
    $can_inv = isset($_POST['can_manage_inventory']) ? 1 : 0;
    $can_fin = isset($_POST['can_manage_finance']) ? 1 : 0;

    if ($user_id > 0) {
        try {
            $pdo->beginTransaction();
            // Update role
            $stmt = $pdo->prepare("UPDATE users SET role = :role WHERE id = :id");
            $stmt->execute([':role' => $role, ':id' => $user_id]);

            // Save overrides
            $stmt = $pdo->prepare("INSERT OR REPLACE INTO permissions (user_id, can_edit_pages, can_manage_inventory, can_manage_finance) VALUES (:user_id, :edit, :inv, :fin)");
            $stmt->execute([
                ':user_id' => $user_id,
                ':edit' => $can_edit,
                ':inv' => $can_inv,
                ':fin' => $can_fin
            ]);

            $pdo->commit();
            header("Location: index.php?view=admin&success=permissions_updated");
            exit;
        } catch (PDOException $e) {
            $pdo->rollBack();
            $error_msg = 'Fehler beim Speichern der Rechte: ' . $e->getMessage();
        }
    }
}

// 5. Delete User
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_user') {
    $user_id = intval($_POST['user_id'] ?? 0);
    $current_admin = current_user();

    if ($user_id === intval($current_admin['id'])) {
        $error_msg = 'Sie können Ihren eigenen Admin-Account nicht löschen.';
    } else {
        $stmt = $pdo->prepare("DELETE FROM users WHERE id = :id");
        $stmt->execute([':id' => $user_id]);
        header("Location: index.php?view=admin&success=user_deleted");
        exit;
    }
}

// Fetch all users and overrides
$users_stmt = $pdo->query("SELECT u.*, p.can_edit_pages, p.can_manage_inventory, p.can_manage_finance 
                           FROM users u 
                           LEFT JOIN permissions p ON u.id = p.user_id 
                           ORDER BY u.id ASC");
$all_users = $users_stmt->fetchAll(PDO::FETCH_ASSOC);

// Loaded settings
$allow_clothing_setting = get_setting('allow_clothing_requests', '1');
$forum_license = get_setting('forum_license', '');
?>

<h1 style="font-size: 28px; font-weight: 800; color: var(--secondary); margin-bottom: 24px;">Admin Backend-Konsole</h1>

<?php if (!empty($success_msg)): ?>
    <div class="alert alert-success"><?= htmlspecialchars($success_msg) ?></div>
<?php endif; ?>

<?php if (!empty($error_msg)): ?>
    <div class="alert alert-danger"><?= htmlspecialchars($error_msg) ?></div>
<?php endif; ?>

<div class="grid">
    <!-- Branding & Core Settings -->
    <div class="card">
        <h3 class="card-title">🎨 Vereins-Branding</h3>
        <form method="POST" enctype="multipart/form-data" action="" style="margin-top: 15px;">
            <input type="hidden" name="action" value="save_settings">
            
            <div class="form-group">
                <label for="club_name">Vereinsname</label>
                <input type="text" id="club_name" name="club_name" value="<?= htmlspecialchars($club_name) ?>" required>
            </div>

            <div class="grid" style="grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 0;">
                <div class="form-group">
                    <label for="primary_color">Primärfarbe (Theme)</label>
                    <input type="color" id="primary_color" name="primary_color" value="<?= htmlspecialchars($primary_color) ?>" style="height: 40px; padding: 2px; cursor: pointer;">
                </div>
                <div class="form-group">
                    <label for="secondary_color">Sekundärfarbe (Muted)</label>
                    <input type="color" id="secondary_color" name="secondary_color" value="<?= htmlspecialchars($secondary_color) ?>" style="height: 40px; padding: 2px; cursor: pointer;">
                </div>
            </div>

            <!-- Farbvorlagen Schnellauswahl -->
            <div style="margin-top: 15px; margin-bottom: 20px;">
                <label style="font-size: 12px; font-weight: 600; color: var(--text-muted); display: block; margin-bottom: 8px;">Farbvorlagen (Schnellauswahl):</label>
                <div style="display: flex; flex-wrap: wrap; gap: 10px;">
                    <?php
                    $presets = [
                        ['name' => 'Classic Blau', 'primary' => '#0284c7', 'secondary' => '#0f172a'],
                        ['name' => 'Smaragd Grün', 'primary' => '#10b981', 'secondary' => '#1e293b'],
                        ['name' => 'Feuer Rot', 'primary' => '#ef4444', 'secondary' => '#111827'],
                        ['name' => 'Gelb / Schwarz', 'primary' => '#eab308', 'secondary' => '#0f172a'],
                        ['name' => 'Indigo Violett', 'primary' => '#6366f1', 'secondary' => '#0f172a'],
                        ['name' => 'Sport Orange', 'primary' => '#f97316', 'secondary' => '#1e293b'],
                    ];
                    foreach ($presets as $p):
                    ?>
                        <button type="button" 
                                onclick="applyColorPreset('<?= $p['primary'] ?>', '<?= $p['secondary'] ?>')" 
                                style="background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 20px; padding: 6px 14px; font-size: 11px; font-weight: 600; cursor: pointer; display: flex; align-items: center; gap: 8px; color: var(--text-main); transition: border-color 0.2s;"
                                onmouseover="this.style.borderColor='var(--primary)'"
                                onmouseout="this.style.borderColor='var(--border-color)'">
                            <span style="display: inline-block; width: 12px; height: 12px; border-radius: 50%; background-color: <?= $p['primary'] ?>; border: 1px solid rgba(0,0,0,0.15);"></span>
                            <span style="display: inline-block; width: 12px; height: 12px; border-radius: 50%; background-color: <?= $p['secondary'] ?>; border: 1px solid rgba(0,0,0,0.15); margin-left: -8px;"></span>
                            <?= htmlspecialchars($p['name']) ?>
                        </button>
                    <?php endforeach; ?>
                </div>
            </div>

            <script>
            function applyColorPreset(primary, secondary) {
                document.getElementById('primary_color').value = primary;
                document.getElementById('secondary_color').value = secondary;
            }
            </script>

            <div class="form-group">
                <label for="logo">Vereinslogo hochladen (Empfohlen: Quadratisch, 200x200 px, max. 500 KB)</label>
                <input type="file" id="logo" name="logo">
                <p style="font-size: 11px; color: var(--text-muted); margin-top: 4px;">Erlaubt: PNG, JPG, SVG, GIF</p>
            </div>

            <div class="form-group" style="margin-top: 20px;">
                <label style="display: flex; align-items: center; gap: 10px; font-weight: 500; cursor: pointer;">
                    <input type="checkbox" name="allow_clothing_requests" value="1" <?= $allow_clothing_setting === '1' ? 'checked' : '' ?>>
                    <span>Mitgliedern erlauben, neue Kleidung anzufordern</span>
                </label>
            </div>

            <div style="margin-top: 20px; border-top: 1px solid var(--border-color); padding-top: 15px;">
                <h4 style="font-size: 14px; font-weight: 700; color: var(--secondary); margin-bottom: 10px;">Schriftart hochladen</h4>
                <div class="grid" style="grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 0;">
                    <div class="form-group">
                        <label for="custom_font_name">Name der Schriftart</label>
                        <input type="text" id="custom_font_name" name="custom_font_name" placeholder="z. B. VereinsFont">
                    </div>
                    <div class="form-group">
                        <label for="custom_font">Schriftdatei (.ttf, .woff, .woff2, .otf, max. 2 MB)</label>
                        <input type="file" id="custom_font" name="custom_font">
                    </div>
                </div>
                <?php
                $uploaded_fonts = json_decode(get_setting('uploaded_fonts', '[]'), true) ?: [];
                if (!empty($uploaded_fonts)):
                ?>
                    <div style="margin-top: 10px;">
                        <span style="font-size: 11px; font-weight: 600; color: var(--text-muted); display: block; margin-bottom: 5px;">Installierte Schriftarten:</span>
                        <div style="display: flex; flex-wrap: wrap; gap: 5px;">
                            <?php foreach ($uploaded_fonts as $fname => $fpath): ?>
                                <span style="font-size: 11px; background: #e2e8f0; color: #475569; padding: 2px 8px; border-radius: 10px;"><?= htmlspecialchars($fname) ?></span>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endif; ?>
            </div>

            <button type="submit" class="btn btn-primary" style="width: 100%; margin-top: 20px;">Einstellungen speichern</button>
        </form>
    </div>

    <!-- Upsell Licenses Panel -->
    <div class="card">
        <h3 class="card-title">🔐 Team Mania PRO Module</h3>
        <p style="font-size: 13px; color: var(--text-muted); margin-bottom: 15px; line-height: 1.4;">
            Geben Sie hier Ihre Lizenzschlüssel von <a href="https://team-mania.de" target="_blank" style="color: var(--primary); font-weight: 600;">team-mania.de</a> ein, um die Premium-Module freizuschalten.
        </p>
        
        <form method="POST" action="">
            <input type="hidden" name="action" value="save_licenses">

            <div class="form-group">
                <label for="forum_license">Forum-Modul Lizenzschlüssel</label>
                <input type="text" id="forum_license" name="forum_license" value="<?= htmlspecialchars($forum_license) ?>" placeholder="z. B. FORUM-PRO-XXXX">
                <span style="font-size: 11px; font-weight: 600; color: <?= !empty($forum_license) ? 'var(--success)' : 'var(--danger)' ?>;">
                    Status: <?= !empty($forum_license) ? '✅ AKTIVIERT (Pro-Version)' : '❌ INAKTIV' ?>
                </span>
            </div>

            <button type="submit" class="btn btn-primary" style="width: 100%; margin-top: 20px;">Lizenzen anwenden</button>
        </form>
    </div>
</div>

<!-- Menü-Sichtbarkeit -->
<?php
$visibility_json = get_setting('menu_visibility', '');
$visibility = json_decode($visibility_json, true) ?: [];

$defaults = [
    'chat' => ['admin', 'vorstand', 'trainer', 'materialwart', 'member'],
    'forum' => ['admin', 'vorstand', 'trainer', 'materialwart', 'member'],
    'trainer' => ['admin', 'trainer'],
    'kassenwart' => ['admin', 'kassenwart'],
    'vorstand' => ['admin', 'vorstand'],
    'inventory' => ['admin', 'vorstand', 'trainer', 'materialwart', 'member']
];

$role_labels = [
    'admin' => 'Admin (Immer aktiv)',
    'vorstand' => 'Vorstand',
    'trainer' => 'Trainer',
    'kassenwart' => 'Kassenwart',
    'materialwart' => 'Zeugwart',
    'member' => 'Mitglied'
];

$custom_roles = json_decode(get_setting('custom_roles', '[]'), true) ?: [];
foreach ($custom_roles as $cr) {
    $role_labels[$cr] = $cr;
}

$menu_labels = [
    'chat' => '💬 Chat-Kanäle',
    'forum' => '🗣️ Forum',
    'trainer' => '🏆 Trainer-Zentrale',
    'kassenwart' => '💰 Kassenbuch & Beiträge',
    'vorstand' => '💼 Vorstand & Protokolle',
    'inventory' => '📦 Inventar & Kleidung'
];
?>
<div class="card" style="margin-bottom: 30px;">
    <h3 class="card-title">🗳️ Menü- & Modulsichtbarkeit festlegen</h3>
    <p style="font-size: 13px; color: var(--text-muted); margin-bottom: 20px; line-height: 1.4;">
        Bestimmen Sie, welche Benutzerrollen Zugriff auf die jeweiligen Menüs und Funktionen des Portals haben.
    </p>
    
    <form method="POST" action="">
        <input type="hidden" name="action" value="save_menu_visibility">
        
        <div style="overflow-x: auto;">
            <table class="table" style="min-width: 600px; width: 100%; border-collapse: collapse;">
                <thead>
                    <tr style="border-bottom: 2px solid var(--border-color);">
                        <th style="text-align: left; padding: 10px;">Funktion / Menüpunkt</th>
                        <?php foreach ($role_labels as $role => $label): ?>
                            <th style="text-align: center; padding: 10px; font-size: 12px; font-weight: 600;"><?= htmlspecialchars($label) ?></th>
                        <?php endforeach; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($menu_labels as $menu => $menu_label): ?>
                        <tr style="border-bottom: 1px solid var(--border-color);">
                            <td style="font-weight: 600; padding: 12px 10px; color: var(--secondary);"><?= htmlspecialchars($menu_label) ?></td>
                            <?php foreach ($role_labels as $role => $label): 
                                $is_allowed = false;
                                if ($role === 'admin') {
                                    $is_allowed = true;
                                } elseif (isset($visibility[$menu])) {
                                    $is_allowed = in_array($role, $visibility[$menu]);
                                } else {
                                    $is_allowed = in_array($role, $defaults[$menu]);
                                }
                            ?>
                                <td style="text-align: center; padding: 12px 10px;">
                                    <?php if ($role === 'admin'): ?>
                                        <input type="checkbox" name="visibility[<?= $menu ?>][]" value="admin" checked disabled>
                                        <input type="hidden" name="visibility[<?= $menu ?>][]" value="admin">
                                    <?php else: ?>
                                        <input type="checkbox" name="visibility[<?= $menu ?>][]" value="<?= $role ?>" <?= $is_allowed ? 'checked' : '' ?> style="cursor: pointer; width: 16px; height: 16px;">
                                    <?php endif; ?>
                                </td>
                            <?php endforeach; ?>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <button type="submit" class="btn btn-primary" style="margin-top: 20px;">Sichtbarkeit speichern</button>
    </form>
</div>

<!-- Neue Rolle anlegen -->
<div class="card" style="margin-bottom: 30px;">
    <h3 class="card-title">🎭 Neue Vereinsrolle anlegen</h3>
    <p style="font-size: 13px; color: var(--text-muted); margin-bottom: 15px; line-height: 1.4;">
        Erstellen Sie benutzerdefinierte Rollen für Ihren Verein (z. B. Jugendwart, Schiedsrichter, Physiotherapeut). Diese können Sie anschließend den Mitgliedern zuweisen und deren Zugriffsrechte konfigurieren.
    </p>
    
    <form method="POST" action="" style="display: flex; gap: 15px; align-items: flex-end; flex-wrap: wrap;">
        <input type="hidden" name="action" value="create_custom_role">
        <div class="form-group" style="margin-bottom: 0; flex: 1; min-width: 200px;">
            <label for="role_name">Bezeichnung der Rolle</label>
            <input type="text" id="role_name" name="role_name" placeholder="z. B. Jugendwart" required style="width: 100%;">
        </div>
        <button type="submit" class="btn btn-primary" style="height: 42px;">Rolle erstellen</button>
    </form>

    <?php
    $custom_roles = json_decode(get_setting('custom_roles', '[]'), true) ?: [];
    if (!empty($custom_roles)):
    ?>
        <div style="margin-top: 20px; border-top: 1px solid var(--border-color); padding-top: 15px;">
            <span style="font-size: 11px; font-weight: 600; color: var(--text-muted); display: block; margin-bottom: 8px;">Bestehende eigene Rollen (Klicken zum Löschen):</span>
            <div style="display: flex; flex-wrap: wrap; gap: 6px;">
                <?php foreach ($custom_roles as $cr): ?>
                    <a href="index.php?view=admin&delete_role=<?= urlencode($cr) ?>" 
                       onclick="return confirm('Möchten Sie diese Rolle wirklich löschen? Mitglieder mit dieser Rolle werden nicht gelöscht, behalten aber ggf. keine Sonderrechte mehr.')" 
                       style="font-size: 11px; background: #e2e8f0; color: #475569; padding: 4px 10px; border-radius: 12px; text-decoration: none; display: inline-flex; align-items: center; gap: 6px;"
                       onmouseover="this.style.background='#fee2e2'; this.style.color='#ef4444';"
                       onmouseout="this.style.background='#e2e8f0'; this.style.color='#475569';">
                        <?= htmlspecialchars($cr) ?> <span style="font-weight: bold; font-size: 12px;">&times;</span>
                    </a>
                <?php endforeach; ?>
            </div>
        </div>
    <?php endif; ?>
</div>

<!-- User Account Creation -->
<div class="card" style="margin-bottom: 30px;">
    <h3 class="card-title">➕ Neues Mitglied anlegen</h3>
    <form method="POST" action="" style="margin-top: 15px;">
        <input type="hidden" name="action" value="create_user">
        
        <div class="grid" style="grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-bottom: 0;">
            <div class="form-group">
                <label for="first_name">Vorname</label>
                <input type="text" id="first_name" name="first_name" required>
            </div>
            <div class="form-group">
                <label for="last_name">Nachname</label>
                <input type="text" id="last_name" name="last_name" required>
            </div>
            <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>
            </div>
            <div class="form-group">
                <label for="role">Rolle</label>
                <select id="role" name="role" required>
                    <option value="member">Mitglied</option>
                    <option value="trainer">Trainer</option>
                    <option value="kassenwart">Kassenwart</option>
                    <option value="materialwart">Materialwart</option>
                    <option value="vorstand">Vorstand</option>
                    <option value="admin">Admin</option>
                    <?php
                    $custom_roles = json_decode(get_setting('custom_roles', '[]'), true) ?: [];
                    foreach ($custom_roles as $cr):
                    ?>
                        <option value="<?= htmlspecialchars($cr) ?>"><?= htmlspecialchars($cr) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
        
        <button type="submit" class="btn btn-primary" style="margin-top: 10px;">Benutzer erstellen</button>
    </form>
</div>

<!-- Users Roster & Permissions Management -->
<div class="card">
    <h3 class="card-title">👥 Mitgliederliste & Berechtigungen</h3>
    <div class="table-responsive">
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Benutzername / E-Mail</th>
                    <th>Hauptrolle</th>
                    <th>Rechte-Overrides (Für Nicht-Admins)</th>
                    <th>Aktionen</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($all_users as $u): ?>
                    <tr>
                        <form method="POST" action="">
                            <input type="hidden" name="action" value="update_permissions">
                            <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                            
                            <td style="font-weight: 600;">
                                <?= htmlspecialchars($u['first_name'] . ' ' . $u['last_name']) ?>
                            </td>
                            <td>
                                <span style="font-size: 13px; color: var(--text-muted);"><?= htmlspecialchars($u['username']) ?></span><br>
                                <span style="font-size: 12px; color: var(--text-muted);"><?= htmlspecialchars($u['email']) ?></span>
                            </td>
                            <td>
                                <select name="role" style="padding: 6px 10px; font-size: 13px;" onchange="this.form.submit()">
                                    <option value="member" <?= $u['role'] === 'member' ? 'selected' : '' ?>>Mitglied</option>
                                    <option value="trainer" <?= $u['role'] === 'trainer' ? 'selected' : '' ?>>Trainer</option>
                                    <option value="kassenwart" <?= $u['role'] === 'kassenwart' ? 'selected' : '' ?>>Kassenwart</option>
                                    <option value="materialwart" <?= $u['role'] === 'materialwart' ? 'selected' : '' ?>>Materialwart</option>
                                    <option value="vorstand" <?= $u['role'] === 'vorstand' ? 'selected' : '' ?>>Vorstand</option>
                                    <option value="admin" <?= $u['role'] === 'admin' ? 'selected' : '' ?>>Admin</option>
                                    <?php
                                    $custom_roles = json_decode(get_setting('custom_roles', '[]'), true) ?: [];
                                    foreach ($custom_roles as $cr):
                                    ?>
                                        <option value="<?= htmlspecialchars($cr) ?>" <?= $u['role'] === $cr ? 'selected' : '' ?>><?= htmlspecialchars($cr) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                            <td>
                                <?php if ($u['role'] !== 'admin'): ?>
                                    <div style="display: flex; flex-direction: column; gap: 4px; font-size: 12px;">
                                        <label style="display: inline-flex; align-items: center; gap: 6px; font-weight: normal; margin-bottom: 0;">
                                            <input type="checkbox" name="can_edit_pages" value="1" <?= $u['can_edit_pages'] ? 'checked' : '' ?> onchange="this.form.submit()"> Pages editieren
                                        </label>
                                        <label style="display: inline-flex; align-items: center; gap: 6px; font-weight: normal; margin-bottom: 0;">
                                            <input type="checkbox" name="can_manage_inventory" value="1" <?= $u['can_manage_inventory'] ? 'checked' : '' ?> onchange="this.form.submit()"> Inventar verwalten
                                        </label>
                                        <label style="display: inline-flex; align-items: center; gap: 6px; font-weight: normal; margin-bottom: 0;">
                                            <input type="checkbox" name="can_manage_finance" value="1" <?= $u['can_manage_finance'] ? 'checked' : '' ?> onchange="this.form.submit()"> Finanzen verwalten
                                        </label>
                                    </div>
                                <?php else: ?>
                                    <span style="color: var(--success); font-size: 12px; font-weight: 600;">Volle Administrator-Rechte</span>
                                <?php endif; ?>
                            </td>
                        </form>
                        <td>
                            <?php if (intval($u['id']) !== intval(current_user()['id'])): ?>
                                <form method="POST" action="" onsubmit="return confirm('Möchten Sie dieses Mitglied wirklich löschen?')">
                                    <input type="hidden" name="action" value="delete_user">
                                    <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                                    <button type="submit" class="btn btn-danger btn-sm">Löschen</button>
                                </form>
                            <?php else: ?>
                                <span style="font-size: 11px; color: var(--text-muted);">Eigener Account</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
