<?php
session_start();
require 'db.php';
require 'lang.php';

// Система лицензирования удалена - Видеозвонки теперь бесплатны для всех.


// Проверка доступа администратора (Роль Admin ИЛИ ID 1)
if (!isset($_SESSION['user_id']) || ($_SESSION['user_id'] != 1 && (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin'))) {
    header("Location: index.php");
    exit;
}

// Обработка действий
$message = '';
$action = $_GET['action'] ?? 'dashboard';

// Начальная загрузка настроек (рано для состояния лицензии)
$earlySettings = [];
try {
    $stmt = $pdo->query("SELECT name, value FROM settings");
    while ($row = $stmt->fetch()) {
        $earlySettings[$row['name']] = $row['value'];
    }
} catch (Exception $e) {
}

$isInitiallyActivated = true; // Всегда активировано

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Обновление настроек
    if (isset($_POST['update_settings'])) {
        $title = trim($_POST['site_title']);
        $favicon = trim($_POST['favicon']);
        $footer = trim($_POST['footer_text']);
        $defLang = trim($_POST['default_lang']);

        // Обработка загрузки файла логотипа
        if (isset($_FILES['logo_file']) && $_FILES['logo_file']['error'] === UPLOAD_ERR_OK) {
            $fileTmpPath = $_FILES['logo_file']['tmp_name'];
            $fileName = $_FILES['logo_file']['name'];
            $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
            $allowedExtensions = ['png', 'jpg', 'jpeg', 'gif', 'ico', 'svg'];

            if (in_array($fileExtension, $allowedExtensions)) {
                $destPath = 'assets/site_logo.' . $fileExtension;
                if (move_uploaded_file($fileTmpPath, $destPath)) {
                    $favicon = $destPath;
                }
            }
        }

        $pdo->prepare("REPLACE INTO settings (name, value) VALUES ('site_title', ?)")->execute([$title]);
        $pdo->prepare("REPLACE INTO settings (name, value) VALUES ('favicon', ?)")->execute([$favicon]);
        $pdo->prepare("REPLACE INTO settings (name, value) VALUES ('footer_text', ?)")->execute([$footer]);
        $pdo->prepare("REPLACE INTO settings (name, value) VALUES ('default_lang', ?)")->execute([$defLang]);

        $enableVoice = isset($_POST['enable_voice']) ? '1' : '0';
        $pdo->prepare("REPLACE INTO settings (name, value) VALUES ('enable_voice', ?)")->execute([$enableVoice]);

        // Видео всегда включено, если отмечено, проверка лицензии не требуется
        $enableVideo = isset($_POST['enable_video']) ? '1' : '0';
        $pdo->prepare("REPLACE INTO settings (name, value) VALUES ('enable_video', ?)")->execute([$enableVideo]);

        if (!$message) {
            $message = isset($t['settings_updated']) ? $t['settings_updated'] : "Settings updated!";
        }
    }



    // Переключение статуса блокировки
    if (isset($_POST['toggle_block'])) {
        $id = intval($_POST['user_id']);
        $newStatus = ($_POST['current_status'] === 'blocked') ? 'active' : 'blocked';
        if ($id != $_SESSION['user_id']) {
            $stmt = $pdo->prepare("UPDATE users SET status = ? WHERE id = ?");
            $stmt->execute([$newStatus, $id]);
            $message = (isset($t['status_updated']) ? $t['status_updated'] : "Status updated.") . " ($newStatus)";
        }
    }

    // Управление пользователями
    if (isset($_POST['delete_user'])) {
        $id = intval($_POST['user_id']);
        if ($id != $_SESSION['user_id']) { // Самозащита
            $pdo->prepare("DELETE FROM users WHERE id = ?")->execute([$id]);
            $message = isset($t['user_deleted']) ? $t['user_deleted'] : "User deleted.";
        }
    }

    // Управление ролями (user -> admin -> bot -> user)
    if (isset($_POST['toggle_role'])) {
        $id = intval($_POST['user_id']);
        $currentRole = $_POST['current_role'];

        $newRole = 'user';
        if ($currentRole === 'user') $newRole = 'admin';
        elseif ($currentRole === 'admin') $newRole = 'bot';
        elseif ($currentRole === 'bot') $newRole = 'user';

        if ($id != $_SESSION['user_id']) { // Защита текущего администратора
            $stmt = $pdo->prepare("UPDATE users SET role = ? WHERE id = ?");
            $stmt->execute([$newRole, $id]);
            $message = $t['role_updated'] . " " . strtoupper($newRole) . ".";
        }
    }

    // Добавить нового пользователя / администратора
    if (isset($_POST['create_user'])) {
        $username = trim($_POST['new_username']);
        $password = password_hash($_POST['new_password'], PASSWORD_DEFAULT);
        $role = $_POST['new_role'] === 'admin' ? 'admin' : 'user';

        if (!empty($username) && !empty($_POST['new_password'])) {
            $stmt = $pdo->prepare("INSERT INTO users (username, password, role) VALUES (?, ?, ?)");
            try {
                $stmt->execute([$username, $password, $role]);
                $message = (isset($t['user_created']) ? $t['user_created'] : "User created.") . " ($username)";
            } catch (Exception $e) {
                $message = isset($t['error_username_taken']) ? $t['error_username_taken'] : "Error: Username might be taken.";
            }
        }
    }

    // Управление комнатами
    if (isset($_POST['delete_room'])) {
        $id = intval($_POST['room_id']);
        if ($id != 1) { // Защита Общей комнаты
            $pdo->prepare("DELETE FROM rooms WHERE id = ?")->execute([$id]);
            $pdo->prepare("DELETE FROM messages WHERE room_id = ?")->execute([$id]); // Очистка
            $message = isset($t['room_deleted']) ? $t['room_deleted'] : "Room deleted.";
        }
    }
}

// Получение статистики
$stats = [
    'users' => $pdo->query("SELECT count(*) FROM users")->fetchColumn(),
    'messages' => $pdo->query("SELECT count(*) FROM messages")->fetchColumn(),
    'rooms' => $pdo->query("SELECT count(*) FROM rooms")->fetchColumn(),
];

// Получение данных
$users = $pdo->query("SELECT * FROM users ORDER BY created_at DESC")->fetchAll();
$rooms_list = $pdo->query("SELECT r.*, u.username as creator_name FROM rooms r LEFT JOIN users u ON r.created_by = u.id ORDER BY r.created_at ASC")->fetchAll();

// Получение настроек
$stmt = $pdo->query("SELECT * FROM settings");
$settings = [];
while ($row = $stmt->fetch()) {
    $settings[$row['name']] = $row['value'];
}
$siteTitle = $settings['site_title'] ?? 'ChatApp';
$siteFavicon = $settings['favicon'] ?? 'assets/logo.png';
$footerText = $settings['footer_text'] ?? 'by ANUS_TANGA';
$defaultLang = $settings['default_lang'] ?? 'en';
$enableVoice = $settings['enable_voice'] ?? '1';
$enableVideo = $settings['enable_video'] ?? '1';
$videoLicenseKey = ''; // Больше не используется
$isActivated = true; // Всегда активировано

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Admin Panel - <?php echo htmlspecialchars($siteTitle); ?></title>
    <link rel="stylesheet" href="assets/style.css">
    <link rel="stylesheet" href="assets/touch-optimizations.css">
    <link rel="icon" href="<?php echo htmlspecialchars($siteFavicon); ?>" type="image/png">
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg-gradient: linear-gradient(135deg, #0f0c29, #302b63, #24243e);
            --bg-main: #0f1011;
            --bg-sidebar: rgba(22, 24, 26, 0.8);
            --accent: #9d4edd;
            --accent-hover: #7b2cbf;
            --accent-glow: rgba(157, 78, 221, 0.4);
            --danger: #ff453a;
            --card-bg: rgba(30, 30, 30, 0.6);
            --border: rgba(255, 255, 255, 0.08);
            --text-main: #ffffff;
            --text-dim: #b0b0b0;
            --glass-border: rgba(255, 255, 255, 0.1);
        }

        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            font-family: 'Outfit', sans-serif;
            background: var(--bg-gradient);
            background-size: 400% 400%;
            animation: gradientBG 15s ease infinite;
            color: var(--text-main);
            -webkit-font-smoothing: antialiased;
            min-height: 100vh;
        }

        @keyframes gradientBG {
            0% {
                background-position: 0% 50%;
            }

            50% {
                background-position: 100% 50%;
            }

            100% {
                background-position: 0% 50%;
            }
        }

        .admin-layout {
            display: flex;
            height: 100vh;
            backdrop-filter: blur(10px);
            background: rgba(0, 0, 0, 0.4);
            width: 100%;
            overflow: hidden;
        }

        /* Sidebar */
        .admin-sidebar {
            width: 280px;
            background: var(--bg-sidebar);
            padding: 40px 25px;
            border-right: 1px solid var(--border);
            display: flex;
            flex-direction: column;
            flex-shrink: 0;
            z-index: 100;
            backdrop-filter: blur(20px);
            height: 100%;
        }

        .admin-sidebar h2 {
            margin: 0;
            color: var(--accent);
            font-size: 1.5rem;
            font-weight: 700;
            letter-spacing: -0.5px;
        }

        .admin-nav {
            margin-top: 50px;
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        .admin-nav a {
            display: flex;
            align-items: center;
            padding: 14px 20px;
            color: rgba(255, 255, 255, 0.6);
            text-decoration: none;
            border-radius: 14px;
            margin-bottom: 8px;
            font-size: 1rem;
            font-weight: 500;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            white-space: nowrap;
        }

        .admin-nav a:hover:not(.active):not(.back-link) {
            color: #fff;
            background: rgba(255, 255, 255, 0.05);
            transform: translateX(5px);
        }

        .admin-nav a.active {
            background: var(--accent) !important;
            color: #fff !important;
            box-shadow: 0 4px 15px rgba(157, 78, 221, 0.3);
        }

        /* Content Area */
        .admin-content {
            flex: 1;
            padding: 40px;
            background: var(--bg-main);
            overflow-y: auto;
            scroll-behavior: smooth;
        }

        h1 {
            font-size: 2.2rem;
            font-weight: 700;
            margin: 0 0 30px 0;
            letter-spacing: -1px;
        }

        section {
            scroll-margin-top: 100px;
        }

        /* Stats Grid */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 40px;
        }

        .stat-card {
            background: var(--card-bg);
            padding: 25px;
            border-radius: 20px;
            text-align: left;
            border: 1px solid var(--border);
            transition: transform 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-5px);
        }

        .welcome-card {
            background: var(--card-bg);
            padding: 30px;
            border-radius: 20px;
            border: 1px solid var(--border);
        }

        .admin-brand {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 30px;
        }

        .stat-num {
            font-size: 2.4rem;
            font-weight: 700;
            color: var(--accent);
            line-height: 1;
            margin-bottom: 8px;
        }

        .stat-label {
            color: var(--text-dim);
            font-size: 0.9rem;
            font-weight: 500;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        /* Tables */
        .table-wrapper {
            width: 100%;
            overflow-x: auto;
            background: var(--card-bg);
            border-radius: 20px;
            border: 1px solid var(--border);
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
        }

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

        .hide-mobile {
            display: table-cell;
        }

        th {
            background: rgba(255, 255, 255, 0.02);
            padding: 12px 18px;
            text-align: left;
            color: var(--text-dim);
            font-size: 0.7rem;
            text-transform: uppercase;
            letter-spacing: 1px;
            font-weight: 700;
            border-bottom: 1px solid var(--border);
            white-space: nowrap;
        }

        @media (max-width: 992px) {
            .hide-mobile {
                display: none !important;
            }

            td,
            th {
                padding: 10px 8px;
                font-size: 0.8rem;
            }

            .btn-sm {
                padding: 5px 8px !important;
                font-size: 0.7rem !important;
            }

            .btn-text {
                display: none;
            }

            .table-wrapper {
                border-radius: 12px;
            }
        }

        td {
            padding: 14px 18px;
            border-bottom: 1px solid var(--border);
            font-size: 0.9rem;
            vertical-align: middle;
            word-break: break-all;
        }

        tr:last-child td {
            border-bottom: none;
        }

        tr:hover td {
            background: rgba(255, 255, 255, 0.015);
        }

        /* Buttons & Forms */
        .btn {
            border: none;
            border-radius: 10px;
            padding: 8px 16px;
            font-weight: 600;
            font-size: 0.85rem;
            cursor: pointer;
            transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            height: 38px;
        }

        .btn-primary {
            background: var(--accent);
            color: #fff;
        }

        .btn-primary:hover {
            background: var(--accent-hover);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px var(--accent-glow);
        }

        .btn-danger {
            background: var(--danger);
            color: #fff;
        }

        .btn-danger:hover {
            background: #ff5b52;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(255, 69, 58, 0.3);
        }

        .form-group {
            margin-bottom: 0;
        }

        .form-group label {
            display: block;
            margin-bottom: 10px;
            color: var(--text-dim);
            font-size: 0.8rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            height: 52px;
            padding: 0 20px;
            background: rgba(255, 255, 255, 0.03);
            border: 1px solid var(--border);
            color: #fff;
            border-radius: 14px;
            font-family: inherit;
            font-size: 0.95rem;
            outline: none;
            transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
            appearance: none;
        }

        .form-group select {
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%2398989d' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 15px center;
            background-size: 18px;
            padding-right: 45px;
        }

        .form-group select option {
            background: #16181a;
            color: #fff;
            padding: 10px;
        }

        .form-group input:focus,
        .form-group select:focus {
            border-color: var(--accent);
            background: rgba(157, 78, 221, 0.1);
            box-shadow: 0 0 0 4px rgba(157, 78, 221, 0.2);
        }

        .form-group input::placeholder {
            color: rgba(255, 255, 255, 0.2);
        }

        /* Mobile Adjustments */
        @media (max-width: 992px) {
            .admin-layout {
                flex-direction: column;
                height: auto;
                min-height: 100vh;
                overflow: visible;
            }

            .admin-sidebar {
                width: 100%;
                padding: 8px 12px;
                height: auto;
                border-right: none;
                border-bottom: 1px solid var(--border);
                position: sticky;
                top: 0;
                flex-direction: row;
                align-items: center;
                justify-content: space-between;
                gap: 10px;
                background: rgba(22, 24, 26, 0.98);
                backdrop-filter: blur(30px);
                z-index: 2000;
            }

            .admin-sidebar img,
            .admin-sidebar h2 {
                display: none;
            }

            .admin-brand {
                display: none;
            }

            .admin-nav {
                margin-top: 0;
                display: flex;
                flex-direction: row;
                gap: 5px;
                overflow-x: auto;
                padding: 5px 0;
                flex: 1;
                justify-content: flex-start;
                scrollbar-width: none;
                -webkit-overflow-scrolling: touch;
            }

            .admin-nav::-webkit-scrollbar {
                display: none;
            }

            .admin-nav a {
                padding: 8px 12px;
                font-size: 0.8rem;
                margin-bottom: 0;
                flex-shrink: 0;
                border-radius: 10px;
                background: rgba(255, 255, 255, 0.03);
            }

            .admin-nav .back-link {
                margin-top: 0;
                padding: 8px 12px;
                background: rgba(157, 78, 221, 0.1) !important;
                border: 1px solid rgba(157, 78, 221, 0.2);
                margin-left: auto;
            }

            .admin-content {
                padding: 12px;
                width: 100%;
                overflow-x: hidden;
            }

            .welcome-card {
                padding: 15px;
                border-radius: 12px;
            }

            h1 {
                font-size: 1.3rem !important;
                margin-bottom: 12px;
                line-height: 1.2;
                word-wrap: break-word;
            }

            section {
                scroll-margin-top: 110px;
                margin-bottom: 40px !important;
            }

            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
                gap: 8px;
            }

            .stat-num {
                font-size: 1.4rem;
            }

            .stat-card {
                padding: 12px;
                border-radius: 15px;
            }

            .user-form {
                grid-template-columns: 1fr !important;
                gap: 12px !important;
            }

            .user-form .btn-primary {
                height: 45px !important;
            }
        }

        @media (max-width: 480px) {
            .stats-grid {
                grid-template-columns: 1fr;
            }

            h1 {
                font-size: 1.2rem !important;
            }

            .admin-nav a {
                padding: 8px 10px;
                font-size: 0.75rem;
            }

            .admin-nav .back-link span {
                display: none;
            }
        }

        /* Improved UI Classes */
        .btn-outline {
            background: rgba(255, 255, 255, 0.03);
            border: 1px solid rgba(255, 255, 255, 0.1);
            color: #fff;
        }

        .btn-outline:hover {
            background: rgba(255, 255, 255, 0.08);
            border-color: rgba(255, 255, 255, 0.2);
            transform: translateY(-2px);
        }

        .btn-sm {
            padding: 8px 16px !important;
            font-size: 0.8rem !important;
            border-radius: 10px !important;
            height: auto !important;
        }

        /* File Input Styling */
        .file-upload-wrapper {
            position: relative;
            width: 100%;
            height: 52px;
            background: rgba(255, 255, 255, 0.03);
            border: 1px solid var(--border);
            border-radius: 14px;
            display: flex;
            align-items: center;
            padding: 0 20px;
            overflow: hidden;
            cursor: pointer;
            transition: all 0.2s;
        }

        .file-upload-wrapper:hover {
            border-color: var(--accent);
            background: rgba(255, 255, 255, 0.06);
        }

        .file-upload-wrapper input[type="file"] {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            cursor: pointer;
        }

        .file-upload-text {
            color: var(--text-dim);
            font-size: 0.95rem;
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .file-upload-btn {
            background: var(--accent);
            color: #fff;
            padding: 6px 12px;
            border-radius: 8px;
            font-size: 0.75rem;
            font-weight: 700;
            text-transform: uppercase;
            margin-left: 10px;
        }

        .admin-nav .back-link {
            padding: 14px 20px;
            margin-top: 25px;
            border-radius: 14px;
            background: rgba(157, 78, 221, 0.1);
            color: var(--accent) !important;
            display: flex;
            align-items: center;
            gap: 10px;
            border: 1px solid rgba(157, 78, 221, 0.2);
            font-weight: 700;
        }

        .admin-nav .back-link:hover {
            background: rgba(157, 78, 221, 0.2);
            transform: scale(1.02);
            color: #fff !important;
        }

        /* Toggle Switch */
        .toggle-switch {
            position: relative;
            display: inline-block;
            width: 50px;
            height: 26px;
            margin-right: 12px;
            flex-shrink: 0;
        }

        .toggle-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(255, 255, 255, 0.1);
            transition: .4s;
            border-radius: 34px;
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .slider:before {
            position: absolute;
            content: "";
            height: 18px;
            width: 18px;
            left: 3px;
            bottom: 3px;
            background-color: #fff;
            transition: .4s;
            border-radius: 50%;
        }

        input:checked+.slider {
            background-color: var(--primary);
            border-color: var(--primary);
        }

        input:focus+.slider {
            box-shadow: 0 0 1px var(--primary);
        }

        input:checked+.slider:before {
            transform: translateX(24px);
        }

        .feature-item {
            display: flex;
            align-items: center;
            padding: 10px;
            border-radius: 8px;
            transition: background 0.2s;
        }

        .feature-item:hover {
            background: rgba(255, 255, 255, 0.05);
        }
    </style>
</head>

<body>
    <div class="admin-layout">
        <div class="admin-sidebar">
            <div class="admin-brand">
                <img src="<?php echo htmlspecialchars($siteFavicon); ?>" style="width:32px; height:32px;">
                <h2>Admin</h2>
            </div>
            <nav class="admin-nav">
                <a href="#dashboard" class="nav-link active"><?php echo $t['dashboard']; ?></a>
                <a href="#users" class="nav-link"><?php echo $t['users']; ?></a>
                <a href="#rooms" class="nav-link"><?php echo $t['rooms']; ?></a>

                <a href="#settings" class="nav-link"><?php echo $t['settings']; ?></a>

                <a href="./" class="nav-link back-link"><span>&larr;</span> <span><?php echo $t['back_to_chat']; ?></span></a>
            </nav>
        </div>

        <div class="admin-content" style="scroll-behavior: smooth;">
            <?php if ($message): ?>
                <div style="background: rgba(76, 209, 55, 0.1); color: #4cd137; padding: 15px 20px; border-radius: 12px; margin-bottom: 30px; border: 1px solid rgba(76, 209, 55, 0.2); font-weight: 500;">
                    <?php echo $message; ?>
                </div>
            <?php endif; ?>

            <!-- DASHBOARD SECTION -->
            <section id="dashboard" style="margin-bottom: 60px;">
                <h1><?php echo $t['dashboard']; ?></h1>
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-num"><?php echo $stats['users']; ?></div>
                        <div class="stat-label"><?php echo $t['total_users']; ?></div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-num"><?php echo $stats['messages']; ?></div>
                        <div class="stat-label"><?php echo $t['total_msgs']; ?></div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-num"><?php echo $stats['rooms']; ?></div>
                        <div class="stat-label"><?php echo $t['active_rooms']; ?></div>
                    </div>
                </div>

                <div class="welcome-card">
                    <h3 style="margin-top:0;">Система</h3>
                    <p style="color: var(--text-dim); line-height: 1.6;"><?php echo $t['admin_welcome']; ?></p>
                </div>
            </section>

            <!-- USERS SECTION -->
            <section id="users" style="margin-bottom: 60px; padding-top: 20px;">
                <h1><?php echo $t['users']; ?></h1>
                <div style="background: var(--card-bg); padding: 25px; border-radius: 20px; border: 1px solid var(--border); margin-bottom: 30px;">
                    <h3 style="margin-top:0; margin-bottom:20px;"><?php echo $t['create_user']; ?></h3>
                    <form method="POST" class="user-form" style="display:grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap:20px; align-items: flex-end;">
                        <div class="form-group">
                            <label><?php echo $t['username']; ?></label>
                            <input type="text" name="new_username" placeholder="e.g. john_doe" required>
                        </div>
                        <div class="form-group">
                            <label><?php echo $t['password']; ?></label>
                            <input type="password" name="new_password" placeholder="••••••••" required>
                        </div>
                        <div class="form-group">
                            <label><?php echo $t['role']; ?></label>
                            <select name="new_role">
                                <option value="user"><?php echo $t['standard_user']; ?></option>
                                <option value="admin"><?php echo $t['administrator']; ?></option>
                            </select>
                        </div>
                        <div>
                            <button type="submit" name="create_user" class="btn btn-primary" style="height:52px; width:100%;"><?php echo $t['create_account']; ?></button>
                        </div>
                    </form>
                </div>

                <div class="table-wrapper">
                    <table>
                        <thead>
                            <tr>
                                <th><?php echo $t['users']; ?></th>
                                <th class="hide-mobile">ID</th>
                                <th>Role</th>
                                <th class="hide-mobile"><?php echo $t['last_activity']; ?></th>
                                <th><?php echo $t['status']; ?></th>
                                <th style="text-align:right; padding-right:20px;"><?php echo $t['actions']; ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($users as $u): ?>
                                <tr style="<?php echo $u['status'] == 'blocked' ? 'opacity:0.6; grayscale(1);' : ''; ?>">
                                    <td>
                                        <div style="display:flex; align-items:center; gap:12px;">
                                            <img src="<?php echo htmlspecialchars($u['avatar'] ?? 'assets/default_avatar.png'); ?>" style="width:36px; height:36px; border-radius:50%; object-fit:cover; border:1px solid var(--border);">
                                            <div style="font-weight:600; color:#fff;"><?php echo htmlspecialchars($u['username']); ?></div>
                                        </div>
                                    </td>
                                    <td class="hide-mobile" style="color:var(--text-dim); font-size:0.8rem; font-family:monospace;">#<?php echo $u['id']; ?></td>
                                    <td>
                                        <form method="POST" style="display:inline;">
                                            <input type="hidden" name="user_id" value="<?php echo $u['id']; ?>">
                                            <input type="hidden" name="current_role" value="<?php echo $u['role']; ?>">
                                            <button type="submit" name="toggle_role" class="btn btn-sm <?php echo $u['role'] == 'admin' ? 'btn-primary' : 'btn-outline'; ?>" <?php echo $u['id'] == $_SESSION['user_id'] ? 'disabled' : ''; ?> style="min-width:60px;">
                                                <?php echo strtoupper($u['role']); ?>
                                            </button>
                                        </form>
                                    </td>
                                    <td class="hide-mobile" style="font-size:0.85rem; color:var(--text-dim);"><?php echo $u['last_seen'] ? date('M j, H:i', strtotime($u['last_seen'])) : 'Never'; ?></td>
                                    <td>
                                        <?php if ($u['status'] == 'blocked'): ?>
                                            <span style="background:rgba(255,69,58,0.1); color:var(--danger); padding:4px 10px; border-radius:100px; font-size:0.7rem; font-weight:700;"><?php echo strtoupper($t['blocked']); ?></span>
                                        <?php else: ?>
                                            <span style="background:rgba(48,209,88,0.1); color:#30d158; padding:4px 10px; border-radius:100px; font-size:0.7rem; font-weight:700;"><?php echo strtoupper($t['active']); ?></span>
                                        <?php endif; ?>
                                    </td>
                                    <td style="padding-right:20px;">
                                        <?php if ($u['id'] != $_SESSION['user_id'] && $u['username'] != 'ChatBot'): ?>
                                            <div style="display:flex; align-items:center; justify-content:flex-end; gap:8px;">
                                                <form method="POST" style="margin:0;">
                                                    <input type="hidden" name="user_id" value="<?php echo $u['id']; ?>">
                                                    <input type="hidden" name="current_status" value="<?php echo $u['status'] ?? 'active'; ?>">
                                                    <button type="submit" name="toggle_block" class="btn btn-sm btn-outline" style="min-width:36px; padding: 0 10px; display:flex; align-items:center; gap:5px;">
                                                        <span><?php echo ($u['status'] ?? 'active') == 'blocked' ? '🔓' : '🚫'; ?></span>
                                                        <span class="hide-mobile"><?php echo ($u['status'] ?? 'active') == 'blocked' ? $t['unblock'] : $t['block']; ?></span>
                                                    </button>
                                                </form>
                                                <form method="POST" style="margin:0;" onsubmit="return confirm('Delete this user?');">
                                                    <input type="hidden" name="user_id" value="<?php echo $u['id']; ?>">
                                                    <button type="submit" name="delete_user" class="btn btn-sm btn-danger" style="width:36px; height:36px; padding:0; border-radius:12px; display:flex; align-items:center; justify-content:center;" title="<?php echo $t['delete']; ?>">
                                                        <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor">
                                                            <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z" />
                                                        </svg>
                                                    </button>
                                                </form>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </section>

            <!-- ROOMS SECTION -->
            <section id="rooms" style="margin-bottom: 60px; padding-top: 20px;">
                <h1><?php echo $t['rooms']; ?></h1>
                <div class="table-wrapper">
                    <table>
                        <thead>
                            <tr>
                                <th>Room Name</th>
                                <th class="hide-mobile">ID</th>
                                <th class="hide-mobile">Created By</th>
                                <th class="hide-mobile">Created At</th>
                                <th style="text-align:right; padding-right:20px; width:60px;"><?php echo $t['actions']; ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($rooms_list as $r): ?>
                                <tr>
                                    <td style="font-weight:600; color:#fff;"><?php echo htmlspecialchars($r['name']); ?></td>
                                    <td class="hide-mobile" style="color:var(--text-dim); font-size:0.8rem; font-family:monospace;">#<?php echo $r['id']; ?></td>
                                    <td class="hide-mobile">
                                        <div style="font-weight:500; font-size:0.9rem; color:var(--text-main);"><?php echo $r['creator_name'] ?: 'System'; ?></div>
                                        <?php if ($r['created_by']): ?><div style="font-size:0.7rem; color:var(--text-dim);">ID: #<?php echo $r['created_by']; ?></div><?php endif; ?>
                                    </td>
                                    <td class="hide-mobile" style="font-size:0.85rem; color:var(--text-dim);"><?php echo date('M j, Y', strtotime($r['created_at'])); ?></td>
                                    <td style="text-align:right; padding-right:20px;">
                                        <?php if ($r['id'] != 1): ?>
                                            <form method="POST" style="display:inline;" onsubmit="return confirm('Delete this room?');">
                                                <input type="hidden" name="room_id" value="<?php echo $r['id']; ?>">
                                                <button type="submit" name="delete_room" class="btn btn-sm btn-danger" style="width:36px; height:36px; padding:0; border-radius:12px;" title="<?php echo $t['delete_room_btn']; ?>">
                                                    <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor">
                                                        <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z" />
                                                    </svg>
                                                </button>
                                            </form>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>


                <!-- SETTINGS SECTION -->
                <section id="settings" style="margin-bottom: 60px; padding-top: 20px; text-align: center;">
                    <h1 style="margin-bottom: 30px;"><?php echo $t['settings']; ?></h1>
                    <div style="max-width: 600px; margin: 0 auto; background: var(--card-bg); padding: 30px; border-radius: 20px; border: 1px solid var(--border); text-align: left;">
                        <form method="POST" enctype="multipart/form-data">
                            <div class="form-group" style="margin-bottom: 25px;">
                                <label><?php echo $t['site_title']; ?></label>
                                <input type="text" name="site_title" value="<?php echo htmlspecialchars($siteTitle); ?>" placeholder="e.g. My Awesome Chat">
                            </div>
                            <div class="form-group" style="margin-bottom: 25px;">
                                <label><?php echo $t['site_logo']; ?></label>
                                <div style="display:flex; align-items:center; gap:15px; margin-bottom:10px;">
                                    <img src="<?php echo htmlspecialchars($siteFavicon); ?>" style="width:50px; height:50px; border-radius:8px; object-fit:contain; background:rgba(255,255,255,0.02); border:1px solid var(--border);">
                                    <div style="flex:1;">
                                        <div class="file-upload-wrapper">
                                            <span class="file-upload-text" id="fileNameDisp"><?php echo $t['choose_file'] ?? 'Choose file...'; ?></span>
                                            <span class="file-upload-btn"><?php echo $t['browse'] ?? 'Browse'; ?></span>
                                            <input type="file" name="logo_file" accept="image/*" onchange="document.getElementById('fileNameDisp').innerText = this.files[0].name">
                                        </div>
                                        <div style="font-size:0.75rem; color:var(--text-dim); margin-top:8px;"><?php echo $t['or_enter_url'] ?? 'Or enter URL below:'; ?></div>
                                    </div>
                                </div>
                                <input type="text" name="favicon" value="<?php echo htmlspecialchars($siteFavicon); ?>" placeholder="assets/logo.png">
                            </div>
                            <div class="form-group" style="margin-bottom: 25px;">
                                <label><?php echo $t['footer_copyright']; ?></label>
                                <input type="text" name="footer_text" value="<?php echo htmlspecialchars($footerText); ?>" placeholder="by YOUR NAME">
                            </div>
                            <div class="form-group" style="margin-bottom: 25px;">
                                <label><?php echo $t['primary_lang']; ?></label>
                                <select name="default_lang">
                                    <option value="en" <?php echo $defaultLang == 'en' ? 'selected' : ''; ?>>English (United States)</option>
                                    <option value="uk" <?php echo $defaultLang == 'uk' ? 'selected' : ''; ?>>Ukrainian (Українська)</option>
                                    <option value="ru" <?php echo $defaultLang == 'ru' ? 'selected' : ''; ?>>Russian (Русский)</option>
                                </select>
                                <small style="color: var(--text-dim); display:block; margin-top:5px;"><?php echo isset($t['default_lang_help']) ? $t['default_lang_help'] : 'This will be the default for new guest users.'; ?></small>
                            </div>

                            <div class="form-group" style="margin-bottom: 25px;">
                                <label><?php echo isset($t['features']) ? $t['features'] : 'Features'; ?></label>
                                <div style="display:flex; flex-direction:column; gap:5px; background:rgba(255,255,255,0.02); padding:15px; border-radius:10px; border:1px solid var(--border);">
                                    <label class="feature-item" style="cursor:pointer;">
                                        <div class="toggle-switch">
                                            <input type="checkbox" name="enable_voice" value="1" <?php echo $enableVoice == '1' ? 'checked' : ''; ?>>
                                            <span class="slider"></span>
                                        </div>
                                        <span style="font-weight:500; font-size:0.95rem;"><?php echo isset($t['enable_voice']) ? $t['enable_voice'] : 'Enable Voice Messages'; ?></span>
                                    </label>
                                    <label class="feature-item" style="cursor:pointer;">
                                        <div class="toggle-switch">
                                            <input type="checkbox" name="enable_video" value="1" <?php echo $enableVideo == '1' ? 'checked' : ''; ?>>
                                            <span class="slider"></span>
                                        </div>
                                        <span style="font-weight:500; font-size:0.95rem;"><?php echo isset($t['enable_video']) ? $t['enable_video'] : 'Enable Video Calls'; ?></span>
                                    </label>
                                </div>
                            </div>



                            <button type="submit" name="update_settings" class="btn btn-primary" style="width:100%; height:52px; margin-top:10px; font-size:1rem;"><?php echo $t['apply_settings']; ?></button>
                        </form>
                    </div>
                </section>
        </div>
    </div>

    <script>
        // Smooth Active State for Sidebar
        const sections = document.querySelectorAll('section');
        const navLinks = document.querySelectorAll('.nav-link');
        const contentArea = document.querySelector('.admin-content');

        function updateActiveLink() {
            let current = '';
            const scrollSource = window.innerWidth <= 992 ? document.documentElement : contentArea;
            const scrollTop = scrollSource.scrollTop;

            sections.forEach(section => {
                const sectionTop = section.offsetTop;
                if (scrollTop >= sectionTop - 150) {
                    current = section.getAttribute('id');
                }
            });

            navLinks.forEach(link => {
                link.classList.remove('active');
                if (link.getAttribute('href').includes(current)) {
                    link.classList.add('active');
                }
            });
        }

        contentArea.addEventListener('scroll', updateActiveLink);
        window.addEventListener('scroll', updateActiveLink);
        window.addEventListener('resize', updateActiveLink);
        window.addEventListener('load', updateActiveLink);
    </script>
</body>

</html>