<?php
declare(strict_types=1);

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/../db.php';

if (empty($_SESSION['user_id'])) {
    header("Location: ../index.html?e=1");
    exit;
}

$pdo = db();
if (!$pdo instanceof PDO) {
    http_response_code(500);
    exit('DB not ready');
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

if (!function_exists('h')) {
    function h($s): string {
        return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
    }
}

$userId = (int)($_SESSION['user_id'] ?? 0);

$st = $pdo->prepare("
    SELECT r.id, r.room_name, r.room_type, r.branch_id
    FROM chat_rooms r
    INNER JOIN chat_room_members rm ON rm.room_id = r.id
    WHERE rm.employee_id = ?
    ORDER BY r.id ASC
");
$st->execute([$userId]);
$rooms = $st->fetchAll();
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>غرفة الدردشة</title>
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;800&display=swap" rel="stylesheet">
<style>
:root{
    --hlg-dark:#00424f;
    --hlg-teal:#006a7a;
    --hlg-gold:#d4af37;
    --bg:#072f36;
    --panel:#0b3a43;
    --panel-2:#0e4650;
    --text:#ecf7f8;
    --muted:#b9d0d4;
    --line:rgba(255,255,255,.08);
}
*{box-sizing:border-box}
body{
    margin:0;
    font-family:"Tajawal",Arial,sans-serif;
    background:linear-gradient(135deg,#062b31,#073640 45%,#05252b);
    color:var(--text);
}
.chat-page{
    display:grid;
    grid-template-columns:320px 1fr;
    height:100vh;
}
.sidebar{
    border-left:1px solid var(--line);
    background:rgba(255,255,255,.03);
    padding:16px;
    overflow:auto;
}
.brand{
    color:var(--hlg-gold);
    font-size:22px;
    font-weight:800;
    margin-bottom:18px;
}
.side-title{
    font-size:14px;
    color:var(--muted);
    margin:12px 0 10px;
}
.room-btn{
    width:100%;
    border:1px solid var(--line);
    background:linear-gradient(90deg,rgba(255,255,255,.03),rgba(255,255,255,.06));
    color:#fff;
    border-radius:14px;
    padding:12px 14px;
    text-align:right;
    font-family:"Tajawal",Arial,sans-serif;
    font-size:15px;
    cursor:pointer;
    margin-bottom:10px;
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:10px;
}
.room-btn.active{
    outline:2px solid rgba(212,175,55,.35);
    background:linear-gradient(90deg,rgba(212,175,55,.08),rgba(255,255,255,.06));
}
.badge{
    min-width:24px;
    height:24px;
    padding:0 8px;
    border-radius:999px;
    background:var(--hlg-gold);
    color:#111;
    font-size:12px;
    font-weight:800;
    display:none;
    align-items:center;
    justify-content:center;
}
.online-list{
    margin-top:8px;
}
.online-user{
    display:flex;
    align-items:center;
    gap:8px;
    padding:8px 10px;
    border-radius:10px;
    background:rgba(255,255,255,.03);
    margin-bottom:8px;
    color:#fff;
}
.online-dot{
    width:10px;
    height:10px;
    border-radius:50%;
    background:#22c55e;
    flex:0 0 10px;
}
.main{
    display:flex;
    flex-direction:column;
    min-width:0;
}
.topbar{
    padding:18px 20px;
    border-bottom:1px solid var(--line);
    background:rgba(0,0,0,.08);
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:16px;
}
.room-title{
    font-size:24px;
    font-weight:800;
    color:var(--hlg-gold);
}
.live-status{
    font-size:14px;
    color:var(--muted);
}
.messages{
    flex:1;
    overflow:auto;
    padding:20px;
}
.msg{
    max-width:75%;
    margin-bottom:14px;
    padding:12px 14px;
    border-radius:16px;
    background:rgba(255,255,255,.06);
    border:1px solid var(--line);
    box-shadow:0 10px 24px rgba(0,0,0,.10);
}
.msg.me{
    margin-right:auto;
    background:rgba(212,175,55,.16);
}
.msg-name{
    font-size:13px;
    color:#ffd86b;
    margin-bottom:5px;
    font-weight:700;
}
.msg-text{
    font-size:15px;
    line-height:1.8;
    color:#fff;
    word-break:break-word;
}
.msg-time{
    margin-top:6px;
    font-size:12px;
    color:#c8dadd;
}
.form-wrap{
    border-top:1px solid var(--line);
    padding:14px;
    background:rgba(0,0,0,.08);
}
.chat-form{
    display:flex;
    gap:10px;
}
.chat-input{
    flex:1;
    height:50px;
    border-radius:14px;
    border:1px solid var(--line);
    background:rgba(255,255,255,.06);
    color:#fff;
    padding:0 14px;
    font-family:"Tajawal",Arial,sans-serif;
    font-size:15px;
}
.chat-input::placeholder{
    color:#b9d0d4;
}
.send-btn{
    border:0;
    border-radius:14px;
    min-width:110px;
    background:var(--hlg-gold);
    color:#111;
    font-family:"Tajawal",Arial,sans-serif;
    font-weight:800;
    cursor:pointer;
    font-size:15px;
}
.empty{
    color:#c4d6da;
    padding:30px 8px;
}
@media (max-width: 900px){
    .chat-page{
        grid-template-columns:1fr;
    }
    .sidebar{
        display:none;
    }
    .msg{
        max-width:88%;
    }
}
</style>
</head>
<body>
<div class="chat-page">
    <aside class="sidebar">
        <div class="brand">HLG Chat</div>

        <div class="side-title">الغرف</div>
        <div id="roomsList">
            <?php foreach ($rooms as $r): ?>
                <button
                    class="room-btn"
                    id="room-btn-<?= (int)$r['id'] ?>"
                    type="button"
                    onclick="openRoom(<?= (int)$r['id'] ?>,'<?= h($r['room_name']) ?>')"
                >
                    <span><?= h($r['room_name']) ?></span>
                    <span class="badge" id="badge-<?= (int)$r['id'] ?>">0</span>
                </button>
            <?php endforeach; ?>
        </div>

        <div class="side-title">الموظفون المتصلون الآن</div>
        <div id="onlineList" class="online-list"></div>
    </aside>

    <section class="main">
        <div class="topbar">

<div class="room-title" id="roomTitle">اختر غرفة</div>

<div style="display:flex; gap:10px; align-items:center">

<button id="leaveRoomBtn"
onclick="leaveRoom()"
style="
background:#b91c1c;
color:#fff;
border:0;
border-radius:10px;
padding:8px 14px;
font-family:Tajawal;
cursor:pointer;
display:none;
">
خروج من الغرفة
</button>

<div class="live-status" id="liveStatus">جاهز</div>

</div>

</div>
            <div class="room-title" id="roomTitle">اختر غرفة</div>
            <div class="live-status" id="liveStatus">جاهز</div>
        </div>

        <div class="messages" id="messages">
            <div class="empty">اختر غرفة من القائمة لبدء المحادثة</div>
        </div>

        <div class="form-wrap">
            <form class="chat-form" onsubmit="sendMessage(event)">
                <input class="chat-input" id="messageInput" type="text" placeholder="اكتب رسالتك هنا...">
                <button class="send-btn" type="submit">إرسال</button>
            </form>
        </div>
    </section>
</div>

<script>
let currentRoomId = 0;
let currentRoomTitle = '';
let lastMessageId = 0;
const myUserId = <?= (int)$userId ?>;

function escapeHtml(text){
    const div = document.createElement('div');
    div.textContent = text ?? '';
    return div.innerHTML;
}

function setActiveRoom(roomId){
    document.querySelectorAll('.room-btn').forEach(btn => btn.classList.remove('active'));
    const btn = document.getElementById('room-btn-' + roomId);
    if (btn) btn.classList.add('active');
}

async function openRoom(roomId, title){
    currentRoomId = parseInt(roomId, 10) || 0;
    currentRoomTitle = title || '';
    lastMessageId = 0;
document.getElementById('leaveRoomBtn').style.display='block';
    document.getElementById('roomTitle').textContent = currentRoomTitle;
    document.getElementById('messages').innerHTML = '<div class="empty">جاري تحميل الرسائل...</div>';

    setActiveRoom(currentRoomId);

    await fetchMessages(true);
    await markRoomRead();
}

async function fetchMessages(reset = false){
    if (!currentRoomId) return;

    try{
        const res = await fetch(`fetch_messages.php?room_id=${currentRoomId}&last_id=${reset ? 0 : lastMessageId}`);
        const data = await res.json();

        if (!data.ok) {
            document.getElementById('messages').innerHTML = `<div class="empty">${escapeHtml(data.message || 'تعذر جلب الرسائل')}</div>`;
            return;
        }

        const box = document.getElementById('messages');

        if (reset) {
            box.innerHTML = '';
        }

        if (reset && (!data.messages || data.messages.length === 0)) {
            box.innerHTML = '<div class="empty">لا توجد رسائل في هذه الغرفة بعد</div>';
            return;
        }

        data.messages.forEach(row => {
            const id = parseInt(row.id, 10) || 0;
            if (id > lastMessageId) lastMessageId = id;

            const mine = (parseInt(row.sender_id, 10) === myUserId);
            const item = document.createElement('div');
            item.className = 'msg' + (mine ? ' me' : '');
            item.innerHTML = `
                <div class="msg-name">${escapeHtml(row.sender_name)}</div>
                <div class="msg-text">${escapeHtml(row.message)}</div>
                <div class="msg-time">${escapeHtml(row.created_at)}</div>
            `;
            box.appendChild(item);
        });

        box.scrollTop = box.scrollHeight;
    }catch(e){
        document.getElementById('messages').innerHTML = '<div class="empty">حدث خطأ أثناء تحميل الرسائل</div>';
        console.error(e);
    }
}

async function sendMessage(e){
    e.preventDefault();

    const input = document.getElementById('messageInput');
    const message = input.value.trim();

    if (!currentRoomId) {
        alert('اختر غرفة أولاً');
        return;
    }

    if (!message) {
        input.focus();
        return;
    }

    try{
        const form = new FormData();
        form.append('room_id', String(currentRoomId));
        form.append('message', message);

        const res = await fetch('send_message.php', {
            method: 'POST',
            body: form
        });

        const data = await res.json();
        console.log('send_message response:', data);

        if (!data.ok) {
            alert(data.message || 'تعذر إرسال الرسالة');
            return;
        }

        input.value = '';
        await fetchMessages(false);
        await markRoomRead();
    }catch(e){
        console.error(e);
        alert('حدث خطأ أثناء الإرسال');
    }
}

async function fetchOnlineUsers(){
    try{
        const res = await fetch('fetch_online_users.php');
        const data = await res.json();
        if (!data.ok) return;

        const box = document.getElementById('onlineList');
        box.innerHTML = '';

        if (!data.users || data.users.length === 0) {
            box.innerHTML = '<div class="empty">لا يوجد موظفون متصلون الآن</div>';
            return;
        }

        data.users.forEach(user => {
            const item = document.createElement('div');
            item.className = 'online-user';
            item.innerHTML = `
                <span class="online-dot"></span>
                <span>${escapeHtml(user.full_name || ('موظف #' + user.id))}</span>
            `;
            box.appendChild(item);
        });
    }catch(e){
        console.error(e);
    }
}

async function fetchNotifications(){
    try{
        const res = await fetch('fetch_notifications.php');
        const data = await res.json();
        if (!data.ok) return;

        document.querySelectorAll('.badge').forEach(b => {
            b.style.display = 'none';
            b.textContent = '0';
        });

        let total = 0;

        (data.notifications || []).forEach(n => {
            const count = parseInt(n.unread_count, 10) || 0;
            total += count;

            const badge = document.getElementById('badge-' + n.room_id);
            if (badge && count > 0) {
                badge.style.display = 'inline-flex';
                badge.textContent = String(count);
            }
        });

        document.getElementById('liveStatus').textContent = total > 0
            ? `لديك ${total} رسالة غير مقروءة`
            : 'جميع الرسائل مقروءة';
    }catch(e){
        console.error(e);
    }
}

async function markRoomRead(){
    if (!currentRoomId) return;

    try{
        const form = new FormData();
        form.append('room_id', String(currentRoomId));

        await fetch('mark_room_read.php', {
            method:'POST',
            body:form
        });

        fetchNotifications();
    }catch(e){
        console.error(e);
    }
}

setInterval(() => {
    fetchOnlineUsers();
    fetchNotifications();
    fetchMessages(false);
}, 5000);

fetchOnlineUsers();
fetchNotifications();

<?php if (!empty($rooms)): ?>
openRoom(<?= (int)$rooms[0]['id'] ?>, <?= json_encode((string)$rooms[0]['room_name'], JSON_UNESCAPED_UNICODE) ?>);
<?php endif; ?>
async function leaveRoom(){

if(!currentRoomId) return;

if(!confirm("هل تريد الخروج من الغرفة؟")) return;

try{

const form = new FormData();
form.append('room_id',currentRoomId);

const res = await fetch('leave_room.php',{
method:'POST',
body:form
});

const data = await res.json();

if(data.ok){

currentRoomId=0;

document.getElementById('messages').innerHTML=
'<div class="empty">لقد خرجت من الغرفة</div>';

document.getElementById('roomTitle').textContent="اختر غرفة";

document.getElementById('leaveRoomBtn').style.display='none';

}

}catch(e){
console.error(e);
}

}
</script>
</body>
</html>