<?php
/**
* CMS: LaiCMS (v1.0 Edition 2026)
* File: messages/index.php
* Оптимизация: PHP 7.4+, Ultra-UI Engine, SQL Performance.
*/
declare(strict_types=1);
require_once '../system/db.php';
require_once '../system/functions.php';
// 1. Защита доступа
$user_id = (int)($_SESSION['user_id'] ?? 0);
if (!$user_id) {
header("Location: /users/login.php");
exit;
}
$page_title = "Чаты — Ultra Messenger";
include '../system/header.php';
/**
* ИНСТРУМЕНТ 1: Высокопроизводительный SQL-запрос.
* Вместо вложенных SELECT в цикле, мы используем JOIN и агрегацию для получения
* последних сообщений и счетчика непрочитанных за один такт.
*/
$query = "
SELECT
u.id as contact_id,
u.username, u.avatar, u.last_seen, u.role,
m.message, m.created_at, m.is_read, m.sender_id as last_sender,
unread.total as unread_count
FROM messages m
INNER JOIN (
/* Получаем ID последних сообщений для каждого диалога */
SELECT MAX(id) as max_id
FROM messages
WHERE sender_id = ? OR receiver_id = ?
GROUP BY IF(sender_id = ?, receiver_id, sender_id)
) last_msg ON m.id = last_msg.max_id
JOIN users u ON u.id = IF(m.sender_id = ?, m.receiver_id, m.sender_id)
LEFT JOIN (
/* Подсчет непрочитанных */
SELECT sender_id, COUNT(*) as total
FROM messages
WHERE receiver_id = ? AND is_read = 0
GROUP BY sender_id
) unread ON unread.sender_id = u.id
ORDER BY m.created_at DESC
";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("iiiii", $user_id, $user_id, $user_id, $user_id, $user_id);
$stmt->execute();
$dialogs = $stmt->get_result();
?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>
<style>
:root {
--u-glass: rgba(255, 255, 255, 0.85);
--u-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.1);
}
[data-theme="dark"] :root {
--u-glass: rgba(13, 17, 23, 0.9);
}
/* ИНСТРУМЕНТ 2: Glassmorphism Layout */
.ultra-messenger {
display: grid;
grid-template-columns: 350px 1fr;
height: 80vh;
background: var(--u-glass);
backdrop-filter: blur(16px);
border: 1px solid var(--ultra-border);
border-radius: 28px;
box-shadow: var(--u-shadow);
overflow: hidden;
}
/* Сайдбар со списком */
.ms-sidebar {
border-right: 1px solid var(--pico-muted-border-color);
display: flex;
flex-direction: column;
}
.dialog-list {
flex: 1;
overflow-y: auto;
padding: 12px;
}
/* Стилизация аватара с градиентом */
.ava-box {
width: 52px; height: 52px;
border-radius: 18px;
display: flex; align-items: center; justify-content: center;
font-weight: bold; color: white;
transition: transform 0.3s ease;
}
.dialog-item {
display: flex; align-items: center; gap: 14px;
padding: 12px;
border-radius: 20px;
text-decoration: none;
transition: 0.2s;
margin-bottom: 4px;
}
.dialog-item:hover { background: rgba(var(--pico-primary-rgb), 0.05); }
.dialog-item.unread { background: rgba(var(--pico-primary-rgb), 0.08); }
/* Метки ролей */
.adm-badge {
background: var(--pico-primary);
font-size: 10px; padding: 2px 6px; border-radius: 6px;
color: white; margin-left: 5px;
}
/* Статус онлайн */
.status-dot {
position: absolute; bottom: -2px; right: -2px;
width: 14px; height: 14px;
border: 3px solid var(--pico-background-color);
border-radius: 50%;
background: #2ecc71;
}
.status-dot.offline { background: #95a5a6; }
@media (max-width: 800px) {
.ultra-messenger { grid-template-columns: 1fr; }
.main-chat-empty { display: none; }
}
</style>
<div class="container">
<header style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
<div>
<h2 style="margin:0;">Чаты</h2>
<small class="secondary">LaiCore 2026: Шифрование включено</small>
</div>
<a href="compose.php" class="button primary" style="border-radius: 50px;">
<i class="fa-solid fa-plus"></i> Начать чат
</a>
</header>
<div class="ultra-messenger animate__animated animate__fadeIn">
<aside class="ms-sidebar">
<div style="padding: 1rem; border-bottom: 1px solid var(--pico-muted-border-color);">
<input type="search" id="msSearch" placeholder="Поиск по имени..." class="ultra-search" style="margin:0; border-radius: 15px;">
</div>
<div class="dialog-list">
<?php if ($dialogs->num_rows > 0): ?>
<?php while($d = $dialogs->fetch_assoc()):
$is_online = (strtotime($d['last_seen'] ?? '') > time() - 300);
$unread = (int)$d['unread_count'];
$is_me = ($d['last_sender'] == $user_id);
?>
<a href="chat.php?id=<?= $d['contact_id'] ?>" class="dialog-item <?= $unread ? 'unread' : '' ?>" data-name="<?= strtolower($d['username']) ?>">
<div style="position: relative;">
<?php if($d['avatar']): ?>
<img src="<?= htmlspecialchars($d['avatar']) ?>" class="ava-box" loading="lazy">
<?php else: ?>
<div class="ava-box" style="background: linear-gradient(135deg, #6366f1, #a855f7);">
<?= mb_substr($d['username'], 0, 1) ?>
</div>
<?php endif; ?>
<div class="status-dot <?= $is_online ? '' : 'offline' ?>"></div>
</div>
<div style="flex: 1; min-width: 0;">
<div style="display: flex; justify-content: space-between;">
<strong class="user-name">
<?= htmlspecialchars($d['username']) ?>
<?php if($d['role'] === 'admin'): ?><span class="adm-badge">ADM</span><?php endif; ?>
</strong>
<small class="secondary"><?= date('H:i', strtotime($d['created_at'])) ?></small>
</div>
<div style="display: flex; justify-content: space-between; align-items: center;">
<span class="secondary" style="font-size: 0.85rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
<?= $is_me ? '<i class="fa-solid fa-reply" style="font-size: 0.7rem;"></i> ' : '' ?>
<?= htmlspecialchars(mb_strimwidth($d['message'], 0, 40, "...")) ?>
</span>
<?php if($unread > 0): ?>
<span class="badge primary" style="font-size: 0.6rem; border-radius: 10px; padding: 2px 6px;"><?= $unread ?></span>
<?php endif; ?>
</div>
</div>
</a>
<?php endwhile; ?>
<?php else: ?>
<p style="text-align: center; margin-top: 2rem;" class="secondary">Нет активных чатов</p>
<?php endif; ?>
</div>
</aside>
<main class="main-chat-empty" style="display: flex; flex-direction: column; align-items: center; justify-content: center; background: rgba(0,0,0,0.02);">
<div style="text-align: center; opacity: 0.4;">
<i class="fa-solid fa-comments fa-4x"></i>
<h4>Выберите чат</h4>
<p>Выберите собеседника, чтобы начать общение</p>
</div>
</main>
</div>
</div>
<script>
/**
* ИНСТРУМЕНТ 3: Smart Search Engine.
* Мгновенная фильтрация без задержек.
*/
document.getElementById('msSearch').addEventListener('input', function(e) {
const val = e.target.value.toLowerCase().trim();
document.querySelectorAll('.dialog-item').forEach(item => {
const name = item.dataset.name;
item.style.display = name.includes(val) ? 'flex' : 'none';
});
});
</script>
<?php include '../system/footer.php'; ?>