<?php
// admin_users.php

require_once __DIR__ . '/lib/bootstrap.php';

// 1) Zugriffskontrolle – nur ADMIN
if (empty($_SESSION['user_id']) || empty($_SESSION['user_roles']) || !in_array('ADMIN', $_SESSION['user_roles'], true)) {
    die("Zugriff verweigert. Nur Administratoren dürfen diese Seite sehen.");
}

$conn = db_connect();

// 2) Aktion: Benutzer löschen
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_user_id'])) {
    $deleteId = (int)$_POST['delete_user_id'];
    
    // Vermeide Selbstlöschung zur Sicherheit
    if ($deleteId !== (int)$_SESSION['user_id']) {
        // Zunächst Abhängigkeiten wie Rollen löschen
        $conn->query("DELETE FROM userRoles WHERE userID = $deleteId");
        
        $delStmt = $conn->prepare("DELETE FROM users WHERE userID = ?");
        $delStmt->bind_param("i", $deleteId);
        $delStmt->execute();
        $delStmt->close();
        
        $successMsg = "Benutzer erfolgreich gelöscht.";
    } else {
        $errorMsg = "Du kannst dich nicht selbst löschen.";
    }
}

// 2b) Aktion: Rollen aktualisieren
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_all_roles'])) {
    $usersRolesData = isset($_POST['user_roles']) && is_array($_POST['user_roles']) ? $_POST['user_roles'] : [];
    $submittedUsers = isset($_POST['submitted_users']) && is_array($_POST['submitted_users']) ? $_POST['submitted_users'] : [];
    
    foreach ($submittedUsers as $uId) {
        $updateId = (int)$uId;
        
        if ($updateId === (int)$_SESSION['user_id']) {
            continue;
        }

        $selectedRole = isset($usersRolesData[$updateId]) ? $usersRolesData[$updateId] : '';
        
        $delStmt = $conn->prepare("DELETE FROM userRoles WHERE userID = ?");
        $delStmt->bind_param("i", $updateId);
        $delStmt->execute();
        $delStmt->close();
        
        if (!empty($selectedRole)) {
            $insStmt = $conn->prepare("INSERT INTO userRoles (userID, roleID) VALUES (?, ?)");
            $roleIdInt = (int)$selectedRole;
            $insStmt->bind_param("ii", $updateId, $roleIdInt);
            $insStmt->execute();
            $insStmt->close();
        }
    }
    $successMsg = "Rollen erfolgreich aktualisiert.";
}

// 2c) Alle verfügbaren Rollen laden
$allRoles = [];
$rolesQuery = $conn->query("SELECT roleID, name FROM roles ORDER BY name ASC");
if ($rolesQuery) {
    while ($r = $rolesQuery->fetch_assoc()) {
        $allRoles[] = $r;
    }
}

// 3) Alle Benutzer laden (mit Suche)
$searchQuery = isset($_GET['search']) ? trim($_GET['search']) : '';
$searchParam = '%' . $searchQuery . '%';
$filterRole = isset($_GET['role']) ? (int)$_GET['role'] : 0;

$sql = "
    SELECT u.userID, u.email, u.displayname, u.profilePicture, u.isActive,
           GROUP_CONCAT(ur.roleID) as roleIDs
    FROM users u
    LEFT JOIN userRoles ur ON u.userID = ur.userID
";

$whereClauses = [];
$types = "";
$params = [];

if ($searchQuery !== '') {
    $whereClauses[] = "(u.displayname LIKE ? OR u.email LIKE ?)";
    $types .= "ss";
    $params[] = $searchParam;
    $params[] = $searchParam;
}

if ($filterRole > 0) {
    // Da wir einen LEFT JOIN mit GROUP_CONCAT haben und auf Rollen filtern wollen,
    // können wir als einfache Lösung einen Subselect für EXISTS machen, damit
    // alle Rollen des Benutzers in GROUP_CONCAT erhalten bleiben, 
    // aber nur Nutzer gezeigt werden, die auch die geforderte Rolle haben.
    $whereClauses[] = "EXISTS (SELECT 1 FROM userRoles sub_ur WHERE sub_ur.userID = u.userID AND sub_ur.roleID = ?)";
    $types .= "i";
    $params[] = $filterRole;
}

if (!empty($whereClauses)) {
    $sql .= " WHERE " . implode(" AND ", $whereClauses);
}

$sql .= " GROUP BY u.userID ORDER BY u.userID ASC";

$stmtUsers = $conn->prepare($sql);
if (!empty($params)) {
    $stmtUsers->bind_param($types, ...$params);
}
$stmtUsers->execute();
$usersResult = $stmtUsers->get_result();

$formActionParams = [];
if ($searchQuery !== '') $formActionParams['search'] = $searchQuery;
if ($filterRole > 0) $formActionParams['role'] = $filterRole;

$formActionUrl = "admin_users.php";
if (!empty($formActionParams)) {
    $formActionUrl .= "?" . http_build_query($formActionParams);
}

?>

<?php include 'header.php'; ?>

<main class="auth" role="main">
    <section class="auth__grid" style="display: block; max-width: 95%; width: max-content; margin: 40px auto; overflow-x: auto;">
        <div class="auth__card" style="width: 100%; min-width: max-content;">
            <header class="auth__header">
                <h1 class="auth__title">Benutzerverwaltung</h1>
                <p style="text-align: center; color: #94a3b8; font-size: 0.9rem; margin-top: 5px;">Hier siehst du alle registrierten Benutzer.</p>
            </header>

            <?php if (!empty($successMsg)): ?>
                <div class="auth__message auth__message--success" style="color: #4ade80; background: #064e3b; padding: 10px; border-radius: 4px; margin-bottom: 15px; text-align: center;"><?= htmlspecialchars($successMsg) ?></div>
            <?php endif; ?>
            <?php if (!empty($errorMsg)): ?>
                <div class="auth__message auth__message--error" style="color: #f87171; background: #7f1d1d; padding: 10px; border-radius: 4px; margin-bottom: 15px; text-align: center;"><?= htmlspecialchars($errorMsg) ?></div>
            <?php endif; ?>

            <form method="get" action="admin_users.php" style="margin-bottom: 20px; display: flex; gap: 10px; align-items: center; flex-wrap: wrap;">
                <input type="text" name="search" placeholder="Suche nach Name oder E-Mail..." value="<?= htmlspecialchars($searchQuery) ?>" style="flex: 1; min-width: 200px; background: #0f172a; color: #f8fafc; border: 1px solid #334155; padding: 10px; border-radius: 4px; font-size: 0.95rem;">
                
                <select name="role" style="background: #0f172a; color: #f8fafc; border: 1px solid #334155; padding: 10px; border-radius: 4px; font-size: 0.95rem;">
                    <option value="0">Alle Rollen</option>
                    <?php foreach ($allRoles as $role): ?>
                        <option value="<?= $role['roleID'] ?>" <?= $filterRole === (int)$role['roleID'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($role['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>

                <button type="submit" class="auth__submit" style="width: auto; padding: 10px 16px; margin: 0; background-color: #3b82f6;">Filtern</button>
                <?php if ($searchQuery !== '' || $filterRole > 0): ?>
                    <a href="admin_users.php" style="color: #94a3b8; text-decoration: none; padding: 10px; font-size: 0.9rem;">Zurücksetzen</a>
                <?php endif; ?>
            </form>

            <form method="post" action="<?= htmlspecialchars($formActionUrl) ?>">
                <div style="display: flex; justify-content: flex-end; margin-top: 10px;">
                    <button type="submit" name="update_all_roles" value="1" style="background-color: #3b82f6; color: white; border: none; padding: 10px 16px; border-radius: 4px; cursor: pointer; font-weight: bold; font-size: 0.9rem;">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: middle; margin-right: 5px;">
                            <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"></path>
                            <polyline points="17 21 17 13 7 13 7 21"></polyline>
                            <polyline points="7 3 7 8 15 8"></polyline>
                        </svg>
                        Alle Rollen speichern
                    </button>
                </div>


                <div style="margin-top: 20px;">
                    <table style="width: 100%; border-collapse: collapse; text-align: left; color: #f8fafc;">
                        <thead>
                            <tr style="border-bottom: 2px solid #334155;">
                                <th style="padding: 12px 10px;">ID</th>
                                <th style="padding: 12px 10px;">Profil</th>
                                <th style="padding: 12px 10px;">Name</th>
                                <th style="padding: 12px 10px;">E-Mail</th>
                                <th style="padding: 12px 10px; width: 15%;">Aktuelle Rollen</th>
                                <th style="padding: 12px 10px; width: 25%;">Rollen zuweisen</th>
                                <th style="padding: 12px 10px;">Aktionen</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($user = $usersResult->fetch_assoc()): ?>
                                <?php 
                                $userRoles = !empty($user['roleIDs']) ? explode(',', $user['roleIDs']) : []; 
                                $isSelf = (int)$user['userID'] === (int)$_SESSION['user_id'];
                                ?>
                                <tr style="border-bottom: 1px solid #1e293b;">
                                    <td style="padding: 12px 10px;"><?= $user['userID'] ?></td>
                                    <td style="padding: 12px 10px;">
                                        <img src="<?= !empty($user['profilePicture']) ? htmlspecialchars($user['profilePicture']) : 'assets/images/placeholder.png' ?>" 
                                             alt="Profil" style="width: 40px; height: 40px; border-radius: 50%; object-fit: cover; display: block;">
                                    </td>
                                    <td style="padding: 12px 10px;"><?= htmlspecialchars($user['displayname']) ?></td>
                                    <td style="padding: 12px 10px; white-space: nowrap;"><?= htmlspecialchars($user['email']) ?></td>
                                    
                                    <td style="padding: 12px 10px;">
                                        <div style="display: flex; flex-wrap: wrap; gap: 5px;">
                                            <?php foreach ($allRoles as $role): ?>
                                                <?php if (in_array($role['roleID'], $userRoles)): ?>
                                                    <span style="background-color: #065f46; border: 1px solid #10b981; color: #a7f3d0; padding: 2px 8px; border-radius: 9999px; font-size: 0.75rem; font-weight: bold;"><?= htmlspecialchars($role['name']) ?></span>
                                                <?php endif; ?>
                                            <?php endforeach; ?>
                                            <?php if (empty($userRoles)): ?>
                                                <span style="color: #64748b; font-size: 0.75rem; font-style: italic;">Keine</span>
                                            <?php endif; ?>
                                        </div>
                                    </td>

                                    <td style="padding: 12px 10px; min-width: 150px;">
                                        <?php if (!$isSelf): ?>
                                            <input type="hidden" name="submitted_users[]" value="<?= $user['userID'] ?>">
                                            <select name="user_roles[<?= $user['userID'] ?>]" style="background: #0f172a; color: #f8fafc; border: 1px solid #334155; padding: 5px; border-radius: 4px; font-size: 0.85rem; width: 100%;">
                                                <?php foreach ($allRoles as $role): ?>
                                                    <option value="<?= $role['roleID'] ?>" <?= in_array($role['roleID'], $userRoles) ? 'selected' : '' ?>>
                                                        <?= htmlspecialchars($role['name']) ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        <?php else: ?>
                                            <span style="color: #94a3b8; font-size: 0.85rem; font-style: italic;">Du (Gesperrt)</span>
                                        <?php endif; ?>
                                    </td>
                                    
                                    <td style="padding: 12px 10px;">
                                        <?php if (!$isSelf): ?>
                                            <button type="submit" name="delete_user_id" value="<?= $user['userID'] ?>" class="auth__submit" style="background-color: #ef4444; color: white; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer; font-size: 0.85rem; width: auto; margin: 0;" onclick="return confirm('Benutzer wirklich löschen? Dies kann nicht rückgängig gemacht werden!');">Löschen</button>
                                        <?php else: ?>
                                            <span style="color: #94a3b8; font-size: 0.85rem; padding: 6px 0; display: inline-block;">Das bist du</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </form>
            
            <div class="auth__actions" style="margin-top: 30px; text-align: center;">
                <a href="account.php" style="color: #64748b; text-decoration: none; font-size: 0.95rem;">&larr; Zurück zum Profil</a>
            </div>
        </div>
    </section>
</main>

<?php include 'footer.php'; ?>
