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

// Обработка выхода
if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: login.php");
    exit;
}

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

// Получение данных пользователя
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$user = $stmt->fetch();

if (!$user || $user['status'] === 'blocked') {
    session_destroy();
    header("Location: login.php?error=blocked");
    exit;
}

// Обновление сессии
$_SESSION['role'] = $user['role'];
$_SESSION['username'] = $user['username'];
$_SESSION['avatar'] = $user['avatar'];

// Получение настроек
$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';
$footerText = $settings['footer_text'] ?? 'by ANUS_TANGA';
$enableVideo = $settings['enable_video'] ?? '0';


$hasLicense = true; // Видеозвонки бесплатны


// Обработка обновления профиля
$profileMessage = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    $newAvatar = $user['avatar'];
    if (isset($_FILES['new_avatar']) && $_FILES['new_avatar']['error'] === 0) {
        $ext = pathinfo($_FILES['new_avatar']['name'], PATHINFO_EXTENSION);
        $newName = 'avatar_' . $_SESSION['user_id'] . '_' . time() . '.' . $ext;
        if (move_uploaded_file($_FILES['new_avatar']['tmp_name'], 'assets/avatars/' . $newName)) {
            $newAvatar = 'assets/avatars/' . $newName;
        }
    }

    $pdo->prepare("UPDATE users SET avatar = ? WHERE id = ?")->execute([$newAvatar, $_SESSION['user_id']]);
    $_SESSION['avatar'] = $newAvatar;
    $profileMessage = $t['update_success'] ?? 'Profile updated!';
}
?>
<!DOCTYPE html>
<html lang="<?php echo $_SESSION['lang']; ?>">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title><?php echo htmlspecialchars($siteTitle); ?></title>
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($siteFavicon); ?>">
    <link rel="stylesheet" href="assets/style.css">
    <script>
        const USER = {
            id: <?php echo $_SESSION['user_id']; ?>,
            username: '<?php echo htmlspecialchars($_SESSION['username']); ?>',
            avatar: '<?php echo htmlspecialchars($_SESSION['avatar'] ?? 'assets/default_avatar.png'); ?>',
            role: '<?php echo $_SESSION['role']; ?>',
            hasLicense: <?php echo $hasLicense ? 'true' : 'false'; ?>,
            isVideoEnabled: <?php echo $enableVideo === '1' ? 'true' : 'false'; ?>
        };
        const LANG = <?php echo json_encode($t); ?>;
    </script>
</head>

<body>
    <div class="app-layout">
        <aside class="sidebar">
            <div class="sidebar-header">
                <div style="display:flex; align-items:center; gap:12px;">
                    <img src="<?php echo htmlspecialchars($siteFavicon); ?>" alt="Logo" style="width:36px; height:36px; border-radius:50%; border:1px solid rgba(255,255,255,0.1);">
                    <h2 style="margin:0; font-size:1.4rem; font-weight:700; color:#fff;"><?php echo htmlspecialchars($siteTitle); ?></h2>
                </div>
            </div>
            <div style="padding: 20px 20px 10px 20px;">
                <h3 style="font-size:0.8rem; text-transform:uppercase; letter-spacing:1.5px; opacity:0.5; margin:0; font-weight:700; color:rgba(255,255,255,0.7);"><?php echo $t['rooms']; ?></h3>
            </div>
            <div class="create-room"><input type="text" id="newRoomName" placeholder="<?php echo $t['new_room']; ?>"><button id="createRoomBtn" onclick="if(window.handleCreateRoom) window.handleCreateRoom();">+</button></div>
            <div id="roomsList" class="rooms-list"></div>
            <div class="sidebar-footer" style="height:96px; padding:0 20px; display:flex; flex-direction:column; justify-content:center; font-size:0.75rem; color:rgba(255,255,255,0.3); text-align:center; border-top:1px solid rgba(255,255,255,0.1); flex-shrink:0;">
                <div style="width:100%; text-align:center; margin-bottom:5px; line-height:1.4;">&copy; <?php echo date('Y'); ?> <strong><?php echo htmlspecialchars($siteTitle); ?></strong><span style="opacity:0.5; margin:0 4px;">•</span><span style="opacity:0.7; font-size:0.75rem;"><?php echo htmlspecialchars(str_replace('by ', '', $footerText)); ?></span></div>
                <?php if ((isset($_SESSION['role']) && $_SESSION['role'] === 'admin') || (isset($_SESSION['user_id']) && $_SESSION['user_id'] == 1)): ?><a href="admin.php" style="color:#0a84ff; text-decoration:none; font-weight:bold; display:block; margin-top:8px;">★ Admin Panel</a><?php endif; ?>
            </div>
        </aside>
        <div class="chat-container">
            <div class="chat-header">
                <button id="menuBtn" class="icon-btn mobile-menu-btn"><svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor">
                        <path d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z" />
                    </svg></button>
                <div style="display:flex; align-items:center; gap:10px;">
                    <div class="avatar-container" onclick="document.getElementById('profile-modal').style.display='flex'" style="cursor:pointer;"><img src="<?php echo htmlspecialchars($_SESSION['avatar'] ?? 'assets/default_avatar.png'); ?>" class="msg-avatar">
                        <div class="status-dot online"></div>
                    </div>
                    <div>
                        <h3 id="chatRoomTitle" style="margin-bottom:2px;">ChatApp</h3>
                        <div class="header-user-info" style="font-size:0.75rem; opacity:0.7;"><span class="welcome-text"><?php echo $t['welcome']; ?>, <?php echo htmlspecialchars($_SESSION['username']); ?></span></div>
                    </div>
                </div>
                <div class="header-controls"><button onclick="document.getElementById('profile-modal').style.display='flex'" style="background:rgba(157,78,221,0.1); border:1px solid rgba(157,78,221,0.2); color:var(--primary); padding:6px 12px; border-radius:8px; cursor:pointer; font-size:0.75rem; font-weight:700;"><?php echo $t['profile']; ?></button><a href="?logout=1" class="logout-btn desktop-only" style="margin-left:10px;"><?php echo $t['logout']; ?></a></div>
            </div>
            <div class="messages-area" id="messagesArea"></div>
            <div class="input-area">
                <input type="file" id="imageInput" accept="image/*" style="display:none">
                <button id="photoBtn" class="icon-btn"><svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor">
                        <path d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z" />
                    </svg></button>
                <input type="text" id="messageInput" placeholder="<?php echo $t['type_msg'] ?? 'Type message...'; ?>">
                <button id="sendBtn" class="icon-btn"><svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
                        <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z" />
                    </svg></button>
                <button id="recordBtn" class="icon-btn"><svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
                        <path d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.66 9 5v6c0 1.66 1.34 3 3 3z" />
                        <path d="M17 11c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z" />
                    </svg></button>
            </div>
        </div>
    </div>

    <!-- Модальное окно профиля (Свой профиль) -->
    <div id="profile-modal" class="modal-overlay" style="display:none;">
        <div class="profile-card">
            <button onclick="document.getElementById('profile-modal').style.display='none'" class="close-modal">&times;</button>
            <h2 style="margin-bottom:25px;"><?php echo $t['profile']; ?></h2>
            <form method="POST" enctype="multipart/form-data">
                <div style="margin-bottom:25px; position:relative; display:inline-block;">
                    <img id="profile-preview" src="<?php echo htmlspecialchars($_SESSION['avatar'] ?? 'assets/default_avatar.png'); ?>" style="width:120px; height:120px; border-radius:50%; object-fit:cover; border:3px solid var(--primary); box-shadow:0 0 20px rgba(157,78,221,0.2);">
                    <input type="file" name="new_avatar" id="avatar-input" style="display:none;" onchange="previewProfileAvatar(this)">
                    <label for="avatar-input" style="position:absolute; bottom:0; right:0; background:var(--primary); color:#fff; width:36px; height:36px; border-radius:50%; display:flex; align-items:center; justify-content:center; cursor:pointer; border:3px solid #1e1e1e; font-size:1.2rem;" title="<?php echo $t['change_avatar']; ?>">📷</label>
                </div>
                <div style="font-weight:800; font-size:1.5rem; margin-bottom:5px; color:#fff;"><?php echo htmlspecialchars($_SESSION['username']); ?></div>
                <div style="margin-bottom:25px; opacity:0.6; font-size:0.85rem; text-transform:uppercase; letter-spacing:1px; font-weight:700;">
                    <?php echo $_SESSION['role'] === 'admin' ? '👑 Admin' : (isset($t['standard_user']) ? $t['standard_user'] : 'Standard User'); ?>
                </div>
                <?php if ($profileMessage): ?><div style="color:#4cd137; margin-bottom:15px; background:rgba(76,209,55,0.1); padding:10px; border-radius:10px; font-size:0.9rem;"><?php echo $profileMessage; ?></div><?php endif; ?>
                <button type="submit" name="update_profile" class="btn"><?php echo $t['save_changes']; ?></button>
            </form>
        </div>
    </div>

    <!-- Модальное окно профиля другого пользователя (Заполняется через JS) -->
    <div id="view-user-modal" class="modal-overlay" style="display:none;"></div>

    <!-- Модальное окно участников комнаты (Заполняется через JS) -->
    <div id="room-members-modal" class="modal-overlay" style="display:none;"></div>

    <script src="assets/script.js?v=<?php echo time(); ?>"></script>
    <script src="assets/user-profile-modal.js"></script>
    <script src="protected/video-call-core.js"></script>
    <script>
        function previewProfileAvatar(i) {
            if (i.files && i.files[0]) {
                var r = new FileReader();
                r.onload = function(e) {
                    document.getElementById('profile-preview').src = e.target.result;
                };
                r.readAsDataURL(i.files[0]);
            }
        }
        <?php if ($profileMessage): ?>document.getElementById('profile-modal').style.display = 'flex';
        <?php endif; ?>
    </script>
</body>

</html>