<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

define('APP_STARTED', true);
session_start();
require_once 'networkconfig.php';
require_once 'includes/functions.php';
require_once 'includes/pagination.php';
require_once 'includes/auth.php';
require_once 'config/settings.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: mp3.php");
    exit;
}

$conn = createDbConnection();

function redirectDashboard(string $anchor = ''): void
{
    $location = 'dashboard.php';
    if ($anchor !== '') {
        $location .= '#' . ltrim($anchor, '#');
    }
    header('Location: ' . $location);
    exit;
}

function syncLocalMediaFromFilesystem(mysqli $conn, int $userId): void
{
    $existing = [];
    $result = $conn->query("SELECT filename, type FROM local_media");
    if ($result) {
        foreach ($result->fetch_all(MYSQLI_ASSOC) as $row) {
            $existing[$row['type'] . ':' . $row['filename']] = true;
        }
    }

    $patterns = [
        'mp3' => 'upload/mmp3/*.mp3',
        'mp4' => 'upload/mvideos/*.mp4',
    ];

    $stmt = $conn->prepare(
        "INSERT INTO local_media (filename, title, description, image_url, type, user_id)
         VALUES (?, ?, '', '', ?, ?)"
    );

    foreach ($patterns as $type => $pattern) {
        foreach (glob($pattern) ?: [] as $path) {
            $filename = basename($path);
            $key = $type . ':' . $filename;
            if (isset($existing[$key])) {
                continue;
            }
            $title = pathinfo($filename, PATHINFO_FILENAME);
            $stmt->bind_param("sssi", $filename, $title, $type, $userId);
            $stmt->execute();
        }
    }

    $stmt->close();
}

if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: mp3.php");
    exit;
}

$hasAdminColumn = hasColumn($conn, 'users', 'is_admin');
$hasSettingsTable = hasTable($conn, 'site_settings');
$hasSlidesTable = hasTable($conn, 'homepage_slides');

if ($hasAdminColumn) {
    $stmt = $conn->prepare("SELECT id, username, email, created_at, is_admin FROM users WHERE id = ?");
} else {
    $stmt = $conn->prepare("SELECT id, username, email, created_at FROM users WHERE id = ?");
}
$stmt->bind_param("i", $_SESSION['user_id']);
$stmt->execute();
$currentUser = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$currentUser) {
    session_destroy();
    header("Location: mp3.php");
    exit;
}

$themeDefaults = getThemeDefaults();

$schemaUpgradeRequired = !$hasAdminColumn || !$hasSettingsTable || !$hasSlidesTable;
$isAdmin = !$schemaUpgradeRequired && (int) ($currentUser['is_admin'] ?? 0) === 1;

if (!$schemaUpgradeRequired && !$isAdmin) {
    http_response_code(403);
}

if (!$schemaUpgradeRequired && $isAdmin) {
    syncLocalMediaFromFilesystem($conn, (int) $_SESSION['user_id']);
}

if (!$schemaUpgradeRequired && $isAdmin && !empty($_POST['action'])) {
    $action = $_POST['action'];

    if ($action === 'update_profile') {
        $username = trim($_POST['profile_username'] ?? '');
        $email = trim($_POST['profile_email'] ?? '');
        if ($username === '' || $email === '') {
            setFlash('error', 'Username and email are required.');
        } else {
            $stmt = $conn->prepare("UPDATE users SET username = ?, email = ? WHERE id = ?");
            $stmt->bind_param("ssi", $username, $email, $_SESSION['user_id']);
            if ($stmt->execute()) {
                $_SESSION['username'] = $username;
                setFlash('success', 'Profile updated.');
            } else {
                setFlash('error', 'Could not update profile.');
            }
            $stmt->close();
        }
        redirectDashboard('profile-admin');
    }

    if ($action === 'change_password') {
        $currentPassword = $_POST['current_password'] ?? '';
        $newPassword = $_POST['new_password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';
        if ($newPassword !== $confirmPassword) {
            setFlash('error', 'New passwords do not match.');
        } elseif (strlen($newPassword) < 6) {
            setFlash('error', 'New password must be at least 6 characters.');
        } else {
            $stmt = $conn->prepare("SELECT password FROM users WHERE id = ?");
            $stmt->bind_param("i", $_SESSION['user_id']);
            $stmt->execute();
            $stmt->bind_result($storedHash);
            $stmt->fetch();
            $stmt->close();

            if (!password_verify($currentPassword, $storedHash ?? '')) {
                setFlash('error', 'Current password is incorrect.');
            } else {
                $newHash = password_hash($newPassword, PASSWORD_DEFAULT);
                $stmt = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
                $stmt->bind_param("si", $newHash, $_SESSION['user_id']);
                $stmt->execute();
                $stmt->close();
                setFlash('success', 'Password updated.');
            }
        }
        redirectDashboard('profile-admin');
    }

    if ($action === 'update_user') {
        $userId = (int) ($_POST['user_id'] ?? 0);
        $username = trim($_POST['username'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $isAdminFlag = isset($_POST['is_admin']) ? 1 : 0;
        $newPassword = trim($_POST['new_password'] ?? '');

        $stmt = $conn->prepare("UPDATE users SET username = ?, email = ?, is_admin = ? WHERE id = ?");
        $stmt->bind_param("ssii", $username, $email, $isAdminFlag, $userId);
        $stmt->execute();
        $stmt->close();

        if ($newPassword !== '') {
            $newHash = password_hash($newPassword, PASSWORD_DEFAULT);
            $stmt = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
            $stmt->bind_param("si", $newHash, $userId);
            $stmt->execute();
            $stmt->close();
        }
        setFlash('success', 'User updated.');
        redirectDashboard('users-admin');
    }

    if ($action === 'delete_user') {
        $userId = (int) ($_POST['user_id'] ?? 0);
        if ($userId === (int) $_SESSION['user_id']) {
            setFlash('error', 'You cannot delete your own account from the dashboard.');
        } else {
            $stmt = $conn->prepare("DELETE FROM playlist_items WHERE playlist_id IN (SELECT id FROM playlists WHERE user_id = ?)");
            $stmt->bind_param("i", $userId);
            $stmt->execute();
            $stmt->close();

            $stmt = $conn->prepare("DELETE FROM playlists WHERE user_id = ?");
            $stmt->bind_param("i", $userId);
            $stmt->execute();
            $stmt->close();

            $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
            $stmt->bind_param("i", $userId);
            $stmt->execute();
            $stmt->close();
            setFlash('success', 'User deleted.');
        }
        redirectDashboard('users-admin');
    }

    if ($action === 'bulk_delete_users') {
        $userIds = $_POST['item_ids'] ?? [];
        if (!is_array($userIds) || empty($userIds)) {
            setFlash('error', 'No users selected.');
        } else {
            $deleted = 0;
            foreach ($userIds as $uid) {
                $uid = (int) $uid;
                if ($uid === (int) $_SESSION['user_id']) continue;
                $stmt = $conn->prepare("DELETE FROM playlist_items WHERE playlist_id IN (SELECT id FROM playlists WHERE user_id = ?)");
                $stmt->bind_param("i", $uid);
                $stmt->execute();
                $stmt->close();
                $stmt = $conn->prepare("DELETE FROM playlists WHERE user_id = ?");
                $stmt->bind_param("i", $uid);
                $stmt->execute();
                $stmt->close();
                $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
                $stmt->bind_param("i", $uid);
                $stmt->execute();
                $deleted += $stmt->affected_rows;
                $stmt->close();
            }
            setFlash('success', "$deleted user(s) deleted.");
        }
        redirectDashboard('users-admin');
    }

    if ($action === 'bulk_delete_media') {
        $mediaIds = $_POST['item_ids'] ?? [];
        $mediaType = $_POST['media_type'] ?? 'mp3';
        if (!is_array($mediaIds) || empty($mediaIds)) {
            setFlash('error', 'No items selected.');
        } else {
            $deleted = 0;
            foreach ($mediaIds as $mid) {
                $mid = (int) $mid;
                $stmt = $conn->prepare("SELECT filename, type FROM local_media WHERE id = ?");
                $stmt->bind_param("i", $mid);
                $stmt->execute();
                $media = $stmt->get_result()->fetch_assoc();
                $stmt->close();
                if ($media) {
                    $stmt = $conn->prepare("DELETE FROM playlist_items WHERE media_type = 'local' AND media_id = ?");
                    $stmt->bind_param("i", $mid);
                    $stmt->execute();
                    $stmt->close();
                    $stmt = $conn->prepare("DELETE FROM local_media WHERE id = ?");
                    $stmt->bind_param("i", $mid);
                    $stmt->execute();
                    $deleted += $stmt->affected_rows;
                    $stmt->close();
                    $path = ($media['type'] === 'mp4' ? 'upload/mvideos/' : 'upload/mmp3/') . $media['filename'];
                    if (is_file($path)) unlink($path);
                }
            }
            setFlash('success', "$deleted item(s) deleted.");
        }
        redirectDashboard($mediaType === 'mp4' ? 'videos-admin' : 'music-admin');
    }

    if ($action === 'bulk_delete_links') {
        $linkIds = $_POST['item_ids'] ?? [];
        if (!is_array($linkIds) || empty($linkIds)) {
            setFlash('error', 'No links selected.');
        } else {
            $deleted = 0;
            foreach ($linkIds as $lid) {
                $lid = (int) $lid;
                $stmt = $conn->prepare("DELETE FROM playlist_items WHERE media_type = 'link' AND media_id = ?");
                $stmt->bind_param("i", $lid);
                $stmt->execute();
                $stmt->close();
                $stmt = $conn->prepare("DELETE FROM media_links WHERE id = ?");
                $stmt->bind_param("i", $lid);
                $stmt->execute();
                $deleted += $stmt->affected_rows;
                $stmt->close();
            }
            setFlash('success', "$deleted link(s) deleted.");
        }
        redirectDashboard('links-admin');
    }

    if ($action === 'bulk_delete_livestreams') {
        $streamIds = $_POST['item_ids'] ?? [];
        if (!is_array($streamIds) || empty($streamIds)) {
            setFlash('error', 'No streams selected.');
        } else {
            $deleted = 0;
            foreach ($streamIds as $sid) {
                $sid = (int) $sid;
                $stmt = $conn->prepare("DELETE FROM playlist_items WHERE media_type = 'link' AND media_id = ?");
                $stmt->bind_param("i", $sid);
                $stmt->execute();
                $stmt->close();
                $stmt = $conn->prepare("DELETE FROM media_links WHERE id = ? AND type = 'm3u8'");
                $stmt->bind_param("i", $sid);
                $stmt->execute();
                $deleted += $stmt->affected_rows;
                $stmt->close();
            }
            setFlash('success', "$deleted stream(s) deleted.");
        }
        redirectDashboard('livestreams-admin');
    }

    if ($action === 'bulk_delete_playlists') {
        $playlistIds = $_POST['item_ids'] ?? [];
        if (!is_array($playlistIds) || empty($playlistIds)) {
            setFlash('error', 'No playlists selected.');
        } else {
            $deleted = 0;
            foreach ($playlistIds as $pid) {
                $pid = (int) $pid;
                $stmt = $conn->prepare("DELETE FROM playlist_items WHERE playlist_id = ?");
                $stmt->bind_param("i", $pid);
                $stmt->execute();
                $stmt->close();
                $stmt = $conn->prepare("DELETE FROM playlists WHERE id = ? AND user_id = ?");
                $stmt->bind_param("ii", $pid, $_SESSION['user_id']);
                $stmt->execute();
                $deleted += $stmt->affected_rows;
                $stmt->close();
            }
            setFlash('success', "$deleted playlist(s) deleted.");
        }
        redirectDashboard('playlists-admin');
    }

    if ($action === 'bulk_delete_games') {
        $gameIds = $_POST['item_ids'] ?? [];
        if (!is_array($gameIds) || empty($gameIds)) {
            setFlash('error', 'No games selected.');
        } else {
            $deleted = 0;
            foreach ($gameIds as $gid) {
                $gid = (int) $gid;
                $stmt = $conn->prepare("SELECT file_path FROM games WHERE id = ?");
                $stmt->bind_param("i", $gid);
                $stmt->execute();
                $game = $stmt->get_result()->fetch_assoc();
                $stmt->close();
                $stmt = $conn->prepare("DELETE FROM game_ratings WHERE game_id = ?");
                $stmt->bind_param("i", $gid);
                $stmt->execute();
                $stmt->close();
                $stmt = $conn->prepare("DELETE FROM game_bookmarks WHERE game_id = ?");
                $stmt->bind_param("i", $gid);
                $stmt->execute();
                $stmt->close();
                $stmt = $conn->prepare("DELETE FROM games WHERE id = ?");
                $stmt->bind_param("i", $gid);
                $stmt->execute();
                $deleted += $stmt->affected_rows;
                $stmt->close();
                if ($game && $game['file_path']) {
                    $basePath = dirname($game['file_path']);
                    if (is_dir($basePath)) {
                        $iterator = new RecursiveIteratorIterator(
                            new RecursiveDirectoryIterator($basePath, RecursiveDirectoryIterator::SKIP_DOTS),
                            RecursiveIteratorIterator::CHILD_FIRST
                        );
                        foreach ($iterator as $file) {
                            if ($file->isDir()) rmdir($file->getRealPath());
                            else unlink($file->getRealPath());
                        }
                        rmdir($basePath);
                    }
                }
            }
            setFlash('success', "$deleted game(s) deleted.");
        }
        redirectDashboard('games-admin');
    }

    if ($action === 'bulk_delete_slides') {
        $slideIds = $_POST['item_ids'] ?? [];
        if (!is_array($slideIds) || empty($slideIds)) {
            setFlash('error', 'No slides selected.');
        } else {
            $deleted = 0;
            foreach ($slideIds as $sid) {
                $sid = (int) $sid;
                $stmt = $conn->prepare("DELETE FROM homepage_slides WHERE id = ?");
                $stmt->bind_param("i", $sid);
                $stmt->execute();
                $deleted += $stmt->affected_rows;
                $stmt->close();
            }
            setFlash('success', "$deleted slide(s) deleted.");
        }
        redirectDashboard('sliders-admin');
    }

    if ($action === 'update_media') {
        $mediaId = (int) ($_POST['media_id'] ?? 0);
        $title = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $imageUrl = trim($_POST['image_url'] ?? '');
        $genreId = !empty($_POST['genre_id']) ? (int) $_POST['genre_id'] : null;
        $categoryId = !empty($_POST['category_id']) ? (int) $_POST['category_id'] : null;
        $isPublic = isset($_POST['is_public']) ? 1 : 0;

        $stmt = $conn->prepare(
            "UPDATE local_media SET title = ?, description = ?, image_url = ?, genre_id = ?, category_id = ?, is_public = ? WHERE id = ?"
        );
        $stmt->bind_param("sssiiii", $title, $description, $imageUrl, $genreId, $categoryId, $isPublic, $mediaId);
        $stmt->execute();
        $stmt->close();
        setFlash('success', 'Media updated.');
        redirectDashboard((($_POST['media_type'] ?? 'mp3') === 'mp4') ? 'videos-admin' : 'music-admin');
    }

    if ($action === 'delete_media') {
        $mediaId = (int) ($_POST['media_id'] ?? 0);
        $mediaType = $_POST['media_type'] ?? 'mp3';
        $stmt = $conn->prepare("SELECT filename, type FROM local_media WHERE id = ?");
        $stmt->bind_param("i", $mediaId);
        $stmt->execute();
        $media = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if ($media) {
            $stmt = $conn->prepare("DELETE FROM playlist_items WHERE media_type = 'local' AND media_id = ?");
            $stmt->bind_param("i", $mediaId);
            $stmt->execute();
            $stmt->close();

            $stmt = $conn->prepare("DELETE FROM local_media WHERE id = ?");
            $stmt->bind_param("i", $mediaId);
            $stmt->execute();
            $stmt->close();

            $path = ($media['type'] === 'mp4' ? 'upload/mvideos/' : 'upload/mmp3/') . $media['filename'];
            if (is_file($path)) {
                unlink($path);
            }
            setFlash('success', 'Media deleted.');
        } else {
            setFlash('error', 'Media not found.');
        }
        redirectDashboard($mediaType === 'mp4' ? 'videos-admin' : 'music-admin');
    }

    if ($action === 'update_link') {
        $linkId = (int) ($_POST['link_id'] ?? 0);
        $title = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $url = trim($_POST['url'] ?? '');
        $imageUrl = trim($_POST['image_url'] ?? '');
        $type = $_POST['type'] ?? 'mp3';
        $isPublic = isset($_POST['is_public']) ? 1 : 0;

        $stmt = $conn->prepare(
            "UPDATE media_links SET title = ?, description = ?, url = ?, image_url = ?, type = ?, is_public = ? WHERE id = ?"
        );
        $stmt->bind_param("sssssii", $title, $description, $url, $imageUrl, $type, $isPublic, $linkId);
        $stmt->execute();
        $stmt->close();
        setFlash('success', 'Link updated.');
        redirectDashboard('links-admin');
    }

    if ($action === 'delete_link') {
        $linkId = (int) ($_POST['link_id'] ?? 0);
        $stmt = $conn->prepare("DELETE FROM playlist_items WHERE media_type = 'link' AND media_id = ?");
        $stmt->bind_param("i", $linkId);
        $stmt->execute();
        $stmt->close();

        $stmt = $conn->prepare("DELETE FROM media_links WHERE id = ?");
        $stmt->bind_param("i", $linkId);
        $stmt->execute();
        $stmt->close();
        setFlash('success', 'Link deleted.');
        redirectDashboard('links-admin');
    }

    if ($action === 'update_livestream') {
        $streamId = (int) ($_POST['livestream_id'] ?? 0);
        $title = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $url = trim($_POST['url'] ?? '');
        $imageUrl = trim($_POST['image_url'] ?? '');
        $isPublic = isset($_POST['is_public']) ? 1 : 0;

        $stmt = $conn->prepare(
            "UPDATE media_links SET title = ?, description = ?, url = ?, image_url = ?, type = 'm3u8', is_public = ? WHERE id = ?"
        );
        $stmt->bind_param("ssssii", $title, $description, $url, $imageUrl, $isPublic, $streamId);
        $stmt->execute();
        $stmt->close();
        setFlash('success', 'Livestream updated.');
        redirectDashboard('livestreams-admin');
    }

    if ($action === 'delete_livestream') {
        $streamId = (int) ($_POST['livestream_id'] ?? 0);
        $stmt = $conn->prepare("DELETE FROM playlist_items WHERE media_type = 'link' AND media_id = ?");
        $stmt->bind_param("i", $streamId);
        $stmt->execute();
        $stmt->close();

        $stmt = $conn->prepare("DELETE FROM media_links WHERE id = ? AND type = 'm3u8'");
        $stmt->bind_param("i", $streamId);
        $stmt->execute();
        $stmt->close();
        setFlash('success', 'Livestream deleted.');
        redirectDashboard('livestreams-admin');
    }

    if ($action === 'create_playlist') {
        $name = trim($_POST['playlist_name'] ?? '');
        $isPublic = isset($_POST['is_public']) ? 1 : 0;
        if ($name === '') {
            setFlash('error', 'Playlist name is required.');
        } else {
            $stmt = $conn->prepare("INSERT INTO playlists (user_id, name, is_public) VALUES (?, ?, ?)");
            $stmt->bind_param("isi", $_SESSION['user_id'], $name, $isPublic);
            $stmt->execute();
            $stmt->close();
            setFlash('success', 'Playlist created.');
        }
        redirectDashboard('playlists-admin');
    }

    if ($action === 'update_playlist') {
        $playlistId = (int) ($_POST['playlist_id'] ?? 0);
        $name = trim($_POST['playlist_name'] ?? '');
        $isPublic = isset($_POST['is_public']) ? 1 : 0;
        $stmt = $conn->prepare("UPDATE playlists SET name = ?, is_public = ? WHERE id = ? AND user_id = ?");
        $stmt->bind_param("siii", $name, $isPublic, $playlistId, $_SESSION['user_id']);
        $stmt->execute();
        $stmt->close();
        setFlash('success', 'Playlist updated.');
        redirectDashboard('playlists-admin');
    }

    if ($action === 'delete_playlist') {
        $playlistId = (int) ($_POST['playlist_id'] ?? 0);
        $stmt = $conn->prepare("DELETE FROM playlist_items WHERE playlist_id = ?");
        $stmt->bind_param("i", $playlistId);
        $stmt->execute();
        $stmt->close();

        $stmt = $conn->prepare("DELETE FROM playlists WHERE id = ? AND user_id = ?");
        $stmt->bind_param("ii", $playlistId, $_SESSION['user_id']);
        $stmt->execute();
        $stmt->close();
        setFlash('success', 'Playlist deleted.');
        redirectDashboard('playlists-admin');
    }

    if ($action === 'add_playlist_item') {
        $playlistId = (int) ($_POST['playlist_id'] ?? 0);
        $mediaEntry = $_POST['media_entry'] ?? '';
        [$mediaType, $mediaId] = array_pad(explode(':', $mediaEntry, 2), 2, '');
        $mediaId = (int) $mediaId;

        $stmt = $conn->prepare("SELECT id FROM playlist_items WHERE playlist_id = ? AND media_type = ? AND media_id = ?");
        $stmt->bind_param("isi", $playlistId, $mediaType, $mediaId);
        $stmt->execute();
        $duplicate = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if ($duplicate) {
            setFlash('error', 'That item is already in the playlist.');
        } else {
            $stmt = $conn->prepare("INSERT INTO playlist_items (playlist_id, media_type, media_id) VALUES (?, ?, ?)");
            $stmt->bind_param("isi", $playlistId, $mediaType, $mediaId);
            $stmt->execute();
            $stmt->close();
            setFlash('success', 'Item added to playlist.');
        }
        redirectDashboard('playlists-admin');
    }

    if ($action === 'remove_playlist_item') {
        $itemId = (int) ($_POST['item_id'] ?? 0);
        $stmt = $conn->prepare(
            "DELETE pi FROM playlist_items pi
             INNER JOIN playlists p ON p.id = pi.playlist_id
             WHERE pi.id = ? AND p.user_id = ?"
        );
        $stmt->bind_param("ii", $itemId, $_SESSION['user_id']);
        $stmt->execute();
        $stmt->close();
        setFlash('success', 'Playlist item removed.');
        redirectDashboard('playlists-admin');
    }

    if ($action === 'save_theme') {
        $allowedKeys = array_keys($themeDefaults);
        $toSave = [];
        foreach ($allowedKeys as $key) {
            $toSave[$key] = trim((string) ($_POST[$key] ?? $themeDefaults[$key]));
        }
        saveSiteSettings($conn, $toSave);
        setFlash('success', 'Front-end theme updated.');
        header('Location: admin/theme-editor.php');
        exit;
    }

    if ($action === 'save_slide') {
        $slideId = (int) ($_POST['slide_id'] ?? 0);
        $sectionKey = $_POST['section_key'] ?? 'home';
        $title = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $imageUrl = trim($_POST['image_url'] ?? '');
        $badge = trim($_POST['badge'] ?? '');
        $ctaLabel = trim($_POST['cta_label'] ?? '');
        $ctaTarget = trim($_POST['cta_target'] ?? '');
        $sortOrder = (int) ($_POST['sort_order'] ?? 0);
        $isActive = isset($_POST['is_active']) ? 1 : 0;

        if ($slideId > 0) {
            $stmt = $conn->prepare(
                "UPDATE homepage_slides
                 SET section_key = ?, title = ?, description = ?, image_url = ?, badge = ?, cta_label = ?, cta_target = ?, sort_order = ?, is_active = ?
                 WHERE id = ?"
            );
            $stmt->bind_param("sssssssiii", $sectionKey, $title, $description, $imageUrl, $badge, $ctaLabel, $ctaTarget, $sortOrder, $isActive, $slideId);
            $stmt->execute();
            $stmt->close();
            setFlash('success', 'Slide updated.');
        } else {
            $stmt = $conn->prepare(
                "INSERT INTO homepage_slides (section_key, title, description, image_url, badge, cta_label, cta_target, sort_order, is_active)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"
            );
            $stmt->bind_param("sssssssii", $sectionKey, $title, $description, $imageUrl, $badge, $ctaLabel, $ctaTarget, $sortOrder, $isActive);
            $stmt->execute();
            $stmt->close();
            setFlash('success', 'Slide created.');
        }
        redirectDashboard('sliders-admin');
    }

    if ($action === 'delete_slide') {
        $slideId = (int) ($_POST['slide_id'] ?? 0);
        $stmt = $conn->prepare("DELETE FROM homepage_slides WHERE id = ?");
        $stmt->bind_param("i", $slideId);
        $stmt->execute();
        $stmt->close();
        setFlash('success', 'Slide deleted.');
        redirectDashboard('sliders-admin');
    }

    if ($action === 'update_chat_room') {
        $roomId = (int) ($_POST['room_id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $stmt = $conn->prepare("UPDATE chat_rooms SET name = ? WHERE id = ?");
        $stmt->bind_param("si", $name, $roomId);
        $stmt->execute();
        $stmt->close();
        setFlash('success', 'Chat room updated.');
        redirectDashboard('chat-admin');
    }

    if ($action === 'delete_chat_room') {
        $roomId = (int) ($_POST['room_id'] ?? 0);
        // Delete messages first
        $stmt = $conn->prepare("DELETE FROM chat_messages WHERE room_id = ?");
        $stmt->bind_param("i", $roomId);
        $stmt->execute();
        $stmt->close();
        // Delete participants
        $stmt = $conn->prepare("DELETE FROM chat_participants WHERE room_id = ?");
        $stmt->bind_param("i", $roomId);
        $stmt->execute();
        $stmt->close();
        // Delete room
        $stmt = $conn->prepare("DELETE FROM chat_rooms WHERE id = ?");
        $stmt->bind_param("i", $roomId);
        $stmt->execute();
        $stmt->close();
        setFlash('success', 'Chat room deleted.');
        redirectDashboard('chat-admin');
    }

    if ($action === 'delete_chat_message') {
        $messageId = (int) ($_POST['message_id'] ?? 0);
        $stmt = $conn->prepare("DELETE FROM chat_messages WHERE id = ?");
        $stmt->bind_param("i", $messageId);
        $stmt->execute();
        $stmt->close();
        setFlash('success', 'Message deleted.');
        redirectDashboard('chat-admin');
    }

    if ($action === 'bulk_delete_chat_rooms') {
        $roomIds = $_POST['item_ids'] ?? [];
        if (!is_array($roomIds) || empty($roomIds)) {
            setFlash('error', 'No rooms selected.');
        } else {
            $deleted = 0;
            foreach ($roomIds as $rid) {
                $rid = (int) $rid;
                $stmt = $conn->prepare("DELETE FROM chat_messages WHERE room_id = ?");
                $stmt->bind_param("i", $rid);
                $stmt->execute();
                $stmt->close();
                $stmt = $conn->prepare("DELETE FROM chat_participants WHERE room_id = ?");
                $stmt->bind_param("i", $rid);
                $stmt->execute();
                $stmt->close();
                $stmt = $conn->prepare("DELETE FROM chat_rooms WHERE id = ?");
                $stmt->bind_param("i", $rid);
                $stmt->execute();
                $deleted += $stmt->affected_rows;
                $stmt->close();
            }
            setFlash('success', "$deleted room(s) deleted.");
        }
        redirectDashboard('chat-admin');
    }

    if ($action === 'bulk_delete_chat_messages') {
        $messageIds = $_POST['item_ids'] ?? [];
        if (!is_array($messageIds) || empty($messageIds)) {
            setFlash('error', 'No messages selected.');
        } else {
            $deleted = 0;
            foreach ($messageIds as $mid) {
                $mid = (int) $mid;
                $stmt = $conn->prepare("DELETE FROM chat_messages WHERE id = ?");
                $stmt->bind_param("i", $mid);
                $stmt->execute();
                $deleted += $stmt->affected_rows;
                $stmt->close();
            }
            setFlash('success', "$deleted message(s) deleted.");
        }
        redirectDashboard('chat-admin');
    }

    if ($action === 'save_chat_settings') {
        $maxFileSize = (int) ($_POST['chat_max_file_size_mb'] ?? 10);
        if ($maxFileSize < 1) $maxFileSize = 1;
        if ($maxFileSize > 100) $maxFileSize = 100;

        // Save to site_settings table
        $stmt = $conn->prepare("INSERT INTO site_settings (setting_key, setting_value) VALUES ('chat_max_file_size_mb', ?) ON DUPLICATE KEY UPDATE setting_value = ?");
        $maxStr = (string) $maxFileSize;
        $stmt->bind_param("ss", $maxStr, $maxStr);
        $stmt->execute();
        $stmt->close();
        setFlash('success', 'Chat settings updated.');
        redirectDashboard('chat-admin');
    }

    if ($action === 'update_registration_passkey') {
        $newPasskey = trim($_POST['registration_passkey'] ?? '');
        if ($newPasskey === '') {
            setFlash('error', 'Registration passkey cannot be empty.');
        } else {
            $stmt = $conn->prepare("INSERT INTO site_settings (setting_key, setting_value) VALUES ('registration_passkey', ?) ON DUPLICATE KEY UPDATE setting_value = ?");
            $stmt->bind_param("ss", $newPasskey, $newPasskey);
            $stmt->execute();
            $stmt->close();
            setFlash('success', 'Registration passkey updated successfully.');
        }
        redirectDashboard('passkey-admin');
    }

    if ($action === 'generate_passkey') {
        $generatedPasskey = bin2hex(random_bytes(8));
        $stmt = $conn->prepare("INSERT INTO site_settings (setting_key, setting_value) VALUES ('registration_passkey', ?) ON DUPLICATE KEY UPDATE setting_value = ?");
        $stmt->bind_param("ss", $generatedPasskey, $generatedPasskey);
        $stmt->execute();
        $stmt->close();
        setFlash('success', 'New registration passkey generated: ' . $generatedPasskey);
        redirectDashboard('passkey-admin');
    }


    if ($action === 'clear_room_messages') {
        $roomId = (int) ($_POST['room_id'] ?? 0);
        if ($roomId === 0) {
            setFlash('error', 'Invalid chat room.');
        } else {
            $stmt = $conn->prepare("DELETE FROM chat_messages WHERE room_id = ?");
            $stmt->bind_param("i", $roomId);
            $stmt->execute();
            $deleted = $stmt->affected_rows;
            $stmt->close();
            setFlash('success', "Cleared $deleted message(s) from the room.");
        }
        redirectDashboard('chat-admin');
    }

    if ($action === 'bulk_delete_messages_by_room') {
        $roomId = (int) ($_POST['room_id'] ?? 0);
        $messageIds = $_POST['item_ids'] ?? [];
        if (!is_array($messageIds) || empty($messageIds)) {
            setFlash('error', 'No messages selected.');
        } else {
            $deleted = 0;
            $placeholders = rtrim(str_repeat('?,', count($messageIds)), ',');
            $sql = "DELETE FROM chat_messages WHERE id IN ($placeholders)";
            if ($roomId > 0) {
                $sql .= " AND room_id = ?";
            }
            $stmt = $conn->prepare($sql);
            if ($roomId > 0) {
                $types = str_repeat('i', count($messageIds)) . 'i';
                $params = array_merge($messageIds, [$roomId]);
                $stmt->bind_param($types, ...$params);
            } else {
                $types = str_repeat('i', count($messageIds));
                $stmt->bind_param($types, ...$messageIds);
            }
            $stmt->execute();
            $deleted = $stmt->affected_rows;
            $stmt->close();
            setFlash('success', "$deleted message(s) deleted.");
        }
        redirectDashboard('chat-admin');
    }

    if ($action === 'suspend_user') {
        if (!hasColumn($conn, 'users', 'is_suspended')) {
            setFlash('error', 'User suspension feature not available. Run the database migration first.');
        } else {
            $userId = (int) ($_POST['user_id'] ?? 0);
            $reason = trim($_POST['suspension_reason'] ?? '');
            $suspensionUntil = trim($_POST['suspended_until'] ?? '');
            
            if ($userId === 0) {
                setFlash('error', 'Invalid user.');
            } elseif ($reason === '') {
                setFlash('error', 'Suspension reason is required.');
            } else {
                $suspendedUntil = !empty($suspensionUntil) ? $suspensionUntil : null;
                $stmt = $conn->prepare("UPDATE users SET is_suspended = 1, suspended_at = NOW(), suspended_by = ?, suspension_reason = ?, suspended_until = ? WHERE id = ?");
                $stmt->bind_param("issi", $_SESSION['user_id'], $reason, $suspendedUntil, $userId);
                $stmt->execute();
                $stmt->close();
                setFlash('success', 'User has been suspended.');
            }
        }
        redirectDashboard('suspensions-admin');
    }

    if ($action === 'unsuspend_user') {
        if (!hasColumn($conn, 'users', 'is_suspended')) {
            setFlash('error', 'User suspension feature not available.');
        } else {
            $userId = (int) ($_POST['user_id'] ?? 0);
            if ($userId === 0) {
                setFlash('error', 'Invalid user.');
            } else {
                $stmt = $conn->prepare("UPDATE users SET is_suspended = 0, suspended_at = NULL, suspended_by = NULL, suspension_reason = NULL, suspended_until = NULL WHERE id = ?");
                $stmt->bind_param("i", $userId);
                $stmt->execute();
                $stmt->close();
                setFlash('success', 'User has been unsuspended.');
            }
        }
        redirectDashboard('suspensions-admin');
    }

    if ($action === 'bulk_suspend_users') {
        if (!hasColumn($conn, 'users', 'is_suspended')) {
            setFlash('error', 'User suspension feature not available. Run the database migration first.');
        } else {
            $userIds = $_POST['item_ids'] ?? [];
            $reason = trim($_POST['bulk_suspend_reason'] ?? '');
            if (!is_array($userIds) || empty($userIds)) {
                setFlash('error', 'No users selected.');
            } elseif ($reason === '') {
                setFlash('error', 'Suspension reason is required.');
            } else {
                $suspended = 0;
                foreach ($userIds as $uid) {
                    $uid = (int) $uid;
                    if ($uid > 0) {
                        $stmt = $conn->prepare("UPDATE users SET is_suspended = 1, suspended_at = NOW(), suspended_by = ?, suspension_reason = ?, suspended_until = NULL WHERE id = ?");
                        $stmt->bind_param("isi", $_SESSION['user_id'], $reason, $uid);
                        $stmt->execute();
                        $suspended += $stmt->affected_rows;
                        $stmt->close();
                    }
                }
                setFlash('success', "$suspended user(s) suspended.");
            }
        }
        redirectDashboard('suspensions-admin');
    }
    
    // Handle PayPal settings save
    if ($action === 'save_paypal_settings' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        requireAdmin($conn);
        
        $paypalMode = trim($_POST['paypal_mode'] ?? 'sandbox');
        $paypalClientId = trim($_POST['paypal_client_id'] ?? '');
        $defaultCurrency = trim($_POST['default_currency'] ?? 'USD');
        
        // Update PayPal settings
        $settings = [
            'paypal_mode' => $paypalMode,
            'paypal_client_id' => $paypalClientId,
            'default_currency' => $defaultCurrency
        ];
        
        foreach ($settings as $key => $value) {
            $stmt = $conn->prepare("INSERT INTO site_settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
            $stmt->bind_param("sss", $key, $value, $value);
            $stmt->execute();
            $stmt->close();
        }
        
        setFlash('success', 'PayPal settings saved successfully!');
        redirectDashboard('donations-admin');
    }
    
    // Handle fee settings save
    if ($action === 'save_fee_settings' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        requireAdmin($conn);
        
        $feeSettings = [
            'platform_fee_percentage' => trim($_POST['platform_fee_percentage'] ?? '2.0'),
            'withdrawal_fee_percentage' => trim($_POST['withdrawal_fee_percentage'] ?? '2.0'),
            'minimum_donation_amount' => trim($_POST['minimum_donation_amount'] ?? '1.00'),
            'maximum_donation_amount' => trim($_POST['maximum_donation_amount'] ?? '1000.00'),
            'minimum_withdrawal_amount' => trim($_POST['minimum_withdrawal_amount'] ?? '10.00'),
            'donation_enabled' => isset($_POST['donation_enabled']) ? '1' : '0',
            'sponsorship_enabled' => isset($_POST['sponsorship_enabled']) ? '1' : '0'
        ];
        
        foreach ($feeSettings as $key => $value) {
            $stmt = $conn->prepare("INSERT INTO site_settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
            $stmt->bind_param("sss", $key, $value, $value);
            $stmt->execute();
            $stmt->close();
        }
        
        setFlash('success', 'Fee settings saved successfully!');
        redirectDashboard('donations-admin');
    }


    if ($action === 'update_game') {
        $gameId = (int) ($_POST['game_id'] ?? 0);
        $title = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $embedUrl = trim($_POST['embed_url'] ?? '');
        $categoryId = !empty($_POST['category_id']) ? (int) $_POST['category_id'] : null;
        $isFeatured = isset($_POST['is_featured']) ? 1 : 0;
        $isPublic = isset($_POST['is_public']) ? 1 : 0;
        $version = trim($_POST['version'] ?? '');
        $developer = trim($_POST['developer'] ?? '');
        $tags = trim($_POST['tags'] ?? '');
        $unityVersion = trim($_POST['unity_version'] ?? '');
        $platformType = $_POST['platform_type'] ?? 'pc';

        if ($title === '') {
            setFlash('error', 'Game title is required.');
        } else {
            if (!in_array($platformType, ['pc', 'mobile'])) {
                setFlash('error', 'Invalid platform type.');
            } else {
                $stmt = $conn->prepare(
                    "UPDATE games SET title = ?, description = ?, embed_url = ?, category_id = ?, is_featured = ?, is_public = ?, version = ?, developer = ?, tags = ?, unity_version = ?, platform_type = ? WHERE id = ?"
                );
                $stmt->bind_param("sssiiisssssi", $title, $description, $embedUrl, $categoryId, $isFeatured, $isPublic, $version, $developer, $tags, $unityVersion, $platformType, $gameId);
                $stmt->execute();
                $stmt->close();
                setFlash('success', 'Game updated.');
            }
        }
        redirectDashboard('games-admin');
    }

    if ($action === 'delete_game') {
        $gameId = (int) ($_POST['game_id'] ?? 0);
        $stmt = $conn->prepare("SELECT file_path FROM games WHERE id = ?");
        $stmt->bind_param("i", $gameId);
        $stmt->execute();
        $game = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if ($game) {
            // Delete game ratings and bookmarks first
            $stmt = $conn->prepare("DELETE FROM game_ratings WHERE game_id = ?");
            $stmt->bind_param("i", $gameId);
            $stmt->execute();
            $stmt->close();

            $stmt = $conn->prepare("DELETE FROM game_bookmarks WHERE game_id = ?");
            $stmt->bind_param("i", $gameId);
            $stmt->execute();
            $stmt->close();

            // Delete game
            $stmt = $conn->prepare("DELETE FROM games WHERE id = ?");
            $stmt->bind_param("i", $gameId);
            $stmt->execute();
            $stmt->close();

            // Delete files if uploaded
            if ($game['file_path']) {
                $basePath = dirname($game['file_path']);
                if (is_dir($basePath)) {
                    $iterator = new RecursiveIteratorIterator(
                        new RecursiveDirectoryIterator($basePath, RecursiveDirectoryIterator::SKIP_DOTS),
                        RecursiveIteratorIterator::CHILD_FIRST
                    );
                    foreach ($iterator as $file) {
                        if ($file->isDir()) rmdir($file->getRealPath());
                        else unlink($file->getRealPath());
                    }
                    rmdir($basePath);
                }
            }
            setFlash('success', 'Game deleted.');
        } else {
            setFlash('error', 'Game not found.');
        }
        redirectDashboard('games-admin');
    }
}

$flash = $_SESSION['flash'] ?? null;
unset($_SESSION['flash']);

$theme = loadSiteSettings($conn, $themeDefaults);

$stats = [
    'users' => countResult($conn, "SELECT COUNT(*) FROM users"),
    'music' => countResult($conn, "SELECT COUNT(*) FROM local_media WHERE type = 'mp3'"),
    'videos' => countResult($conn, "SELECT COUNT(*) FROM local_media WHERE type = 'mp4'"),
    'links' => countResult($conn, "SELECT COUNT(*) FROM media_links WHERE type IN ('mp3', 'mp4')"),
    'livestreams' => countResult($conn, "SELECT COUNT(*) FROM media_links WHERE type = 'm3u8'"),
    'playlists' => countResult($conn, "SELECT COUNT(*) FROM playlists"),
    'slides' => countResult($conn, "SELECT COUNT(*) FROM homepage_slides"),
    'games' => countResult($conn, "SELECT COUNT(*) FROM games"),
];

$genres = $conn->query("SELECT id, name FROM genres ORDER BY name");
$genres = $genres ? $genres->fetch_all(MYSQLI_ASSOC) : [];
$categories = $conn->query("SELECT id, name FROM categories ORDER BY name");
$categories = $categories ? $categories->fetch_all(MYSQLI_ASSOC) : [];

$users = [];
$musicItems = [];
$videoItems = [];
$links = [];
$livestreams = [];
$playlists = [];
$playlistItemsByPlaylist = [];
$playlistSources = [];
$slides = [];
$chatRooms = [];
$chatMessages = [];
$gameCategories = [];
$games = [];

if (!$schemaUpgradeRequired && $isAdmin) {
    // Load users with suspension data (if columns exist)
    $hasSuspension = hasColumn($conn, 'users', 'is_suspended');
    $userFields = 'id, username, email, created_at, is_admin';
    if ($hasSuspension) {
        $userFields .= ', is_suspended, suspended_at, suspended_by, suspension_reason, suspended_until';
    }
    $result = $conn->query("SELECT {$userFields} FROM users ORDER BY created_at DESC");

    $users = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];

    // Load PayPal settings from database
    $paypal_settings = [
        'mode' => 'sandbox',
        'client_id' => '',
        'currency' => 'USD',
        'platform_fee' => 2.0,
        'withdrawal_fee' => 2.0,
        'min_donation' => 1.00,
        'max_donation' => 1000.00,
        'min_withdrawal' => 10.00,
        'donation_enabled' => true,
        'sponsorship_enabled' => true
    ];
    
    $settings_keys = [
        'paypal_mode' => 'mode',
        'paypal_client_id' => 'client_id',
        'default_currency' => 'currency',
        'platform_fee_percentage' => 'platform_fee',
        'withdrawal_fee_percentage' => 'withdrawal_fee',
        'minimum_donation_amount' => 'min_donation',
        'maximum_donation_amount' => 'max_donation',
        'minimum_withdrawal_amount' => 'min_withdrawal',
        'donation_enabled' => 'donation_enabled',
        'sponsorship_enabled' => 'sponsorship_enabled'
    ];
    
    foreach ($settings_keys as $db_key => $array_key) {
        $stmt = $conn->prepare("SELECT setting_value FROM site_settings WHERE setting_key = ?");
        $stmt->bind_param("s", $db_key);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($row = $result->fetch_assoc()) {
            $value = $row['setting_value'];
            // Convert to appropriate type
            if (in_array($array_key, ['platform_fee', 'withdrawal_fee', 'min_donation', 'max_donation', 'min_withdrawal'])) {
                $paypal_settings[$array_key] = floatval($value);
            } elseif (in_array($array_key, ['donation_enabled', 'sponsorship_enabled'])) {
                $paypal_settings[$array_key] = (bool) intval($value);
            } else {
                $paypal_settings[$array_key] = $value;
            }
        }
        $stmt->close();
    }

    $mediaQuery = "SELECT lm.*, u.username AS owner_name FROM local_media lm LEFT JOIN users u ON u.id = lm.user_id WHERE lm.type = ? ORDER BY lm.created_at DESC";
    $stmt = $conn->prepare($mediaQuery);
    $type = 'mp3';
    $stmt->bind_param("s", $type);
    $stmt->execute();
    $musicItems = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    $stmt = $conn->prepare($mediaQuery);
    $type = 'mp4';
    $stmt->bind_param("s", $type);
    $stmt->execute();
    $videoItems = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    $result = $conn->query("SELECT ml.*, u.username AS owner_name FROM media_links ml LEFT JOIN users u ON u.id = ml.user_id WHERE ml.type IN ('mp3', 'mp4') ORDER BY ml.created_at DESC");
    $links = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];

    $result = $conn->query("SELECT ml.*, u.username AS owner_name FROM media_links ml LEFT JOIN users u ON u.id = ml.user_id WHERE ml.type = 'm3u8' ORDER BY ml.created_at DESC");
    $livestreams = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];

    $stmt = $conn->prepare(
        "SELECT p.*, COUNT(pi.id) AS item_count
         FROM playlists p
         LEFT JOIN playlist_items pi ON pi.playlist_id = p.id
         WHERE p.user_id = ?
         GROUP BY p.id
         ORDER BY p.created_at DESC"
    );
    $stmt->bind_param("i", $_SESSION['user_id']);
    $stmt->execute();
    $playlists = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    $stmt = $conn->prepare(
        "SELECT pi.id AS item_id, pi.playlist_id, pi.media_type, pi.media_id,
                COALESCE(lm.title, ml.title) AS item_title,
                COALESCE(lm.type, ml.type) AS item_format
         FROM playlist_items pi
         INNER JOIN playlists p ON p.id = pi.playlist_id
         LEFT JOIN local_media lm ON pi.media_type = 'local' AND lm.id = pi.media_id
         LEFT JOIN media_links ml ON pi.media_type = 'link' AND ml.id = pi.media_id
         WHERE p.user_id = ?
         ORDER BY pi.added_at DESC"
    );
    $stmt->bind_param("i", $_SESSION['user_id']);
    $stmt->execute();
    $playlistItems = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    foreach ($playlistItems as $item) {
        $playlistItemsByPlaylist[$item['playlist_id']][] = $item;
    }

    $result = $conn->query("SELECT id, title, type FROM local_media ORDER BY title");
    if ($result) {
        foreach ($result->fetch_all(MYSQLI_ASSOC) as $item) {
            $playlistSources[] = [
                'value' => 'local:' . $item['id'],
                'label' => $item['title'] . ' (' . strtoupper($item['type']) . ' / local)',
            ];
        }
    }
    $result = $conn->query("SELECT id, title, type FROM media_links ORDER BY title");
    if ($result) {
        foreach ($result->fetch_all(MYSQLI_ASSOC) as $item) {
            $playlistSources[] = [
                'value' => 'link:' . $item['id'],
                'label' => $item['title'] . ' (' . strtoupper($item['type']) . ' / link)',
            ];
        }
    }

    $result = $conn->query("SELECT * FROM homepage_slides ORDER BY section_key, sort_order, id");
    $slides = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];

    // Load chat rooms with participant counts
    $result = $conn->query("
        SELECT r.*, 
               (SELECT COUNT(*) FROM chat_participants WHERE room_id = r.id) as participant_count,
               (SELECT COUNT(*) FROM chat_messages WHERE room_id = r.id) as message_count
        FROM chat_rooms r
        ORDER BY r.created_at DESC
    ");
    $chatRooms = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];

    // Load recent chat messages
    $result = $conn->query("
        SELECT m.*, u.username, r.name as room_name, r.type as room_type
        FROM chat_messages m
        JOIN users u ON m.sender_id = u.id
        JOIN chat_rooms r ON m.room_id = r.id
        ORDER BY m.created_at DESC
        LIMIT 100
    ");
    $chatMessages = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];

    // Load game categories
    $result = $conn->query("SELECT * FROM game_categories ORDER BY sort_order");
    $gameCategories = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];

    // Load games with category and user info
    $result = $conn->query("
        SELECT g.*, u.username, gc.name as category_name, gc.slug as category_slug,
               (SELECT COUNT(*) FROM game_bookmarks WHERE game_id = g.id) as bookmarks_count,
               COALESCE((SELECT AVG(rating) FROM game_ratings WHERE game_id = g.id), 0) as avg_rating
        FROM games g
        LEFT JOIN users u ON g.user_id = u.id
        LEFT JOIN game_categories gc ON g.category_id = gc.id
        ORDER BY g.created_at DESC
    ");
    $games = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NEXUS Dashboard</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <link rel="stylesheet" href="assets/payment.css?v=2026042301">
    <link rel="stylesheet" href="assets/theme.css">
    <style>
        :root {
            --primary: <?= e($theme['primary_color']) ?>;
            --primary-strong: <?= e($theme['secondary_color']) ?>;
            --accent: <?= e($theme['accent_color']) ?>;
            --surface: <?= e($theme['surface_color']) ?>;
            --text: <?= e($theme['text_color']) ?>;
            --muted: <?= e($theme['muted_color']) ?>;
            --bg-start: <?= e($theme['bg_start']) ?>;
            --bg-mid: <?= e($theme['bg_mid']) ?>;
            --bg-end: <?= e($theme['bg_end']) ?>;
            --radius-lg: <?= (int) ($theme['border_radius'] ?? 28) ?>px;
            --radius-md: <?= ((int) ($theme['border_radius'] ?? 28) - 8) ?>px;
        }
        body {
            font-family: <?= e($theme['font_family'] ?? 'Outfit') ?>, system-ui, sans-serif;
            <?php if (!empty($theme['background_image'])): ?>
            background-image: url(<?= e($theme['background_image']) ?>) !important;
            background-size: cover !important;
            background-position: center !important;
            background-attachment: fixed !important;
            <?php endif; ?>
        }

        /* Themed scrollbar for dashboard sidebar */
        .admin-sidebar {
            max-height: 100vh;
            overflow-y: auto;
            scrollbar-width: thin;
            scrollbar-color: var(--primary) rgba(255,255,255,0.05);
        }
        .admin-sidebar::-webkit-scrollbar {
            width: 8px;
        }
        .admin-sidebar::-webkit-scrollbar-track {
            background: rgba(255,255,255,0.05);
            border-radius: 4px;
        }
        .admin-sidebar::-webkit-scrollbar-thumb {
            background: linear-gradient(135deg, var(--primary), var(--primary-strong));
            border-radius: 4px;
        }
        .admin-sidebar::-webkit-scrollbar-thumb:hover {
            background: var(--accent);
        }

        /* Bulk delete controls */
        .bulk-actions-bar {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            padding: 12px 16px;
            margin-bottom: 16px;
            background: rgba(255,255,255,0.04);
            border: 1px solid rgba(255,255,255,0.08);
            border-radius: var(--radius-md);
        }
        .bulk-actions-bar .bulk-select-all {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 0.85rem;
            color: var(--muted);
        }
        .bulk-actions-bar .bulk-select-all input[type="checkbox"] {
            width: 18px;
            height: 18px;
            cursor: pointer;
        }
        .bulk-actions-bar .bulk-delete-btn {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 16px;
            background: rgba(220, 53, 69, 0.2);
            border: 1px solid rgba(220, 53, 69, 0.4);
            border-radius: 10px;
            color: #ff6b6b;
            font-size: 0.85rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
        }
        .bulk-actions-bar .bulk-delete-btn:hover {
            background: rgba(220, 53, 69, 0.3);
            border-color: rgba(220, 53, 69, 0.6);
        }
        .bulk-actions-bar .bulk-delete-btn:disabled {
            opacity: 0.4;
            cursor: not-allowed;
        }
        .bulk-actions-bar .bulk-count {
            font-size: 0.85rem;
            color: var(--accent);
        }
        .manager-card .bulk-checkbox {
            position: absolute;
            top: 12px;
            left: 12px;
            width: 20px;
            height: 20px;
            cursor: pointer;
            z-index: 10;
        }
        .manager-card {
            position: relative;
            padding-left: 40px;
        }

        /* Floating scroll-to-top button */
        .scroll-to-top-btn {
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--primary), var(--primary-strong));
            border: none;
            color: #04111d;
            font-size: 1.2rem;
            cursor: pointer;
            display: none;
            align-items: center;
            justify-content: center;
            box-shadow: 0 4px 20px rgba(0,0,0,0.3);
            transition: all 0.3s ease;
            z-index: 9999;
        }
        .scroll-to-top-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 25px rgba(0,0,0,0.4);
            background: var(--accent);
        }
        .scroll-to-top-btn.is-visible {
            display: flex;
        }
    </style>
</head>
<body class="nexus-body">
    <div class="admin-layout">
        <aside class="admin-sidebar glass-panel">
            <div>
                <p class="eyebrow">Dashboard Menu</p>
                <h2>Admin Controls</h2>
            </div>
            <nav class="admin-nav">
                <a href="#overview-admin" class="admin-nav-link"><i class="fas fa-gauge-high"></i> Overview</a>
                <a href="#users-admin" class="admin-nav-link"><i class="fas fa-users"></i> Users</a>
                <a href="#profile-admin" class="admin-nav-link"><i class="fas fa-id-card"></i> Profile</a>
                <div class="divider" style="margin: 8px 0;"></div>
                <a href="profile.php" class="admin-nav-link" style="background: linear-gradient(135deg, rgba(120, 240, 197, 0.1), rgba(63, 210, 255, 0.1)); border-color: var(--primary);">
                    <i class="fas fa-user-circle"></i> Social Profile
                </a>
                <a href="community.php" class="admin-nav-link" style="background: linear-gradient(135deg, rgba(255, 143, 112, 0.1), rgba(63, 210, 255, 0.1)); border-color: var(--accent);">
                    <i class="fas fa-globe"></i> Community Feed
                </a>
                <div class="divider" style="margin: 8px 0;"></div>
                <a href="#music-admin" class="admin-nav-link"><i class="fas fa-music"></i> Music</a>
                <a href="#videos-admin" class="admin-nav-link"><i class="fas fa-film"></i> Videos</a>
                <a href="#links-admin" class="admin-nav-link"><i class="fas fa-link"></i> Links</a>
                <a href="#livestreams-admin" class="admin-nav-link"><i class="fas fa-broadcast-tower"></i> Livestreams</a>
                <a href="#playlists-admin" class="admin-nav-link"><i class="fas fa-list"></i> Playlists</a>
                <a href="#chat-admin" class="admin-nav-link"><i class="fas fa-comments"></i> Chat Rooms</a>
                <a href="games.php" class="admin-nav-link" style="background: linear-gradient(135deg, rgba(139, 92, 246, 0.1), rgba(236, 72, 153, 0.1)); border-color: #8b5cf6;">
                    <i class="fas fa-gamepad"></i> Games
                </a>
                <a href="#games-admin" class="admin-nav-link"><i class="fas fa-gamepad"></i> Manage Games</a>
                <a href="admin/theme-editor.php" class="admin-nav-link"><i class="fas fa-palette"></i> Theme Editor</a>
                <a href="#sliders-admin" class="admin-nav-link"><i class="fas fa-images"></i> Sliders</a>
                <a href="#passkey-admin" class="admin-nav-link"><i class="fas fa-key"></i> Registration Passkey</a>
                <a href="#suspensions-admin" class="admin-nav-link"><i class="fas fa-user-slash"></i> User Suspensions</a>
                <a href="#donations-admin" class="admin-nav-link"><i class="fas fa-hand-holding-heart"></i> Donations & Payments</a>            </nav>
            <div class="admin-sidebar-actions">
                <a href="mp3.php" class="btn btn-secondary btn-full"><i class="fas fa-circle-play"></i> Open Front End</a>
                <a href="?logout=1" class="btn btn-danger btn-full"><i class="fas fa-right-from-bracket"></i> Logout</a>
            </div>
        </aside>

        <main class="admin-content">
            <header class="site-header">
                <div>
                    <p class="eyebrow">Admin Overview</p>
                    <h1 class="hero-title">Nexus Control Center</h1>
                    <p class="lede compact">Edit users, media metadata, links, playlists, theme colors, front-end copy, and animated slider content from one responsive admin surface.</p>
                </div>
                <button type="button" class="mobile-menu-toggle" data-menu-toggle aria-label="Toggle menu" aria-expanded="false">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="site-actions" id="site-actions" data-menu>
                    <div class="user-chip">
                        <span class="avatar"><?= strtoupper(substr((string) $_SESSION['username'], 0, 1)) ?></span>
                        <div>
                            <strong><?= e($_SESSION['username']) ?></strong>
                            <small><?= e($currentUser['email']) ?></small>
                        </div>
                    </div>
                    <a href="mp3.php" class="btn btn-secondary"><i class="fas fa-circle-play"></i> Home</a>
                    <a href="profile.php" class="btn btn-secondary"><i class="fas fa-user-circle"></i> Profile</a>
                    <a href="?logout=1" class="btn btn-danger"><i class="fas fa-right-from-bracket"></i> Logout</a>

                    <nav class="mobile-nav" data-mobile-nav>
                        <a href="mp3.php" class="top-nav-link">
                            <i class="fas fa-home"></i> <span>Home</span>
                        </a>
                        <a href="#overview-admin" class="top-nav-link">
                            <i class="fas fa-gauge-high"></i> <span>Overview</span>
                        </a>
                        <a href="#users-admin" class="top-nav-link">
                            <i class="fas fa-users"></i> <span>Users</span>
                        </a>
                        <a href="#profile-admin" class="top-nav-link">
                            <i class="fas fa-id-card"></i> <span>Profile</span>
                        </a>
                        <a href="profile.php" class="top-nav-link">
                            <i class="fas fa-user-circle"></i> <span>My Profile</span>
                        </a>
                        <a href="?logout=1" class="top-nav-link" style="color: var(--accent);">
                            <i class="fas fa-right-from-bracket"></i> <span>Logout</span>
                        </a>
                    </nav>
                </div>
            </header>

            <?php if ($flash): ?>
                <div class="alert <?= $flash['type'] === 'error' ? 'alert-error' : 'alert-success' ?>"><?= e($flash['message']) ?></div>
            <?php endif; ?>

            <?php if ($schemaUpgradeRequired): ?>
                <section class="glass-panel upgrade-panel">
                    <p class="eyebrow">Schema Upgrade Required</p>
                    <h2>Run `dashboard_admin_upgrade.sql` before using this dashboard.</h2>
                    <p>The dashboard now expects `users.is_admin`, `site_settings`, and `homepage_slides`. After running the SQL, reload this page.</p>
                </section>
            <?php elseif (!$isAdmin): ?>
                <section class="glass-panel upgrade-panel">
                    <p class="eyebrow">Access Restricted</p>
                    <h2>This dashboard is for admins only.</h2>
                    <p>Your account does not currently have `is_admin = 1`.</p>
                    <a href="mp3.php" class="btn btn-secondary"><i class="fas fa-circle-play"></i> Back to Front End</a>
                </section>
            <?php else: ?>
                <section class="hero-grid" id="overview-admin">
                    <div class="glass-panel hero-panel">
                        <p class="eyebrow">Live Front-End Control</p>
                        <h2>Customize the public experience without hand-editing files.</h2>
                        <p>Theme colors, headings, users, media descriptions, links, playlists, and animated sliders are now configurable from dedicated dashboard sections.</p>
                        <div class="pill-row">
                            <span class="pill"><i class="fas fa-users"></i> <?= $stats['users'] ?> Users</span>
                            <span class="pill"><i class="fas fa-music"></i> <?= $stats['music'] ?> Music</span>
                            <span class="pill"><i class="fas fa-film"></i> <?= $stats['videos'] ?> Videos</span>
                            <span class="pill"><i class="fas fa-link"></i> <?= $stats['links'] ?> Links</span>
                            <span class="pill"><i class="fas fa-images"></i> <?= $stats['slides'] ?> Slides</span>
                        </div>
                    </div>
                    <div class="stats-grid">
                        <article class="glass-panel stat-card"><span class="stat-label">Users</span><strong><?= $stats['users'] ?></strong><small>Editable accounts</small></article>
                        <article class="glass-panel stat-card"><span class="stat-label">Music</span><strong><?= $stats['music'] ?></strong><small>MP3 items</small></article>
                        <article class="glass-panel stat-card"><span class="stat-label">Videos</span><strong><?= $stats['videos'] ?></strong><small>MP4 items</small></article>
                        <article class="glass-panel stat-card"><span class="stat-label">Links</span><strong><?= $stats['links'] ?></strong><small>Remote sources</small></article>
                    </div>
                </section>

                <section class="glass-panel admin-section" id="users-admin" data-pagination-section="users">
                    <div class="section-head">
                        <div><p class="eyebrow">Users</p><h2>User accounts and admin access</h2></div>
                    </div>
                    <div class="management-stack">
                        <!-- Top Pagination -->
                        <div class="pagination-wrapper" data-pagination-wrapper="users"></div>
                        <div class="bulk-actions-bar" data-bulk-section="users">
                            <label class="bulk-select-all">
                                <input type="checkbox" data-bulk-select-all="users"> Select All
                            </label>
                            <span class="bulk-count" data-bulk-count="users">0 selected</span>
                            <form method="post" class="bulk-delete-form" data-bulk-delete-form="users" style="display:inline;">
                                <input type="hidden" name="action" value="bulk_delete_users">
                                <button type="submit" class="bulk-delete-btn" data-bulk-delete-btn="users" disabled>
                                    <i class="fas fa-trash"></i> Delete Selected (<span data-bulk-delete-count="users">0</span>)
                                </button>
                            </form>
                        </div>
                        <?php foreach ($users as $user): ?>
                            <details class="manager-card" data-bulk-item="users" data-item-id="<?= (int) $user['id'] ?>">
                                <input type="checkbox" class="bulk-checkbox" data-bulk-item="users" data-item-id="<?= (int) $user['id'] ?>" <?= (int) $user['id'] === (int) $_SESSION['user_id'] ? 'disabled' : '' ?>>
                                <summary class="manager-summary">
                                    <div>
                                        <strong><?= e($user['username']) ?></strong>
                                        <small><?= e($user['email']) ?></small>
                                    </div>
                                    <div class="pill-row">
                                        <span class="pill"><?= (int) $user['is_admin'] === 1 ? 'Admin' : 'Member' ?></span>
                                        <span class="pill"><?= e(date('M j, Y', strtotime($user['created_at']))) ?></span>
                                    </div>
                                </summary>
                                <form method="post" class="inline-form-grid">
                                    <input type="hidden" name="action" value="update_user">
                                    <input type="hidden" name="user_id" value="<?= (int) $user['id'] ?>">
                                    <label><span>Username</span><input type="text" name="username" value="<?= e($user['username']) ?>" required></label>
                                    <label><span>Email</span><input type="email" name="email" value="<?= e($user['email']) ?>" required></label>
                                    <label><span>Reset Password</span><input type="text" name="new_password" placeholder="Leave blank to keep current password"></label>
                                    <label class="checkbox-field"><input type="checkbox" name="is_admin" value="1" <?= (int) $user['is_admin'] === 1 ? 'checked' : '' ?>><span>Grant admin access</span></label>
                                    <div class="action-row full-span"><button type="submit" class="btn btn-primary">Save User</button></div>
                                </form>
                                <?php if ((int) $user['id'] !== (int) $_SESSION['user_id']): ?>
                                    <form method="post" class="danger-form" onsubmit="return confirm('Delete this user account?');">
                                        <input type="hidden" name="action" value="delete_user">
                                        <input type="hidden" name="user_id" value="<?= (int) $user['id'] ?>">
                                        <button type="submit" class="btn btn-danger">Delete User</button>
                                    </form>
                                <?php endif; ?>
                            </details>
                        <?php endforeach; ?>
                        <!-- Bottom Pagination -->
                        <div class="pagination-wrapper" data-pagination-wrapper="users"></div>
                    </div>
                </section>

                <section class="dashboard-grid dashboard-grid-tight" id="profile-admin">
                    <article class="glass-panel">
                        <div class="section-head"><div><p class="eyebrow">Profile</p><h2>Edit your own account</h2></div></div>
                        <form method="post" class="stack-form">
                            <input type="hidden" name="action" value="update_profile">
                            <label><span>Username</span><input type="text" name="profile_username" value="<?= e($currentUser['username']) ?>" required></label>
                            <label><span>Email</span><input type="email" name="profile_email" value="<?= e($currentUser['email']) ?>" required></label>
                            <button type="submit" class="btn btn-primary">Save Profile</button>
                        </form>
                    </article>
                    <article class="glass-panel">
                        <div class="section-head"><div><p class="eyebrow">Security</p><h2>Change your password</h2></div></div>
                        <form method="post" class="stack-form">
                            <input type="hidden" name="action" value="change_password">
                            <label><span>Current Password</span><input type="password" name="current_password" required></label>
                            <label><span>New Password</span><input type="password" name="new_password" required></label>
                            <label><span>Confirm Password</span><input type="password" name="confirm_password" required></label>
                            <button type="submit" class="btn btn-secondary">Update Password</button>
                        </form>
                    </article>
                </section>

                <?php
                $mediaSections = [
                    'music-admin' => ['title' => 'Music', 'icon' => 'fa-music', 'type' => 'mp3', 'items' => $musicItems],
                    'videos-admin' => ['title' => 'Videos', 'icon' => 'fa-film', 'type' => 'mp4', 'items' => $videoItems],
                ];
                foreach ($mediaSections as $sectionId => $section):
                ?>
                    <section class="glass-panel admin-section" id="<?= e($sectionId) ?>">
                        <div class="section-head">
                            <div><p class="eyebrow"><?= e($section['title']) ?></p><h2>Edit <?= e(strtolower($section['title'])) ?> metadata</h2></div>
                            <span class="pill"><i class="fas <?= e($section['icon']) ?>"></i> <?= count($section['items']) ?> items</span>
                        </div>
                        <div class="management-stack">
                            <?php if (empty($section['items'])): ?>
                                <div class="empty-state">No <?= e(strtolower($section['title'])) ?> items found.</div>
                            <?php else: ?>
                                <div class="bulk-actions-bar" data-bulk-section="<?= $section['type'] ?>">
                                    <label class="bulk-select-all">
                                        <input type="checkbox" data-bulk-select-all="<?= $section['type'] ?>"> Select All
                                    </label>
                                    <span class="bulk-count" data-bulk-count="<?= $section['type'] ?>">0 selected</span>
                                    <form method="post" class="bulk-delete-form" data-bulk-delete-form="<?= $section['type'] ?>" style="display:inline;">
                                        <input type="hidden" name="action" value="bulk_delete_media">
                                        <input type="hidden" name="media_type" value="<?= e($section['type']) ?>">
                                        <button type="submit" class="bulk-delete-btn" data-bulk-delete-btn="<?= $section['type'] ?>" disabled>
                                            <i class="fas fa-trash"></i> Delete Selected (<span data-bulk-delete-count="<?= $section['type'] ?>">0</span>)
                                        </button>
                                    </form>
                                </div>
                                <?php foreach ($section['items'] as $media): ?>
                                    <details class="manager-card" data-bulk-item="<?= $section['type'] ?>" data-item-id="<?= (int) $media['id'] ?>">
                                        <input type="checkbox" class="bulk-checkbox" data-bulk-item="<?= $section['type'] ?>" data-item-id="<?= (int) $media['id'] ?>">
                                        <summary class="manager-summary">
                                            <div>
                                                <strong><?= e($media['title'] ?: $media['filename']) ?></strong>
                                                <small><?= e($media['filename']) ?></small>
                                            </div>
                                            <div class="pill-row">
                                                <span class="pill"><?= strtoupper(e($media['type'])) ?></span>
                                                <span class="pill"><?= (int) $media['is_public'] === 1 ? 'Public' : 'Private' ?></span>
                                            </div>
                                        </summary>
                                        <form method="post" class="inline-form-grid">
                                            <input type="hidden" name="action" value="update_media">
                                            <input type="hidden" name="media_id" value="<?= (int) $media['id'] ?>">
                                            <input type="hidden" name="media_type" value="<?= e($section['type']) ?>">
                                            <label><span>Title</span><input type="text" name="title" value="<?= e($media['title']) ?>" required></label>
                                            <label><span>Thumbnail URL</span><input type="url" name="image_url" value="<?= e($media['image_url']) ?>" placeholder="https://..."></label>
                                            <label><span>Genre</span><select name="genre_id"><option value="">None</option><?php foreach ($genres as $genre): ?><option value="<?= (int) $genre['id'] ?>" <?= (int) $media['genre_id'] === (int) $genre['id'] ? 'selected' : '' ?>><?= e($genre['name']) ?></option><?php endforeach; ?></select></label>
                                            <label><span>Category</span><select name="category_id"><option value="">None</option><?php foreach ($categories as $category): ?><option value="<?= (int) $category['id'] ?>" <?= (int) $media['category_id'] === (int) $category['id'] ? 'selected' : '' ?>><?= e($category['name']) ?></option><?php endforeach; ?></select></label>
                                            <label class="checkbox-field full-span"><input type="checkbox" name="is_public" value="1" <?= (int) $media['is_public'] === 1 ? 'checked' : '' ?>><span>Show this item in shared/public browsing</span></label>
                                            <label class="full-span"><span>Description</span><textarea name="description" rows="3"><?= e($media['description']) ?></textarea></label>
                                            <div class="action-row full-span"><button type="submit" class="btn btn-primary">Save <?= e($section['title']) ?> Item</button></div>
                                        </form>
                                        <form method="post" class="danger-form" onsubmit="return confirm('Delete this media item and remove it from playlists?');">
                                            <input type="hidden" name="action" value="delete_media">
                                            <input type="hidden" name="media_id" value="<?= (int) $media['id'] ?>">
                                            <input type="hidden" name="media_type" value="<?= e($section['type']) ?>">
                                            <button type="submit" class="btn btn-danger">Delete Item</button>
                                        </form>
                                    </details>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </section>
                <?php endforeach; ?>

                <section class="glass-panel admin-section" id="links-admin" data-pagination-section="links">
                    <div class="section-head">
                        <div><p class="eyebrow">Links</p><h2>Edit saved external media sources</h2></div>
                        <span class="pill"><i class="fas fa-link"></i> <?= count($links) ?> links</span>
                    </div>
                    <div class="management-stack">
                        <!-- Top Pagination -->
                        <div class="pagination-wrapper" data-pagination-wrapper="links"></div>
                        <div class="bulk-actions-bar" data-bulk-section="links">
                            <label class="bulk-select-all">
                                <input type="checkbox" data-bulk-select-all="links"> Select All
                            </label>
                            <span class="bulk-count" data-bulk-count="links">0 selected</span>
                            <form method="post" class="bulk-delete-form" data-bulk-delete-form="links" style="display:inline;">
                                <input type="hidden" name="action" value="bulk_delete_links">
                                <button type="submit" class="bulk-delete-btn" data-bulk-delete-btn="links" disabled>
                                    <i class="fas fa-trash"></i> Delete Selected (<span data-bulk-delete-count="links">0</span>)
                                </button>
                            </form>
                        </div>
                        <?php foreach ($links as $link): ?>
                            <details class="manager-card" data-bulk-item="links" data-item-id="<?= (int) $link['id'] ?>">
                                <input type="checkbox" class="bulk-checkbox" data-bulk-item="links" data-item-id="<?= (int) $link['id'] ?>">
                                <summary class="manager-summary">
                                    <div>
                                        <strong><?= e($link['title']) ?></strong>
                                        <small><?= e($link['url']) ?></small>
                                    </div>
                                    <div class="pill-row">
                                        <span class="pill"><?= strtoupper(e($link['type'])) ?></span>
                                        <span class="pill"><?= (int) $link['is_public'] === 1 ? 'Public' : 'Private' ?></span>
                                    </div>
                                </summary>
                                <form method="post" class="inline-form-grid">
                                    <input type="hidden" name="action" value="update_link">
                                    <input type="hidden" name="link_id" value="<?= (int) $link['id'] ?>">
                                    <label><span>Title</span><input type="text" name="title" value="<?= e($link['title']) ?>" required></label>
                                    <label><span>Type</span><select name="type"><option value="mp3" <?= $link['type'] === 'mp3' ? 'selected' : '' ?>>MP3 Audio</option><option value="mp4" <?= $link['type'] === 'mp4' ? 'selected' : '' ?>>MP4 Video</option></select></label>
                                    <label class="full-span"><span>Direct URL</span><input type="url" name="url" value="<?= e($link['url']) ?>" required></label>
                                    <label><span>Thumbnail URL</span><input type="url" name="image_url" value="<?= e($link['image_url']) ?>"></label>
                                    <label class="checkbox-field"><input type="checkbox" name="is_public" value="1" <?= (int) $link['is_public'] === 1 ? 'checked' : '' ?>><span>Public link</span></label>
                                    <label class="full-span"><span>Description</span><textarea name="description" rows="3"><?= e($link['description']) ?></textarea></label>
                                    <div class="action-row full-span"><button type="submit" class="btn btn-primary">Save Link</button></div>
                                </form>
                                <form method="post" class="danger-form" onsubmit="return confirm('Delete this link and remove it from playlists?');">
                                    <input type="hidden" name="action" value="delete_link">
                                    <input type="hidden" name="link_id" value="<?= (int) $link['id'] ?>">
                                    <button type="submit" class="btn btn-danger">Delete Link</button>
                                </form>
                            </details>
                        <?php endforeach; ?>
                    
                        <!-- Bottom Pagination -->
                        <div class="pagination-wrapper" data-pagination-wrapper="links"></div></div>
                </section>

                <section class="glass-panel admin-section" id="livestreams-admin" data-pagination-section="livestreams">
                    <div class="section-head">
                        <div><p class="eyebrow">Livestreams</p><h2>Manage M3U8 live stream sources</h2></div>
                        <span class="pill"><i class="fas fa-broadcast-tower"></i> <?= count($livestreams) ?> streams</span>
                    </div>
                    <div class="management-stack">
                        <!-- Top Pagination -->
                        <div class="pagination-wrapper" data-pagination-wrapper="livestreams"></div>
                        <div class="bulk-actions-bar" data-bulk-section="livestreams">
                            <label class="bulk-select-all">
                                <input type="checkbox" data-bulk-select-all="livestreams"> Select All
                            </label>
                            <span class="bulk-count" data-bulk-count="livestreams">0 selected</span>
                            <form method="post" class="bulk-delete-form" data-bulk-delete-form="livestreams" style="display:inline;">
                                <input type="hidden" name="action" value="bulk_delete_livestreams">
                                <button type="submit" class="bulk-delete-btn" data-bulk-delete-btn="livestreams" disabled>
                                    <i class="fas fa-trash"></i> Delete Selected (<span data-bulk-delete-count="livestreams">0</span>)
                                </button>
                            </form>
                        </div>
                        <?php foreach ($livestreams as $stream): ?>
                            <details class="manager-card" data-bulk-item="livestreams" data-item-id="<?= (int) $stream['id'] ?>">
                                <input type="checkbox" class="bulk-checkbox" data-bulk-item="livestreams" data-item-id="<?= (int) $stream['id'] ?>">
                                <summary class="manager-summary">
                                    <div>
                                        <strong><?= e($stream['title']) ?></strong>
                                        <small><?= e($stream['url']) ?></small>
                                    </div>
                                    <div class="pill-row">
                                        <span class="pill">M3U8</span>
                                        <span class="pill"><?= (int) $stream['is_public'] === 1 ? 'Public' : 'Private' ?></span>
                                    </div>
                                </summary>
                                <form method="post" class="inline-form-grid">
                                    <input type="hidden" name="action" value="update_livestream">
                                    <input type="hidden" name="livestream_id" value="<?= (int) $stream['id'] ?>">
                                    <label><span>Title</span><input type="text" name="title" value="<?= e($stream['title']) ?>" required></label>
                                    <label class="full-span"><span>M3U8 Stream URL</span><input type="url" name="url" value="<?= e($stream['url']) ?>" required></label>
                                    <label><span>Thumbnail URL</span><input type="url" name="image_url" value="<?= e($stream['image_url']) ?>"></label>
                                    <label class="checkbox-field"><input type="checkbox" name="is_public" value="1" <?= (int) $stream['is_public'] === 1 ? 'checked' : '' ?>><span>Public stream</span></label>
                                    <label class="full-span"><span>Description</span><textarea name="description" rows="3"><?= e($stream['description']) ?></textarea></label>
                                    <div class="action-row full-span"><button type="submit" class="btn btn-primary">Save Stream</button></div>
                                </form>
                                <form method="post" class="danger-form" onsubmit="return confirm('Delete this livestream and remove it from playlists?');">
                                    <input type="hidden" name="action" value="delete_livestream">
                                    <input type="hidden" name="livestream_id" value="<?= (int) $stream['id'] ?>">
                                    <button type="submit" class="btn btn-danger">Delete Stream</button>
                                </form>
                            </details>
                        <?php endforeach; ?>
                        <!-- Bottom Pagination -->
                        <div class="pagination-wrapper" data-pagination-wrapper="livestreams"></div>
                    </div>
                </section>

                <section class="dashboard-grid dashboard-grid-playlists admin-section" id="playlists-admin" data-pagination-section="playlists">
                    <article class="glass-panel">
                        <div class="section-head"><div><p class="eyebrow">Playlists</p><h2>Create a new playlist</h2></div></div>
                        <form method="post" class="stack-form">
                            <input type="hidden" name="action" value="create_playlist">
                            <label><span>Playlist Name</span><input type="text" name="playlist_name" required></label>
                            <label class="checkbox-field"><input type="checkbox" name="is_public" value="1"><span>Make playlist public</span></label>
                            <button type="submit" class="btn btn-primary">Create Playlist</button>
                        </form>
                    </article>
                    <article class="glass-panel">
                        <div class="section-head"><div><p class="eyebrow">Sources</p><h2>Playlist-ready media</h2></div></div>
                        <div class="list-row"><div><strong><?= count($playlistSources) ?></strong><small>Items available to add</small></div><span class="pill">Local + Link</span></div>
                    </article>
                </section>

                <section class="glass-panel admin-section">
                    <div class="section-head"><div><p class="eyebrow">Playlist Library</p><h2>Edit your playlists and items</h2></div></div>
                    <div class="management-stack">
                        <!-- Top Pagination -->
                        <div class="pagination-wrapper" data-pagination-wrapper="playlists"></div>
                        <div class="bulk-actions-bar" data-bulk-section="playlists">
                            <label class="bulk-select-all">
                                <input type="checkbox" data-bulk-select-all="playlists"> Select All
                            </label>
                            <span class="bulk-count" data-bulk-count="playlists">0 selected</span>
                            <form method="post" class="bulk-delete-form" data-bulk-delete-form="playlists" style="display:inline;">
                                <input type="hidden" name="action" value="bulk_delete_playlists">
                                <button type="submit" class="bulk-delete-btn" data-bulk-delete-btn="playlists" disabled>
                                    <i class="fas fa-trash"></i> Delete Selected (<span data-bulk-delete-count="playlists">0</span>)
                                </button>
                            </form>
                        </div>
                        <?php foreach ($playlists as $playlist): ?>
                            <details class="manager-card" data-bulk-item="playlists" data-item-id="<?= (int) $playlist['id'] ?>">
                                <input type="checkbox" class="bulk-checkbox" data-bulk-item="playlists" data-item-id="<?= (int) $playlist['id'] ?>">
                                <summary class="manager-summary">
                                    <div><strong><?= e($playlist['name']) ?></strong><small><?= (int) $playlist['item_count'] ?> items</small></div>
                                    <div class="pill-row"><span class="pill"><?= (int) $playlist['is_public'] === 1 ? 'Public' : 'Private' ?></span></div>
                                </summary>
                                <form method="post" class="inline-form-grid">
                                    <input type="hidden" name="action" value="update_playlist">
                                    <input type="hidden" name="playlist_id" value="<?= (int) $playlist['id'] ?>">
                                    <label><span>Playlist Name</span><input type="text" name="playlist_name" value="<?= e($playlist['name']) ?>" required></label>
                                    <label class="checkbox-field"><input type="checkbox" name="is_public" value="1" <?= (int) $playlist['is_public'] === 1 ? 'checked' : '' ?>><span>Public playlist</span></label>
                                    <div class="action-row full-span"><button type="submit" class="btn btn-primary">Save Playlist</button></div>
                                </form>
                                <form method="post" class="danger-form" onsubmit="return confirm('Delete this playlist and all items?');">
                                    <input type="hidden" name="action" value="delete_playlist">
                                    <input type="hidden" name="playlist_id" value="<?= (int) $playlist['id'] ?>">
                                    <button type="submit" class="btn btn-danger">Delete Playlist</button>
                                </form>
                                <form method="post" class="playlist-add-form">
                                    <input type="hidden" name="action" value="add_playlist_item">
                                    <input type="hidden" name="playlist_id" value="<?= (int) $playlist['id'] ?>">
                                    <label class="full-span"><span>Add Media</span><select name="media_entry" required><option value="">Select item</option><?php foreach ($playlistSources as $source): ?><option value="<?= e($source['value']) ?>"><?= e($source['label']) ?></option><?php endforeach; ?></select></label>
                                    <button type="submit" class="btn btn-secondary">Add to Playlist</button>
                                </form>
                                <div class="playlist-items">
                                    <?php foreach ($playlistItemsByPlaylist[$playlist['id']] ?? [] as $item): ?>
                                        <div class="list-row">
                                            <div><strong><?= e($item['item_title'] ?: 'Missing media') ?></strong><small><?= strtoupper(e($item['media_type'])) ?> / <?= strtoupper(e($item['item_format'] ?: 'n/a')) ?></small></div>
                                            <form method="post"><input type="hidden" name="action" value="remove_playlist_item"><input type="hidden" name="item_id" value="<?= (int) $item['item_id'] ?>"><button type="submit" class="btn btn-secondary">Remove</button></form>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </details>
                        <?php endforeach; ?>
                    
                        <!-- Bottom Pagination -->
                        <div class="pagination-wrapper" data-pagination-wrapper="playlists"></div></div>
                </section>

                <section class="glass-panel admin-section" id="chat-admin" data-pagination-section="chat">
                    <div class="section-head">
                        <div><p class="eyebrow">Chat Management</p><h2>Manage chat rooms, messages, and settings</h2></div>
                        <span class="pill"><i class="fas fa-comments"></i> <?= count($chatRooms) ?> rooms</span>
                    </div>

                    <!-- Chat Settings -->
                    <div class="glass-panel" style="margin-bottom: 20px; padding: 20px;">
                        <h3 style="margin: 0 0 16px;">Chat File Upload Settings</h3>
                        <form method="post" class="inline-form-grid">
                            <input type="hidden" name="action" value="save_chat_settings">
                            <?php
                            $chatMaxFileSize = 10;
                            $settingsResult = $conn->query("SELECT setting_value FROM site_settings WHERE setting_key = 'chat_max_file_size_mb'");
                            if ($settingsResult && $row = $settingsResult->fetch_assoc()) {
                                $chatMaxFileSize = max(1, (int) $row['setting_value']);
                            }
                            ?>
                            <label><span>Max File Size (MB)</span><input type="number" name="chat_max_file_size_mb" value="<?= $chatMaxFileSize ?>" min="1" max="100" required></label>
                            <small class="muted" style="margin-top: 4px;">Maximum file size users can upload in chat (1-100 MB)</small>
                            <div class="action-row full-span" style="margin-top: 12px;"><button type="submit" class="btn btn-primary">Save Chat Settings</button></div>
                        </form>
                    </div>

                    <div class="management-stack">
                        <!-- Top Pagination -->
                        <div class="pagination-wrapper" data-pagination-wrapper="chat"></div>
                        <div class="bulk-actions-bar" data-bulk-section="chat-rooms">
                            <label class="bulk-select-all">
                                <input type="checkbox" data-bulk-select-all="chat-rooms"> Select All
                            </label>
                            <span class="bulk-count" data-bulk-count="chat-rooms">0 selected</span>
                            <form method="post" class="bulk-delete-form" data-bulk-delete-form="chat-rooms" style="display:inline;">
                                <input type="hidden" name="action" value="bulk_delete_chat_rooms">
                                <button type="submit" class="bulk-delete-btn" data-bulk-delete-btn="chat-rooms" disabled>
                                    <i class="fas fa-trash"></i> Delete Selected (<span data-bulk-delete-count="chat-rooms">0</span>)
                                </button>
                            </form>
                        </div>
                        <?php if (empty($chatRooms)): ?>
                            <div class="empty-state">No chat rooms found.</div>
                        <?php else: ?>
                            <?php foreach ($chatRooms as $room): ?>
                                <details class="manager-card" data-bulk-item="chat-rooms" data-item-id="<?= (int) $room['id'] ?>">
                                    <input type="checkbox" class="bulk-checkbox" data-bulk-item="chat-rooms" data-item-id="<?= (int) $room['id'] ?>">
                                    <summary class="manager-summary">
                                        <div>
                                            <strong><?= e($room['name'] ?: 'Unnamed Room') ?></strong>
                                            <small><?= (int) $room['message_count'] ?> messages, <?= (int) $room['participant_count'] ?> participants</small>
                                        </div>
                                        <div class="pill-row">
                                            <span class="pill"><?= strtoupper(e($room['type'])) ?></span>
                                            <span class="pill"><?= e(date('M j, Y', strtotime($room['created_at']))) ?></span>
                                        </div>
                                    </summary>
                                    <form method="post" class="inline-form-grid">
                                        <input type="hidden" name="action" value="update_chat_room">
                                        <input type="hidden" name="room_id" value="<?= (int) $room['id'] ?>">
                                        <label class="full-span"><span>Room Name</span><input type="text" name="name" value="<?= e($room['name'] ?? '') ?>" placeholder="Room name"></label>
                                        <div class="action-row full-span"><button type="submit" class="btn btn-primary">Save Room</button></div>
                                    </form>
                                    <form method="post" class="danger-form" onsubmit="return confirm('Delete this chat room and all its messages?');">
                                        <input type="hidden" name="action" value="delete_chat_room">
                                        <input type="hidden" name="room_id" value="<?= (int) $room['id'] ?>">
                                        <button type="submit" class="btn btn-danger">Delete Room</button>
                                    </form>
                                    <?php if (!empty($chatMessages)): ?>
                                        <div class="chat-messages-preview" style="margin-top: 16px; max-height: 300px; overflow-y: auto;">
                                            <h4 style="margin: 0 0 12px; font-size: 0.9rem; color: var(--muted);">Recent Messages</h4>
                                            <?php 
                                            $roomMessages = array_filter($chatMessages, function($m) use ($room) { return $m['room_id'] == $room['id']; });
                                            if (empty($roomMessages)): 
                                            ?>
                                                <p class="muted" style="font-size: 0.85rem;">No messages in this room.</p>
                                            <?php else: ?>
                                                <?php foreach (array_slice($roomMessages, 0, 10) as $msg): ?>
                                                    <div class="chat-message-item" style="padding: 8px 12px; background: rgba(255,255,255,0.03); border-radius: 8px; margin-bottom: 8px;">
                                                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">
                                                            <strong style="font-size: 0.85rem;"><?= e($msg['username']) ?></strong>
                                                            <small class="muted" style="font-size: 0.7rem;"><?= e(date('M j, g:i A', strtotime($msg['created_at']))) ?></small>
                                                        </div>
                                                        <p style="margin: 0; font-size: 0.85rem; word-break: break-word;">
                                                            <?php if (str_starts_with($msg['message'], '[VOICE:')): ?>
                                                                <i class="fas fa-microphone"></i> Voice message
                                                            <?php elseif (str_starts_with($msg['message'], '[VIDEO:')): ?>
                                                                <i class="fas fa-video"></i> Video message
                                                            <?php else: ?>
                                                                <?= e($msg['message']) ?>
                                                            <?php endif; ?>
                                                        </p>
                                                        <form method="post" style="margin-top: 8px;">
                                                            <input type="hidden" name="action" value="delete_chat_message">
                                                            <input type="hidden" name="message_id" value="<?= (int) $msg['id'] ?>">
                                                            <button type="submit" class="btn btn-danger btn-sm" style="font-size: 0.7rem; padding: 4px 8px;" onclick="return confirm('Delete this message?');"><i class="fas fa-trash"></i> Delete</button>
                                                        </form>
                                                    </div>
                                                <?php endforeach; ?>
                                            <?php endif; ?>
                                        </div>
                                    <?php endif; ?>
                                </details>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>

                    <!-- Chat Messages Management -->
                    <div class="glass-panel" style="margin-top: 30px; padding: 20px;">
                        <h3 style="margin: 0 0 16px;"><i class="fas fa-comments"></i> Manage Chat Messages</h3>
                        
                        <!-- Room Selector -->
                        <div style="margin-bottom: 16px;">
                            <label style="display: block; margin-bottom: 8px;">
                                <strong>Filter by Chat Room:</strong>
                            </label>
                            <select id="messageRoomFilter" onchange="filterMessagesByRoom()" style="width: 100%; max-width: 400px; padding: 8px; border-radius: 6px; border: 1px solid var(--border); background: var(--bg); color: var(--text);">
                                <option value="">All Rooms</option>
                                <?php foreach ($chatRooms as $room): ?>
                                    <option value="<?= (int) $room['id'] ?>"><?= e($room['name'] ?: 'Unnamed Room') ?> (<?= (int) $room['message_count'] ?> messages)</option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <!-- Clear Room Messages -->
                        <div style="margin-bottom: 16px; padding: 12px; background: rgba(255, 77, 79, 0.05); border-radius: 8px; border: 1px solid rgba(255, 77, 79, 0.2);">
                            <form method="post" style="display: flex; gap: 10px; align-items: flex-end;">
                                <input type="hidden" name="action" value="clear_room_messages">
                                <label style="flex: 1;">
                                    <span style="font-size: 0.85rem;">Clear All Messages from Room:</span>
                                    <select name="room_id" required style="width: 100%; padding: 6px; border-radius: 4px; border: 1px solid var(--border); background: var(--bg); color: var(--text);">
                                        <option value="">Select Room...</option>
                                        <?php foreach ($chatRooms as $room): ?>
                                            <option value="<?= (int) $room['id'] ?>"><?= e($room['name'] ?: 'Unnamed Room') ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </label>
                                <button type="submit" class="btn btn-danger" onclick="return confirm('This will delete ALL messages from the selected room. Are you sure?');">
                                    <i class="fas fa-trash"></i> Clear Room
                                </button>
                            </form>
                        </div>

                        <!-- Bulk Message Delete -->
                        <div class="bulk-actions-bar" data-bulk-section="chat-messages">
                            <label class="bulk-select-all">
                                <input type="checkbox" data-bulk-select-all="chat-messages"> Select All
                            </label>
                            <span class="bulk-count" data-bulk-count="chat-messages">0 selected</span>
                            <form method="post" class="bulk-delete-form" data-bulk-delete-form="chat-messages" style="display:inline;">
                                <input type="hidden" name="action" value="bulk_delete_messages_by_room">
                                <input type="hidden" name="room_id" id="bulkDeleteRoomId" value="">
                                <button type="submit" class="bulk-delete-btn" data-bulk-delete-btn="chat-messages" disabled>
                                    <i class="fas fa-trash"></i> Delete Selected (<span data-bulk-delete-count="chat-messages">0</span>)
                                </button>
                            </form>
                        </div>

                        <div class="management-stack" id="chatMessagesList">
                            <?php if (empty($chatMessages)): ?>
                                <div class="empty-state">No chat messages found.</div>
                            <?php else: ?>
                                <?php 
                                $messagesByRoom = [];
                                foreach ($chatMessages as $msg) {
                                    $messagesByRoom[$msg['room_id']][] = $msg;
                                }
                                ?>
                                
                                <?php foreach ($chatRooms as $room): ?>
                                    <?php if (!isset($messagesByRoom[$room['id']])) continue; ?>
                                    
                                    <details class="manager-card chat-room-messages" data-room-id="<?= (int) $room['id'] ?>" data-bulk-item="chat-messages" open>
                                        <summary class="manager-summary">
                                            <div>
                                                <strong><?= e($room['name'] ?: 'Unnamed Room') ?></strong>
                                                <small><?= count($messagesByRoom[$room['id']]) ?> recent messages</small>
                                            </div>
                                        </summary>
                                        
                                        <?php foreach ($messagesByRoom[$room['id']] as $msg): ?>
                                            <div class="chat-message-item" data-bulk-item="chat-messages" data-item-id="<?= (int) $msg['id'] ?>" data-room-id="<?= (int) $room['id'] ?>" style="padding: 12px; background: rgba(255,255,255,0.03); border-radius: 8px; margin-bottom: 8px; border-left: 3px solid var(--primary);">
                                                <input type="checkbox" class="bulk-checkbox" data-bulk-item="chat-messages" data-item-id="<?= (int) $msg['id'] ?>" style="margin-right: 8px;">
                                                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;">
                                                    <div>
                                                        <strong style="font-size: 0.9rem;"><?= e($msg['username']) ?></strong>
                                                        <small class="muted" style="margin-left: 10px; font-size: 0.75rem;"><?= e(date('M j, Y g:i A', strtotime($msg['created_at']))) ?></small>
                                                    </div>
                                                </div>
                                                <p style="margin: 0 0 8px 0; font-size: 0.9rem; word-break: break-word; line-height: 1.4;">
                                                    <?php if (str_starts_with($msg['message'], '[VOICE:')): ?>
                                                        <i class="fas fa-microphone"></i> Voice message
                                                    <?php elseif (str_starts_with($msg['message'], '[VIDEO:')): ?>
                                                        <i class="fas fa-video"></i> Video message
                                                    <?php elseif (str_starts_with($msg['message'], '[FILE:')): ?>
                                                        <i class="fas fa-file"></i> File attachment
                                                    <?php else: ?>
                                                        <?= e($msg['message']) ?>
                                                    <?php endif; ?>
                                                </p>
                                                <form method="post" style="display: inline;">
                                                    <input type="hidden" name="action" value="delete_chat_message">
                                                    <input type="hidden" name="message_id" value="<?= (int) $msg['id'] ?>">
                                                    <button type="submit" class="btn btn-danger btn-sm" style="font-size: 0.75rem; padding: 4px 10px;" onclick="return confirm('Delete this message?');">
                                                        <i class="fas fa-trash"></i> Delete
                                                    </button>
                                                </form>
                                            </div>
                                        <?php endforeach; ?>
                                    </details>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                </section>

                <section class="glass-panel admin-section" id="games-admin" data-pagination-section="games">
                    <div class="section-head">
                        <div><p class="eyebrow">Games Management</p><h2>Manage Unity WebGL games, categories, and settings</h2></div>
                        <span class="pill"><i class="fas fa-gamepad"></i> <?= count($games) ?> games</span>
                    </div>

                    <!-- Game Categories -->
                    <div class="glass-panel" style="margin-bottom: 20px; padding: 20px;">
                        <h3 style="margin: 0 0 16px;"><i class="fas fa-layer-group" style="color: var(--primary); margin-right: 8px;"></i>Game Categories</h3>
                        <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 12px;">
                            <?php foreach ($gameCategories as $cat): ?>
                                <div style="padding: 12px; background: rgba(255,255,255,0.03); border-radius: 12px; border: 1px solid rgba(255,255,255,0.08);">
                                    <i class="fas <?= e($cat['icon'] ?? 'fa-gamepad') ?>" style="color: var(--primary); margin-right: 6px;"></i>
                                    <strong style="font-size: 0.9rem;"><?= e($cat['name']) ?></strong>
                                    <small class="muted" style="display: block; margin-top: 4px;"><?= e($cat['slug']) ?></small>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <div class="management-stack">
                        <!-- Top Pagination -->
                        <div class="pagination-wrapper" data-pagination-wrapper="games"></div>
                        <div class="bulk-actions-bar" data-bulk-section="games">
                            <label class="bulk-select-all">
                                <input type="checkbox" data-bulk-select-all="games"> Select All
                            </label>
                            <span class="bulk-count" data-bulk-count="games">0 selected</span>
                            <form method="post" class="bulk-delete-form" data-bulk-delete-form="games" style="display:inline;">
                                <input type="hidden" name="action" value="bulk_delete_games">
                                <button type="submit" class="bulk-delete-btn" data-bulk-delete-btn="games" disabled>
                                    <i class="fas fa-trash"></i> Delete Selected (<span data-bulk-delete-count="games">0</span>)
                                </button>
                            </form>
                        </div>
                        <?php if (empty($games)): ?>
                            <div class="empty-state">
                                <i class="fas fa-gamepad" style="font-size: 3rem; opacity: 0.3; margin-bottom: 12px;"></i>
                                <p>No games found. Users can add games from the Games page.</p>
                            </div>
                        <?php else: ?>
                            <?php foreach ($games as $game): ?>
                                <details class="manager-card" data-bulk-item="games" data-item-id="<?= (int) $game['id'] ?>">
                                    <input type="checkbox" class="bulk-checkbox" data-bulk-item="games" data-item-id="<?= (int) $game['id'] ?>">
                                    <summary class="manager-summary">
                                        <div>
                                            <strong><?= e($game['title']) ?></strong>
                                            <small>by <?= e($game['username'] ?? 'Unknown') ?></small>
                                        </div>
                                        <div class="pill-row">
                                            <span class="pill"><?= $game['game_type'] === 'embed' ? 'Embed' : 'Upload' ?></span>
                                            <?php if ($game['platform_type']): ?>
                                                <span class="pill"><i class="fas fa-<?= $game['platform_type'] === 'mobile' ? 'mobile-alt' : 'desktop' ?>"></i> <?= ucfirst($game['platform_type']) ?></span>
                                            <?php endif; ?>
                                            <?php if ($game['category_name']): ?>
                                                <span class="pill"><?= e($game['category_name']) ?></span>
                                            <?php endif; ?>
                                            <span class="pill"><?= (int) $game['is_featured'] === 1 ? 'Featured' : '' ?></span>
                                            <span class="pill"><?= (int) $game['is_public'] === 1 ? 'Public' : 'Private' ?></span>
                                            <span class="pill"><i class="fas fa-play"></i> <?= (int) $game['plays_count'] ?></span>
                                            <?php if ($game['avg_rating'] > 0): ?>
                                                <span class="pill"><i class="fas fa-star" style="color: #ffc107;"></i> <?= number_format($game['avg_rating'], 1) ?></span>
                                            <?php endif; ?>
                                            <?php if ($game['bookmarks_count'] > 0): ?>
                                                <span class="pill"><i class="fas fa-bookmark"></i> <?= (int) $game['bookmarks_count'] ?></span>
                                            <?php endif; ?>
                                        </div>
                                    </summary>
                                    
                                    <?php if ($game['cover_image']): ?>
                                        <div style="margin: 12px 0;">
                                            <img src="<?= e($game['cover_image']) ?>" alt="<?= e($game['title']) ?>" style="max-width: 100%; max-height: 200px; border-radius: 12px; object-fit: cover;">
                                        </div>
                                    <?php endif; ?>

                                    <form method="post" class="inline-form-grid">
                                        <input type="hidden" name="action" value="update_game">
                                        <input type="hidden" name="game_id" value="<?= (int) $game['id'] ?>">
                                        
                                        <label class="full-span"><span>Title</span><input type="text" name="title" value="<?= e($game['title']) ?>" required></label>
                                        
                                        <label class="full-span"><span>Description</span><textarea name="description" rows="3"><?= e($game['description'] ?? '') ?></textarea></label>
                                        
                                        <label class="full-span"><span>Embed URL</span><input type="url" name="embed_url" value="<?= e($game['embed_url'] ?? '') ?>" placeholder="https://play.unity.com/... or any embed URL"></label>
                                        
                                        <label><span>Category</span>
                                            <select name="category_id">
                                                <option value="">None</option>
                                                <?php foreach ($gameCategories as $cat): ?>
                                                    <option value="<?= (int) $cat['id'] ?>" <?= (int) $game['category_id'] === (int) $cat['id'] ? 'selected' : '' ?>><?= e($cat['name']) ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </label>

                                        <label><span>Platform Type</span>
                                            <select name="platform_type">
                                                <option value="pc" <?= $game['platform_type'] === 'pc' ? 'selected' : '' ?>>PC</option>
                                                <option value="mobile" <?= $game['platform_type'] === 'mobile' ? 'selected' : '' ?>>Mobile</option>
                                            </select>
                                        </label>
                                        
                                        <label><span>Version</span><input type="text" name="version" value="<?= e($game['version'] ?? '') ?>" placeholder="1.0.0"></label>
                                        
                                        <label><span>Developer</span><input type="text" name="developer" value="<?= e($game['developer'] ?? '') ?>" placeholder="Developer name"></label>
                                        
                                        <label><span>Unity Version</span><input type="text" name="unity_version" value="<?= e($game['unity_version'] ?? '') ?>" placeholder="2022.3 LTS"></label>
                                        
                                        <label class="full-span"><span>Tags (comma-separated)</span><input type="text" name="tags" value="<?= e($game['tags'] ?? '') ?>" placeholder="action, multiplayer, puzzle"></label>
                                        
                                        <label class="checkbox-field"><input type="checkbox" name="is_featured" value="1" <?= (int) $game['is_featured'] === 1 ? 'checked' : '' ?>><span>Featured game</span></label>
                                        
                                        <label class="checkbox-field"><input type="checkbox" name="is_public" value="1" <?= (int) $game['is_public'] === 1 ? 'checked' : '' ?>><span>Public game</span></label>
                                        
                                        <div class="action-row full-span"><button type="submit" class="btn btn-primary">Save Game</button></div>
                                    </form>
                                    
                                    <form method="post" class="danger-form" onsubmit="return confirm('Delete this game and all its files?');">
                                        <input type="hidden" name="action" value="delete_game">
                                        <input type="hidden" name="game_id" value="<?= (int) $game['id'] ?>">
                                        <button type="submit" class="btn btn-danger">Delete Game</button>
                                    </form>
                                    
                                    <!-- Game Info -->
                                    <div style="margin-top: 16px; padding: 12px; background: rgba(255,255,255,0.03); border-radius: 12px; font-size: 0.85rem;">
                                        <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 12px;">
                                            <div>
                                                <small class="muted">Uploaded</small>
                                                <div style="font-size: 0.9rem;"><?= e(date('M j, Y g:i A', strtotime($game['created_at']))) ?></div>
                                            </div>
                                            <div>
                                                <small class="muted">Last Updated</small>
                                                <div style="font-size: 0.9rem;"><?= e(date('M j, Y g:i A', strtotime($game['updated_at']))) ?></div>
                                            </div>
                                            <div>
                                                <small class="muted">Plays</small>
                                                <div style="font-size: 0.9rem;"><i class="fas fa-play"></i> <?= (int) $game['plays_count'] ?></div>
                                            </div>
                                            <?php if ($game['file_size'] > 0): ?>
                                                <div>
                                                    <small class="muted">File Size</small>
                                                    <div style="font-size: 0.9rem;"><?= number_format($game['file_size'] / 1024 / 1024, 2) ?> MB</div>
                                                </div>
                                            <?php endif; ?>
                                            <?php if ($game['file_path']): ?>
                                                <div>
                                                    <small class="muted">File Path</small>
                                                    <div style="font-size: 0.8rem; word-break: break-all;"><?= e($game['file_path']) ?></div>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </details>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    
                        <!-- Bottom Pagination -->
                        <div class="pagination-wrapper" data-pagination-wrapper="games"></div></div>
                </section>

                <section class="glass-panel admin-section" id="theme-admin">
                    <div class="section-head">
                        <div><p class="eyebrow">Theme Editor</p><h2>Edit front-end copy and color system</h2></div>
                    </div>
                    <form method="post" class="theme-editor-grid">
                        <input type="hidden" name="action" value="save_theme">
                        <label><span>Brand Name</span><input type="text" name="brand_name" value="<?= e($theme['brand_name']) ?>"></label>
                        <label><span>Hero Eyebrow</span><input type="text" name="hero_eyebrow" value="<?= e($theme['hero_eyebrow']) ?>"></label>
                        <label class="full-span"><span>Hero Title</span><input type="text" name="hero_title" value="<?= e($theme['hero_title']) ?>"></label>
                        <label class="full-span"><span>Hero Description</span><textarea name="hero_description" rows="3"><?= e($theme['hero_description']) ?></textarea></label>
                        <label><span>Library Title</span><input type="text" name="library_title" value="<?= e($theme['library_title']) ?>"></label>
                        <label><span>Library Description</span><input type="text" name="library_description" value="<?= e($theme['library_description']) ?>"></label>
                        <label><span>Music Title</span><input type="text" name="music_title" value="<?= e($theme['music_title']) ?>"></label>
                        <label><span>Music Description</span><input type="text" name="music_description" value="<?= e($theme['music_description']) ?>"></label>
                        <label><span>Videos Title</span><input type="text" name="videos_title" value="<?= e($theme['videos_title']) ?>"></label>
                        <label><span>Videos Description</span><input type="text" name="videos_description" value="<?= e($theme['videos_description']) ?>"></label>
                        <label><span>Links Title</span><input type="text" name="links_title" value="<?= e($theme['links_title']) ?>"></label>
                        <label><span>Links Description</span><input type="text" name="links_description" value="<?= e($theme['links_description']) ?>"></label>
                        <label><span>Primary Color</span><input type="color" name="primary_color" value="<?= e($theme['primary_color']) ?>"></label>
                        <label><span>Secondary Color</span><input type="color" name="secondary_color" value="<?= e($theme['secondary_color']) ?>"></label>
                        <label><span>Accent Color</span><input type="color" name="accent_color" value="<?= e($theme['accent_color']) ?>"></label>
                        <label><span>Background Start</span><input type="color" name="bg_start" value="<?= e($theme['bg_start']) ?>"></label>
                        <label><span>Background Mid</span><input type="color" name="bg_mid" value="<?= e($theme['bg_mid']) ?>"></label>
                        <label><span>Background End</span><input type="color" name="bg_end" value="<?= e($theme['bg_end']) ?>"></label>
                        <label><span>Text Color</span><input type="color" name="text_color" value="<?= e($theme['text_color']) ?>"></label>
                        <label><span>Muted Color</span><input type="color" name="muted_color" value="<?= e($theme['muted_color']) ?>"></label>
                        <label class="full-span"><span>Surface Color</span><input type="text" name="surface_color" value="<?= e($theme['surface_color']) ?>"></label>
                        <div class="action-row full-span"><button type="submit" class="btn btn-primary">Save Theme Settings</button></div>
                    </form>
                </section>

                <section class="dashboard-grid dashboard-grid-playlists admin-section" id="sliders-admin" data-pagination-section="sliders">
                    <article class="glass-panel">
                        <div class="section-head"><div><p class="eyebrow">New Slide</p><h2>Create animated front-end slider items</h2></div></div>
                        <form method="post" class="stack-form">
                            <input type="hidden" name="action" value="save_slide">
                            <input type="hidden" name="slide_id" value="0">
                            <label><span>Section</span><select name="section_key"><option value="home">Home Hero</option><option value="music">Music</option><option value="videos">Videos</option><option value="links">Links</option></select></label>
                            <label><span>Badge</span><input type="text" name="badge" placeholder="New Arrival"></label>
                            <label><span>Title</span><input type="text" name="title" required></label>
                            <label class="full-span"><span>Description</span><textarea name="description" rows="3"></textarea></label>
                            <label class="full-span"><span>Image URL</span><input type="url" name="image_url" placeholder="https://..."></label>
                            <label><span>Button Label</span><input type="text" name="cta_label" placeholder="Browse Music"></label>
                            <label><span>Button Target</span><input type="text" name="cta_target" placeholder="#music-tab"></label>
                            <label><span>Sort Order</span><input type="number" name="sort_order" value="0"></label>
                            <label class="checkbox-field"><input type="checkbox" name="is_active" value="1" checked><span>Show this slide</span></label>
                            <button type="submit" class="btn btn-primary">Create Slide</button>
                        </form>
                    </article>
                    <article class="glass-panel">
                        <div class="section-head"><div><p class="eyebrow">Slider Tips</p><h2>Front-end slide targets</h2></div></div>
                        <div class="list-stack">
                            <div class="list-row"><div><strong>`#music-tab`</strong><small>Jump into the music tab</small></div><span class="pill">Music</span></div>
                            <div class="list-row"><div><strong>`#video-tab`</strong><small>Jump into the videos tab</small></div><span class="pill">Videos</span></div>
                            <div class="list-row"><div><strong>`#link-tab`</strong><small>Jump into the links tab</small></div><span class="pill">Links</span></div>
                        </div>
                    </article>
                </section>

                <section class="glass-panel admin-section">
                    <div class="section-head"><div><p class="eyebrow">Existing Slides</p><h2>Edit current slider content</h2></div></div>
                    <div class="management-stack">
                        <!-- Top Pagination -->
                        <div class="pagination-wrapper" data-pagination-wrapper="sliders"></div>
                        <div class="bulk-actions-bar" data-bulk-section="slides">
                            <label class="bulk-select-all">
                                <input type="checkbox" data-bulk-select-all="slides"> Select All
                            </label>
                            <span class="bulk-count" data-bulk-count="slides">0 selected</span>
                            <form method="post" class="bulk-delete-form" data-bulk-delete-form="slides" style="display:inline;">
                                <input type="hidden" name="action" value="bulk_delete_slides">
                                <button type="submit" class="bulk-delete-btn" data-bulk-delete-btn="slides" disabled>
                                    <i class="fas fa-trash"></i> Delete Selected (<span data-bulk-delete-count="slides">0</span>)
                                </button>
                            </form>
                        </div>
                        <?php foreach ($slides as $slide): ?>
                            <details class="manager-card" data-bulk-item="slides" data-item-id="<?= (int) $slide['id'] ?>">
                                <input type="checkbox" class="bulk-checkbox" data-bulk-item="slides" data-item-id="<?= (int) $slide['id'] ?>">
                                <summary class="manager-summary">
                                    <div><strong><?= e($slide['title']) ?></strong><small><?= e($slide['section_key']) ?> slider</small></div>
                                    <div class="pill-row"><span class="pill"><?= (int) $slide['is_active'] === 1 ? 'Active' : 'Hidden' ?></span><span class="pill">Order <?= (int) $slide['sort_order'] ?></span></div>
                                </summary>
                                <form method="post" class="inline-form-grid">
                                    <input type="hidden" name="action" value="save_slide">
                                    <input type="hidden" name="slide_id" value="<?= (int) $slide['id'] ?>">
                                    <label><span>Section</span><select name="section_key"><option value="home" <?= $slide['section_key'] === 'home' ? 'selected' : '' ?>>Home Hero</option><option value="music" <?= $slide['section_key'] === 'music' ? 'selected' : '' ?>>Music</option><option value="videos" <?= $slide['section_key'] === 'videos' ? 'selected' : '' ?>>Videos</option><option value="links" <?= $slide['section_key'] === 'links' ? 'selected' : '' ?>>Links</option></select></label>
                                    <label><span>Badge</span><input type="text" name="badge" value="<?= e($slide['badge']) ?>"></label>
                                    <label><span>Title</span><input type="text" name="title" value="<?= e($slide['title']) ?>" required></label>
                                    <label><span>Sort Order</span><input type="number" name="sort_order" value="<?= (int) $slide['sort_order'] ?>"></label>
                                    <label class="full-span"><span>Description</span><textarea name="description" rows="3"><?= e($slide['description']) ?></textarea></label>
                                    <label class="full-span"><span>Image URL</span><input type="url" name="image_url" value="<?= e($slide['image_url']) ?>"></label>
                                    <label><span>Button Label</span><input type="text" name="cta_label" value="<?= e($slide['cta_label']) ?>"></label>
                                    <label><span>Button Target</span><input type="text" name="cta_target" value="<?= e($slide['cta_target']) ?>"></label>
                                    <label class="checkbox-field full-span"><input type="checkbox" name="is_active" value="1" <?= (int) $slide['is_active'] === 1 ? 'checked' : '' ?>><span>Active slide</span></label>
                                    <div class="action-row full-span"><button type="submit" class="btn btn-primary">Save Slide</button></div>
                                </form>
                                <form method="post" class="danger-form" onsubmit="return confirm('Delete this slide?');">
                                    <input type="hidden" name="action" value="delete_slide">
                                    <input type="hidden" name="slide_id" value="<?= (int) $slide['id'] ?>">
                                    <button type="submit" class="btn btn-danger">Delete Slide</button>
                                </form>
                            </details>
                        <?php endforeach; ?>
                    
                        <!-- Bottom Pagination -->
                        <div class="pagination-wrapper" data-pagination-wrapper="sliders"></div></div>
                </section>
            <?php endif; ?>

                <section class="glass-panel admin-section" id="passkey-admin">
                    <div class="section-head">
                        <div>
                            <p class="eyebrow">Security</p>
                            <h2>Registration Passkey</h2>
                        </div>
                    </div>
                    <div class="management-stack">
                        <article class="info-card">
                            <p>Require a passkey for new user registrations. Users must enter the correct passkey before they can create an account.</p>
                        </article>
                        
                        <?php
                        // Fetch current passkey
                        $passkeyResult = $conn->query("SELECT setting_value FROM site_settings WHERE setting_key = 'registration_passkey'");
                        $currentPasskey = '';
                        if ($passkeyResult && $passkeyResult->num_rows > 0) {
                            $currentPasskey = $passkeyResult->fetch_assoc()['setting_value'];
                        }
                        ?>
                        
                        <form method="post" class="inline-form-grid">
                            <input type="hidden" name="action" value="update_registration_passkey">
                            <label class="full-span">
                                <span>Current Passkey</span>
                                <input type="text" name="registration_passkey" value="<?= e($currentPasskey) ?>" id="passkeyField" required>
                            </label>
                            <div class="action-row">
                                <button type="submit" class="btn btn-primary">Update Passkey</button>
                                <button type="button" class="btn btn-secondary" onclick="togglePasskeyVisibility()">
                                    <i class="fas fa-eye" id="passkeyToggleIcon"></i> Show/Hide
                                </button>
                            </div>
                        </form>
                        
                        <form method="post" class="inline-form-grid" style="margin-top: 1rem;">
                            <input type="hidden" name="action" value="generate_passkey">
                            <div class="action-row">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-magic"></i> Generate New Passkey
                                </button>
                            </div>
                        </form>
                        
                        <?php if (!empty($currentPasskey)): ?>
                            <article class="info-card" style="margin-top: 1rem;">
                                <p><strong>Active Passkey:</strong> <code id="activePasskeyDisplay"><?= e($currentPasskey) ?></code></p>
                                <p style="margin-top: 0.5rem; font-size: 0.9rem; opacity: 0.8;">Share this passkey with users who need to register new accounts.</p>
                            </article>
                        <?php else: ?>
                            <article class="info-card" style="margin-top: 1rem; border-color: var(--warning);">
                                <p><strong>No passkey set.</strong> Generate a new passkey or set one manually to enable registration protection.</p>
                            </article>
                        <?php endif; ?>
                    </div>
                </section>

                <section class="glass-panel admin-section" id="suspensions-admin">
                    <div class="section-head">
                        <div>
                            <p class="eyebrow">User Management</p>
                            <h2>Suspended Users</h2>
                        </div>
                        <span class="pill"><i class="fas fa-user-slash"></i> <?= count(array_filter($users, function($u) { return !empty($u['is_suspended']); })) ?> suspended</span>
                    </div>

                    <div class="management-stack">
                        <!-- Suspend User Form -->
                        <div class="glass-panel" style="margin-bottom: 20px; padding: 20px;">
                            <h3 style="margin: 0 0 16px;"><i class="fas fa-user-slash"></i> Suspend User</h3>
                            <form method="post" class="inline-form-grid">
                                <input type="hidden" name="action" value="suspend_user">
                                <label>
                                    <span>Select User</span>
                                    <select name="user_id" required>
                                        <option value="">Choose a user...</option>
                                        <?php foreach ($users as $user): ?>
                                            <?php if (empty($user['is_suspended']) && !$user['is_admin']): ?>
                                                <option value="<?= (int) $user['id'] ?>"><?= e($user['username']) ?> (<?= e($user['email']) ?>)</option>
                                            <?php endif; ?>
                                        <?php endforeach; ?>
                                    </select>
                                </label>
                                <label class="full-span">
                                    <span>Reason for Suspension</span>
                                    <textarea name="suspension_reason" rows="3" required placeholder="Explain why this user is being suspended..."></textarea>
                                </label>
                                <label>
                                    <span>Suspend Until (optional)</span>
                                    <input type="datetime-local" name="suspended_until">
                                </label>
                                <div class="action-row full-span">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-ban"></i> Suspend User
                                    </button>
                                </div>
                            </form>
                        </div>

                        <!-- Bulk Suspend Users -->
                        <div class="glass-panel" style="margin-bottom: 20px; padding: 20px;">
                            <h3 style="margin: 0 0 16px;"><i class="fas fa-users-slash"></i> Bulk Suspend Users</h3>
                            <div class="bulk-actions-bar" data-bulk-section="users-suspend">
                                <label class="bulk-select-all">
                                    <input type="checkbox" data-bulk-select-all="users-suspend"> Select All
                                </label>
                                <span class="bulk-count" data-bulk-count="users-suspend">0 selected</span>
                                <form method="post" class="bulk-delete-form" data-bulk-delete-form="users-suspend" style="display:inline;">
                                    <input type="hidden" name="action" value="bulk_suspend_users">
                                    <label style="display: inline-block; margin: 0 10px;">
                                        <input type="text" name="bulk_suspend_reason" placeholder="Suspension reason..." required style="padding: 6px 10px; border-radius: 4px; border: 1px solid var(--border); background: var(--bg); color: var(--text);">
                                    </label>
                                    <button type="submit" class="bulk-delete-btn" data-bulk-delete-btn="users-suspend" disabled style="background: linear-gradient(135deg, var(--danger), #ff6b6b);">
                                        <i class="fas fa-ban"></i> Suspend Selected (<span data-bulk-delete-count="users-suspend">0</span>)
                                    </button>
                                </form>
                            </div>

                            <div class="management-stack">
                                <?php foreach ($users as $user): ?>
                                    <?php if (empty($user['is_suspended']) && !$user['is_admin']): ?>
                                        <div class="manager-card" data-bulk-item="users-suspend" data-item-id="<?= (int) $user['id'] ?>" style="padding: 12px;">
                                            <input type="checkbox" class="bulk-checkbox" data-bulk-item="users-suspend" data-item-id="<?= (int) $user['id'] ?>">
                                            <div style="display: flex; align-items: center; gap: 12px;">
                                                <div style="flex: 1;">
                                                    <strong><?= e($user['username']) ?></strong>
                                                    <small style="display: block; color: var(--muted);"><?= e($user['email']) ?></small>
                                                </div>
                                                <small class="muted">Joined <?= e(date('M j, Y', strtotime($user['created_at']))) ?></small>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <!-- Currently Suspended Users -->
                        <div class="glass-panel" style="padding: 20px;">
                            <h3 style="margin: 0 0 16px;"><i class="fas fa-list"></i> Currently Suspended Users</h3>
                            <?php 
                            $suspendedUsers = array_filter($users, function($u) { return !empty($u['is_suspended']); });
                            if (empty($suspendedUsers)): 
                            ?>
                                <div class="empty-state">No users are currently suspended.</div>
                            <?php else: ?>
                                <div class="management-stack">
                                    <?php foreach ($suspendedUsers as $suspendedUser): ?>
                                        <details class="manager-card" style="border-left-color: var(--danger);">
                                            <summary class="manager-summary">
                                                <div>
                                                    <strong><?= e($suspendedUser['username']) ?></strong>
                                                    <small><?= e($suspendedUser['email']) ?></small>
                                                </div>
                                                <div class="pill-row">
                                                    <span class="pill" style="background: rgba(255, 77, 79, 0.2); color: var(--danger);">SUSPENDED</span>
                                                    <?php if (!empty($suspendedUser['suspended_until'])): ?>
                                                        <span class="pill">Until <?= e(date('M j, Y', strtotime($suspendedUser['suspended_until']))) ?></span>
                                                    <?php endif; ?>
                                                    <span class="pill"><?= e(date('M j, Y', strtotime($suspendedUser['suspended_at']))) ?></span>
                                                </div>
                                            </summary>
                                            
                                            <div style="padding: 12px; background: rgba(255, 77, 79, 0.05); border-radius: 8px; margin-bottom: 12px;">
                                                <strong style="font-size: 0.85rem;">Reason:</strong>
                                                <p style="margin: 6px 0 0 0; font-size: 0.9rem;"><?= e($suspendedUser['suspension_reason'] ?: 'No reason provided') ?></p>
                                            </div>

                                            <form method="post" class="danger-form" onsubmit="return confirm('Unsuspend this user?');">
                                                <input type="hidden" name="action" value="unsuspend_user">
                                                <input type="hidden" name="user_id" value="<?= (int) $suspendedUser['id'] ?>">
                                                <button type="submit" class="btn btn-primary">
                                                    <i class="fas fa-check"></i> Unsuspend User
                                                </button>
                                            </form>
                                        </details>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </section>

                <section class="glass-panel admin-section" id="donations-admin">
                    <div class="section-head">
                        <div>
                            <p class="eyebrow">Payments</p>
                            <h2>Donations, Sponsorships & Withdrawals</h2>
                        </div>
                        <span class="pill"><i class="fas fa-hand-holding-heart"></i> Payment Management</span>
                    </div>

                    <!-- PayPal Settings -->
                    <div class="glass-panel" style="margin-bottom: 20px;">
                        <h3 style="margin: 0 0 16px;"><i class="fab fa-paypal" style="color: #003087;"></i> PayPal API Settings</h3>
                        <form method="post" class="responsive-form">
                            <input type="hidden" name="action" value="save_paypal_settings">
                            <div class="full-span">
                                <label for="paypal_mode">PayPal Mode</label>
                                <select name="paypal_mode" id="paypal_mode">
                                    <option value="sandbox" <?= $paypal_settings['mode'] === 'sandbox' ? 'selected' : '' ?>>Sandbox (Testing)</option>
                                    <option value="live" <?= $paypal_settings['mode'] === 'live' ? 'selected' : '' ?>>Live (Production)</option>
                                </select>
                            </div>
                            <div class="full-span">
                            <div class="full-span">
                                <label for="default_currency">Default Currency</label>
                                <select name="default_currency" id="default_currency">
                                    <option value="USD" <?= $paypal_settings['currency'] === 'USD' ? 'selected' : '' ?>>USD - US Dollar</option>
                                    <option value="EUR" <?= $paypal_settings['currency'] === 'EUR' ? 'selected' : '' ?>>EUR - Euro</option>
                                    <option value="GBP" <?= $paypal_settings['currency'] === 'GBP' ? 'selected' : '' ?>>GBP - British Pound</option>
                                    <option value="CAD" <?= $paypal_settings['currency'] === 'CAD' ? 'selected' : '' ?>>CAD - Canadian Dollar</option>
                                    <option value="AUD" <?= $paypal_settings['currency'] === 'AUD' ? 'selected' : '' ?>>AUD - Australian Dollar</option>
                                    <option value="JPY" <?= $paypal_settings['currency'] === 'JPY' ? 'selected' : '' ?>>JPY - Japanese Yen</option>
                                    <option value="BRL" <?= $paypal_settings['currency'] === 'BRL' ? 'selected' : '' ?>>BRL - Brazilian Real</option>
                                    <option value="MXN" <?= $paypal_settings['currency'] === 'MXN' ? 'selected' : '' ?>>MXN - Mexican Peso</option>
                                </select>
                            </div>
                            <div class="full-span">
                                <label for="paypal_client_id">PayPal Client ID</label>
                                <input type="text" name="paypal_client_id" id="paypal_client_id" value="<?= e($paypal_settings['client_id']) ?>" placeholder="Your PayPal Client ID">
                            </div>
                            <div class="full-span">
                                <button type="submit" class="btn btn-primary btn-full">
                                    <i class="fas fa-save"></i> Save PayPal Settings
                                </button>
                            </div>
                        </form>
                    </div>

                    <!-- Platform Fee Settings -->
                    <div class="glass-panel" style="margin-bottom: 20px;">
                        <h3 style="margin: 0 0 16px;"><i class="fas fa-percentage" style="color: var(--accent);"></i> Platform Fees & Limits</h3>
                        <form method="post" class="responsive-form">
                            <input type="hidden" name="action" value="save_fee_settings">
                            <div>
                                <label for="platform_fee">Platform Fee (%)</label>
                                <input type="number" name="platform_fee_percentage" id="platform_fee" value="<?= $paypal_settings['platform_fee'] ?>" min="0" max="100" step="0.1">
                            </div>
                            <div>
                                <label for="withdrawal_fee">Withdrawal Fee (%)</label>
                                <input type="number" name="withdrawal_fee_percentage" id="withdrawal_fee" value="<?= $paypal_settings['withdrawal_fee'] ?>" min="0" max="100" step="0.1">
                            </div>
                            <div>
                                <label for="min_donation">Minimum Donation ($)</label>
                                <input type="number" name="minimum_donation_amount" id="min_donation" value="<?= $paypal_settings['min_donation'] ?>" min="1" step="0.01">
                            </div>
                            <div>
                                <label for="max_donation">Maximum Donation ($)</label>
                                <input type="number" name="maximum_donation_amount" id="max_donation" value="<?= $paypal_settings['max_donation'] ?>" min="1" step="0.01">
                            </div>
                            <div>
                                <label for="min_withdrawal">Minimum Withdrawal ($)</label>
                                <input type="number" name="minimum_withdrawal_amount" id="min_withdrawal" value="<?= $paypal_settings['min_withdrawal'] ?>" min="1" step="0.01">
                            </div>
                            <div class="full-span">
                                <label class="checkbox-field">
                                    <input type="checkbox" name="donation_enabled" value="1" <?= $paypal_settings['donation_enabled'] ? 'checked' : '' ?>>
                                    <span>Enable Donations</span>
                                </label>
                            </div>
                            <div class="full-span">
                                <label class="checkbox-field">
                                    <input type="checkbox" name="sponsorship_enabled" value="1" <?= $paypal_settings['sponsorship_enabled'] ? 'checked' : '' ?>>
                                    <span>Enable Sponsorships</span>
                                </label>
                            </div>
                            <div class="full-span">
                                <button type="submit" class="btn btn-primary btn-full">
                                    <i class="fas fa-save"></i> Save Fee Settings
                                </button>
                            </div>
                        </form>
                    </div>

                    <!-- Donation Totals Dashboard -->
                    <div class="glass-panel" style="margin-bottom: 20px;">
                        <h3 style="margin: 0 0 16px;"><i class="fas fa-chart-line" style="color: var(--primary);"></i> Platform Donation Overview</h3>
                        <div id="donation-totals-dashboard">
                            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px;">
                                <div style="background: linear-gradient(135deg, rgba(120,240,197,0.15), rgba(63,210,255,0.1)); border: 1px solid rgba(120,240,197,0.3); border-radius: 16px; padding: 20px; text-align: center;">
                                    <div style="font-size: 0.85rem; color: var(--muted); margin-bottom: 8px;"><i class="fas fa-hand-holding-heart"></i> Total Donations</div>
                                    <div id="admin-total-donations" style="font-size: 1.8rem; font-weight: 800; color: var(--primary);">$0.00</div>
                                    <div id="admin-donation-count" style="font-size: 0.75rem; color: var(--muted); margin-top: 4px;">0 donations</div>
                                </div>
                                <div style="background: linear-gradient(135deg, rgba(255,107,138,0.15), rgba(255,150,180,0.1)); border: 1px solid rgba(255,107,138,0.3); border-radius: 16px; padding: 20px; text-align: center;">
                                    <div style="font-size: 0.85rem; color: var(--muted); margin-bottom: 8px;"><i class="fas fa-users"></i> Total Sponsorships</div>
                                    <div id="admin-total-sponsorships" style="font-size: 1.8rem; font-weight: 800; color: #ff6b8a;">$0.00</div>
                                    <div id="admin-sponsorship-count" style="font-size: 0.75rem; color: var(--muted); margin-top: 4px;">0 sponsorships</div>
                                </div>
                                <div style="background: rgba(255,255,255,0.05); border: 1px solid var(--line); border-radius: 16px; padding: 20px; text-align: center;">
                                    <div style="font-size: 0.85rem; color: var(--muted); margin-bottom: 8px;"><i class="fas fa-money-bill-wave"></i> Total Withdrawals (Paid)</div>
                                    <div id="admin-total-withdrawals" style="font-size: 1.8rem; font-weight: 800; color: var(--text);">$0.00</div>
                                    <div id="admin-withdrawal-count" style="font-size: 0.75rem; color: var(--muted); margin-top: 4px;">0 withdrawals</div>
                                </div>
                                <div style="background: rgba(255,193,7,0.1); border: 1px solid rgba(255,193,7,0.3); border-radius: 16px; padding: 20px; text-align: center;">
                                    <div style="font-size: 0.85rem; color: var(--muted); margin-bottom: 8px;"><i class="fas fa-clock"></i> Pending Withdrawals</div>
                                    <div id="admin-pending-withdrawals" style="font-size: 1.8rem; font-weight: 800; color: #ffc107;">$0.00</div>
                                    <div id="admin-pending-count" style="font-size: 0.75rem; color: var(--muted); margin-top: 4px;">0 pending</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Pending Withdrawals -->
                    <div class="glass-panel" style="margin-bottom: 20px;">
                        <h3 style="margin: 0 0 16px;"><i class="fas fa-hourglass-half" style="color: #ffc107;"></i> Pending Withdrawals</h3>
                        <div id="pending-withdrawals-list">
                            <div class="empty-state">
                                <i class="fas fa-hourglass-half" style="font-size: 2rem; margin-bottom: 12px;"></i>
                                <p>No pending withdrawals</p>
                            </div>
                        </div>
                    </div>

                    <!-- Recent Donations -->
                    <div class="glass-panel">
                        <h3 style="margin: 0 0 16px;"><i class="fas fa-list" style="color: var(--primary);"></i> Recent Donations & Sponsorships</h3>
                        <div id="recent-donations-list">
                            <div class="empty-state">
                                <i class="fas fa-hand-holding-heart" style="font-size: 2rem; margin-bottom: 12px;"></i>
                                <p>No donations yet</p>
                            </div>
                        </div>
                    </div>
                </section>
        </main>
    </div>

    <script src="assets/app.js"></script>
    <script>
    document.addEventListener('DOMContentLoaded', () => {
        // ===== Bulk Delete Functionality =====
        const bulkSections = ['users', 'music', 'videos', 'links', 'livestreams', 'playlists', 'games', 'slides', 'chat-rooms', 'chat-messages'];
        
        bulkSections.forEach(section => {
            const selectAllCheckbox = document.querySelector(`[data-bulk-select-all="${section}"]`);
            const deleteBtn = document.querySelector(`[data-bulk-delete-btn="${section}"]`);
            const deleteCount = document.querySelector(`[data-bulk-delete-count="${section}"]`);
            const countDisplay = document.querySelector(`[data-bulk-count="${section}"]`);
            const checkboxes = document.querySelectorAll(`[data-bulk-item="${section}"]:not(:disabled)`);
            const deleteForm = document.querySelector(`[data-bulk-delete-form="${section}"]`);

            if (!selectAllCheckbox || !deleteBtn || !deleteForm) return;

            // Hidden input to hold selected IDs
            const hiddenInput = document.createElement('input');
            hiddenInput.type = 'hidden';
            hiddenInput.name = 'item_ids[]';
            deleteForm.appendChild(hiddenInput);

            function updateBulkCount() {
                const checked = document.querySelectorAll(`[data-bulk-item="${section}"]:checked`);
                const count = checked.length;
                if (deleteCount) deleteCount.textContent = count;
                if (countDisplay) countDisplay.textContent = `${count} selected`;
                deleteBtn.disabled = count === 0;
                
                // Update hidden input values
                const ids = Array.from(checked).map(cb => cb.dataset.itemId);
                hiddenInput.value = '';
                // We need to create multiple hidden inputs for array submission
                Array.from(deleteForm.querySelectorAll('input[name="item_ids[]"]')).forEach(el => el.remove());
                ids.forEach(id => {
                    const inp = document.createElement('input');
                    inp.type = 'hidden';
                    inp.name = 'item_ids[]';
                    inp.value = id;
                    deleteForm.appendChild(inp);
                });
            }

            // Select all handler
            selectAllCheckbox.addEventListener('change', function() {
                checkboxes.forEach(cb => {
                    cb.checked = this.checked;
                });
                updateBulkCount();
            });

            // Individual checkbox handlers
            checkboxes.forEach(cb => {
                cb.addEventListener('change', updateBulkCount);
            });

            // Form submission confirmation
            deleteForm.addEventListener('submit', function(e) {
                const checked = document.querySelectorAll(`[data-bulk-item="${section}"]:checked`);
                const count = checked.length;
                if (count === 0) {
                    e.preventDefault();
                    return;
                }
                if (!confirm(`Are you sure you want to delete ${count} item(s)? This action cannot be undone.`)) {
                    e.preventDefault();
                }
            });
        });

        // ===== Floating Scroll-to-Top Button =====
        const scrollBtn = document.createElement('button');
        scrollBtn.className = 'scroll-to-top-btn';
        scrollBtn.id = 'scrollToTopBtn';
        scrollBtn.innerHTML = '<i class="fas fa-chevron-up"></i>';
        scrollBtn.title = 'Scroll to top';
        document.body.appendChild(scrollBtn);

        function toggleScrollButton() {
            if (window.scrollY > 400) {
                scrollBtn.classList.add('is-visible');
            } else {
                scrollBtn.classList.remove('is-visible');
            }
        }

        window.addEventListener('scroll', toggleScrollButton, { passive: true });
        
        scrollBtn.addEventListener('click', () => {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        });

        // ===== Passkey Visibility Toggle =====
        window.togglePasskeyVisibility = function() {
            const field = document.getElementById('passkeyField');
            const icon = document.getElementById('passkeyToggleIcon');
            if (field.type === 'password') {
                field.type = 'text';
                icon.className = 'fas fa-eye-slash';
            } else {
                field.type = 'password';
                icon.className = 'fas fa-eye';
            }

        // ===== Chat Message Room Filtering =====
        window.filterMessagesByRoom = function() {
            const selectedRoom = document.getElementById('messageRoomFilter').value;
            const roomCards = document.querySelectorAll('.chat-room-messages');
            const bulkDeleteRoomId = document.getElementById('bulkDeleteRoomId');
            
            roomCards.forEach(card => {
                const roomId = card.dataset.roomId;
                if (!selectedRoom || roomId === selectedRoom) {
                    card.style.display = 'block';
                } else {
                    card.style.display = 'none';
                }
            });
            
            // Update bulk delete room filter
            bulkDeleteRoomId.value = selectedRoom;
        };
        
        // Initialize room filter on page load
        const roomFilter = document.getElementById('messageRoomFilter');
        if (roomFilter) {
            roomFilter.addEventListener('change', window.filterMessagesByRoom);
        }
        
        // ===== Bulk Suspend Users Functionality =====
        const bulkSections = ['users-suspend'];
        
        bulkSections.forEach(section => {
            const selectAllCheckbox = document.querySelector(`[data-bulk-select-all="${section}"]`);
            const deleteBtn = document.querySelector(`[data-bulk-delete-btn="${section}"]`);
            const deleteCount = document.querySelector(`[data-bulk-delete-count="${section}"]`);
            const countDisplay = document.querySelector(`[data-bulk-count="${section}"]`);
            const checkboxes = document.querySelectorAll(`[data-bulk-item="${section}"]:not(:disabled)`);
            const deleteForm = document.querySelector(`[data-bulk-delete-form="${section}"]`);

            if (!selectAllCheckbox || !deleteBtn || !deleteForm) return;

            // Hidden input to hold selected IDs
            const hiddenInput = document.createElement('input');
            hiddenInput.type = 'hidden';
            hiddenInput.name = 'item_ids[]';
            deleteForm.appendChild(hiddenInput);

            function updateBulkCount() {
                const checked = document.querySelectorAll(`[data-bulk-item="${section}"]:checked`);
                const count = checked.length;
                if (deleteCount) deleteCount.textContent = count;
                if (countDisplay) countDisplay.textContent = `${count} selected`;
                deleteBtn.disabled = count === 0;
                
                // Update hidden input values
                Array.from(deleteForm.querySelectorAll('input[name="item_ids[]"]')).forEach(el => el.remove());
                checked.forEach(cb => {
                    const inp = document.createElement('input');
                    inp.type = 'hidden';
                    inp.name = 'item_ids[]';
                    inp.value = cb.dataset.itemId;
                    deleteForm.appendChild(inp);
                });
            }

            // Select all handler
            selectAllCheckbox.addEventListener('change', function() {
                checkboxes.forEach(cb => {
                    cb.checked = this.checked;
                });
                updateBulkCount();
            });

            // Individual checkbox handlers
            checkboxes.forEach(cb => {
                cb.addEventListener('change', updateBulkCount);
            });
        });
        };

        // ===== Donation Dashboard =====
        async function loadDonationTotals() {
            try {
                const res = await fetch('social_api.php?action=get_donation_totals');
                const data = await res.json();
                
                if (data.success && data.data) {
                    const totals = data.data;
                    
                    // Update donation totals
                    if (totals.donations) {
                        document.getElementById('admin-total-donations').textContent = '$' + parseFloat(totals.donations.total_amount || 0).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
                        document.getElementById('admin-donation-count').textContent = (totals.donations.total_count || 0) + ' donations';
                    }
                    
                    // Update sponsorship totals
                    if (totals.sponsorships) {
                        document.getElementById('admin-total-sponsorships').textContent = '$' + parseFloat(totals.sponsorships.total_amount || 0).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
                        document.getElementById('admin-sponsorship-count').textContent = (totals.sponsorships.total_count || 0) + ' sponsorships';
                    }
                    
                    // Update withdrawal totals
                    if (totals.withdrawals) {
                        document.getElementById('admin-total-withdrawals').textContent = '$' + parseFloat(totals.withdrawals.total_amount || 0).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
                        document.getElementById('admin-withdrawal-count').textContent = (totals.withdrawals.total_count || 0) + ' withdrawals';
                    }
                    
                    // Update pending withdrawals
                    if (totals.pending_withdrawals) {
                        document.getElementById('admin-pending-withdrawals').textContent = '$' + parseFloat(totals.pending_withdrawals.total_amount || 0).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
                        document.getElementById('admin-pending-count').textContent = (totals.pending_withdrawals.total_count || 0) + ' pending';
                    }
                }
            } catch (err) {
                console.error('Failed to load donation totals:', err);
            }
        }
        
        async function loadPendingWithdrawals() {
            try {
                const res = await fetch('social_api.php?action=get_withdrawal_history&status=pending');
                const data = await res.json();
                
                const container = document.getElementById('pending-withdrawals-list');
                if (!container) return;
                
                if (data.success && data.data && data.data.length > 0) {
                    container.innerHTML = data.data.map(w => `
                        <div class="manager-card" style="margin-bottom: 12px;">
                            <div class="card-header">
                                <div>
                                    <strong>${w.username || 'Unknown'}</strong>
                                    <div class="muted" style="font-size: 0.75rem;">Requested: ${new Date(w.requested_at).toLocaleDateString()}</div>
                                </div>
                                <div style="text-align: right;">
                                    <strong style="color: var(--accent); font-size: 1.2rem;">$${parseFloat(w.amount).toLocaleString('en-US', {minimumFractionDigits: 2})}</strong>
                                    <div class="muted" style="font-size: 0.75rem;">Net: $${parseFloat(w.net_amount).toLocaleString('en-US', {minimumFractionDigits: 2})}</div>
                                </div>
                            </div>
                            <div class="muted" style="font-size: 0.8rem; margin-top: 8px;">
                                PayPal: ${w.paypal_email} | Fee: $${parseFloat(w.platform_fee).toLocaleString('en-US', {minimumFractionDigits: 2})}
                            </div>
                            <div style="margin-top: 12px; display: flex; gap: 8px;">
                                <button class="btn btn-success" onclick="processWithdrawal(${w.id}, 'approve')" style="flex: 1;">
                                    <i class="fas fa-check"></i> Approve
                                </button>
                                <button class="btn btn-danger" onclick="processWithdrawal(${w.id}, 'reject')" style="flex: 1;">
                                    <i class="fas fa-times"></i> Reject
                                </button>
                                <button class="btn btn-primary" onclick="processWithdrawal(${w.id}, 'mark_paid')" style="flex: 1;">
                                    <i class="fas fa-money-bill-wave"></i> Mark Paid
                                </button>
                            </div>
                        </div>
                    `).join('');
                } else {
                    container.innerHTML = '<div class="empty-state"><i class="fas fa-hourglass-half" style="font-size: 2rem; margin-bottom: 12px;"></i><p>No pending withdrawals</p></div>';
                }
            } catch (err) {
                console.error('Failed to load pending withdrawals:', err);
            }
        }
        
        async function processWithdrawal(withdrawalId, action) {
            if (!confirm(`Are you sure you want to ${action} this withdrawal?`)) return;
            
            try {
                const formData = new FormData();
                formData.append('action', 'process_withdrawal');
                formData.append('withdrawal_id', withdrawalId);
                formData.append('action_type', action);
                formData.append('admin_notes', `${action.charAt(0).toUpperCase() + action.slice(1)} by admin`);
                
                const res = await fetch('social_api.php', {
                    method: 'POST',
                    body: formData
                });
                const data = await res.json();
                
                if (data.success) {
                    alert('Withdrawal processed successfully!');
                    loadPendingWithdrawals();
                    loadDonationTotals();
                } else {
                    alert('Error: ' + (data.error || 'Failed to process withdrawal'));
                }
            } catch (err) {
                alert('Error processing withdrawal: ' + err.message);
            }
        }
        
        // Load donation dashboard data
        if (document.getElementById('donations-admin')) {
            loadDonationTotals();
            loadPendingWithdrawals();
            // Refresh every 30 seconds
            setInterval(() => {
                loadDonationTotals();
                loadPendingWithdrawals();
            }, 30000);
        }

    });

    // Bulk Selection System
    class BulkSelectionManager {
        constructor() {
            this.sections = {};
            this.init();
        }

        init() {
            // Initialize all bulk action bars
            document.querySelectorAll('[data-bulk-section]').forEach(bar => {
                const sectionId = bar.dataset.bulkSection;
                this.sections[sectionId] = {
                    selectedItems: new Set(),
                    selectAllCheckbox: bar.querySelector('[data-bulk-select-all]'),
                    countDisplay: bar.querySelector('[data-bulk-count]'),
                    deleteButton: bar.querySelector('[data-bulk-delete-btn]'),
                    deleteCountSpan: bar.querySelector('[data-bulk-delete-count]'),
                    deleteForm: bar.querySelector('[data-bulk-delete-form]')
                };

                // Select All checkbox
                if (this.sections[sectionId].selectAllCheckbox) {
                    this.sections[sectionId].selectAllCheckbox.addEventListener('change', (e) => {
                        this.toggleSelectAll(sectionId, e.target.checked);
                    });
                }

                // Delete button form submission
                if (this.sections[sectionId].deleteButton) {
                    this.sections[sectionId].deleteButton.addEventListener('click', (e) => {
                        e.preventDefault();
                        this.handleBulkDelete(sectionId);
                    });
                }

                // Individual checkboxes
                this.initCheckboxes(sectionId);
            });
        }

        initCheckboxes(sectionId) {
            const container = document.querySelector(`[data-bulk-section="${sectionId}"]`).closest('.management-stack');
            if (!container) return;

            container.querySelectorAll('[data-bulk-item="' + sectionId + '"]').forEach(checkbox => {
                if (checkbox.disabled) return; // Skip disabled checkboxes
                
                checkbox.addEventListener('change', (e) => {
                    const itemId = e.target.dataset.itemId;
                    if (e.target.checked) {
                        this.sections[sectionId].selectedItems.add(itemId);
                    } else {
                        this.sections[sectionId].selectedItems.delete(itemId);
                    }
                    this.updateBulkUI(sectionId);
                });
            });
        }

        toggleSelectAll(sectionId, checked) {
            const container = document.querySelector(`[data-bulk-section="${sectionId}"]`).closest('.management-stack');
            if (!container) return;

            const items = container.querySelectorAll('[data-bulk-item="' + sectionId + '"]:not([disabled])');
            items.forEach(item => {
                item.checked = checked;
                const itemId = item.dataset.itemId;
                if (checked) {
                    this.sections[sectionId].selectedItems.add(itemId);
                } else {
                    this.sections[sectionId].selectedItems.delete(itemId);
                }
            });

            this.updateBulkUI(sectionId);
        }

        updateBulkUI(sectionId) {
            const section = this.sections[sectionId];
            const count = section.selectedItems.size;

            // Update count display
            if (section.countDisplay) {
                section.countDisplay.textContent = count + ' selected';
            }

            // Update delete button
            if (section.deleteButton) {
                section.deleteButton.disabled = count === 0;
            }

            // Update delete count span
            if (section.deleteCountSpan) {
                section.deleteCountSpan.textContent = count;
            }

            // Update select all checkbox state
            const container = document.querySelector(`[data-bulk-section="${sectionId}"]`).closest('.management-stack');
            if (container && section.selectAllCheckbox) {
                const allItems = container.querySelectorAll('[data-bulk-item="' + sectionId + '"]:not([disabled])');
                const allChecked = Array.from(allItems).every(item => item.checked);
                section.selectAllCheckbox.checked = allChecked;
            }
        }

        handleBulkDelete(sectionId) {
            const section = this.sections[sectionId];
            const count = section.selectedItems.size;

            if (count === 0) {
                alert('No items selected');
                return;
            }

            if (!confirm(`Are you sure you want to delete ${count} item(s)? This action cannot be undone.`)) {
                return;
            }

            // Add selected items to form as hidden inputs
            const form = section.deleteForm;
            if (!form) return;

            // Remove existing item inputs
            form.querySelectorAll('.bulk-item-input').forEach(input => input.remove());

            // Add new item inputs
            section.selectedItems.forEach(itemId => {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'item_ids[]';
                input.value = itemId;
                input.classList.add('bulk-item-input');
                form.appendChild(input);
            });

            // Submit form
            form.submit();
        }
    }

    // Initialize bulk selection when DOM is ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => new BulkSelectionManager());
    } else {
        new BulkSelectionManager();
    }

    // Client-Side Pagination System
    class PaginationManager {
        constructor() {
            this.sections = {};
            this.init();
        }

        init() {
            console.log('PaginationManager initializing...');
            // Find all pagination sections
            document.querySelectorAll('[data-pagination-section]').forEach(section => {
                const sectionId = section.id;
                const itemType = section.dataset.paginationSection;
                console.log('Found section:', sectionId, 'with type:', itemType);
                
                // Find all bulk items (manager-card elements)
                const items = Array.from(section.querySelectorAll('.manager-card[data-bulk-item="' + itemType + '"]'));
                console.log('Found', items.length, 'items for', itemType);
                if (items.length === 0) return;

                // Load saved items per page from localStorage
                const savedPerPage = localStorage.getItem('items_per_page_' + itemType);
                const itemsPerPage = savedPerPage ? parseInt(savedPerPage) : 25;

                this.sections[sectionId] = {
                    itemType: itemType,
                    items: items,
                    currentPage: 1,
                    itemsPerPage: itemsPerPage,
                    totalPages: Math.ceil(items.length / itemsPerPage)
                };

                console.log('Initializing pagination for', sectionId, ':', items.length, 'items,', itemsPerPage, 'per page');
                this.renderPagination(sectionId);
                this.updateDisplay(sectionId);
            });
        }

        renderPagination(sectionId) {
            const section = this.sections[sectionId];
            if (!section || section.totalPages <= 1) return;

            const html = this.createPaginationHTML(section.currentPage, section.totalPages, section.itemsPerPage, section.itemType);
            
            // Update all pagination wrappers in this section
            document.querySelectorAll(`[data-pagination-wrapper="${section.itemType}"]`).forEach(wrapper => {
                wrapper.innerHTML = html;
            });

            // Attach event listeners
            this.attachPaginationEvents(sectionId);
        }

        createPaginationHTML(currentPage, totalPages, itemsPerPage, sectionId) {
            let html = '<div class="pagination-controls">';
            
            // Items per page selector
            html += '<div class="pagination-info">';
            html += '<label>Items per page:</label>';
            html += '<select class="items-per-page" data-section="' + sectionId + '">';
            [10, 25, 50, 100, 250, 500].forEach(opt => {
                html += '<option value="' + opt + '"' + (itemsPerPage === opt ? ' selected' : '') + '>' + opt + '</option>';
            });
            html += '</select></div>';

            // Page navigation
            html += '<div class="page-navigation">';
            
            // Prev button
            html += currentPage > 1 
                ? '<a href="#" class="page-link" data-page="' + (currentPage - 1) + '">« Prev</a>'
                : '<span class="page-link disabled">« Prev</span>';

            // Page numbers
            const startPage = Math.max(1, currentPage - 2);
            const endPage = Math.min(totalPages, currentPage + 2);

            if (startPage > 1) {
                html += '<a href="#" class="page-link" data-page="1">1</a>';
                if (startPage > 2) html += '<span class="page-ellipsis">...</span>';
            }

            for (let i = startPage; i <= endPage; i++) {
                html += i === currentPage
                    ? '<span class="page-link active">' + i + '</span>'
                    : '<a href="#" class="page-link" data-page="' + i + '">' + i + '</a>';
            }

            if (endPage < totalPages) {
                if (endPage < totalPages - 1) html += '<span class="page-ellipsis">...</span>';
                html += '<a href="#" class="page-link" data-page="' + totalPages + '">' + totalPages + '</a>';
            }

            // Next button
            html += currentPage < totalPages
                ? '<a href="#" class="page-link" data-page="' + (currentPage + 1) + '">Next »</a>'
                : '<span class="page-link disabled">Next »</span>';

            html += '</div>';

            // Summary
            const startItem = ((currentPage - 1) * itemsPerPage) + 1;
            const endItem = Math.min(currentPage * itemsPerPage, section.items.length);
            html += '<div class="pagination-summary">Showing ' + startItem + '-' + endItem + ' of ' + section.items.length + ' items</div>';
            
            html += '</div>';
            return html;
        }

        attachPaginationEvents(sectionId) {
            const section = this.sections[sectionId];
            if (!section) return;
            const wrapper = document.querySelector(`[data-pagination-wrapper="${section.itemType}"]`);
            if (!wrapper) return;

            // Items per page change
            const select = wrapper.querySelector('.items-per-page');
            if (select) {
                select.addEventListener('change', (e) => {
                    const newPerPage = parseInt(e.target.value);
                    localStorage.setItem('items_per_page_' + sectionId, newPerPage);
                    this.updatePerPage(sectionId, newPerPage);
                });
            }

            // Page link clicks
            wrapper.querySelectorAll('.page-link[data-page]').forEach(link => {
                link.addEventListener('click', (e) => {
                    e.preventDefault();
                    const page = parseInt(link.dataset.page);
                    if (link.classList.contains('disabled') || link.classList.contains('active')) return;
                    this.goToPage(sectionId, page);
                });
            });
        }

        goToPage(sectionId, page) {
            if (!this.sections[sectionId]) return;
            const section = this.sections[sectionId];
            section.currentPage = Math.max(1, Math.min(page, section.totalPages));
            console.log('Going to page', page, 'for', sectionId);
            this.updateDisplay(sectionId);
            this.renderPagination(sectionId);
            
            // Scroll to section
            document.getElementById(sectionId)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }

        updatePerPage(sectionId, itemsPerPage) {
            if (!this.sections[sectionId]) return;
            const section = this.sections[sectionId];
            section.itemsPerPage = itemsPerPage;
            section.totalPages = Math.ceil(section.items.length / itemsPerPage);
            section.currentPage = 1;
            console.log('Updated to', itemsPerPage, 'per page for', sectionId);
            this.updateDisplay(sectionId);
            this.renderPagination(sectionId);
        }

        updateDisplay(sectionId) {
            const section = this.sections[sectionId];
            if (!section) return;

            const start = (section.currentPage - 1) * section.itemsPerPage;
            const end = start + section.itemsPerPage;

            section.items.forEach((item, index) => {
                if (index >= start && index < end) {
                    item.style.display = '';
                    item.classList.remove('paginated-hidden');
                } else {
                    item.style.display = 'none';
                    item.classList.add('paginated-hidden');
                }
            });
        }
    }

    // Initialize pagination when DOM is ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => new PaginationManager());
    } else {
        new PaginationManager();
    }
    </script>
    <?php require_once 'includes/footer.php'; ?>
</body>
</html>
