<?php
/**
 * Floating Chat Widget
 * File: layouts/chat_widget.php
 *
 * Include this at the bottom of layouts/main.php (before </body>):
 *   <?php if (isset($_SESSION['user_id'])) include 'layouts/chat_widget.php'; ?>
 *
 * Features:
 *  - Floating chat button in bottom-right corner with unread badge
 *  - Mini chat panel with conversation list + quick message view
 *  - "Open full chat" button linking to messaging.php
 *  - Polls for unread count every 10 seconds
 *  - Polls for new messages every 5 seconds when a conv is open
 */
if (!isset($_SESSION['user_id'])) return;
?>

<style>
.float-chat-btn {
    position: fixed; bottom: 24px; right: 24px; z-index: 1050;
    width: 52px; height: 52px; border-radius: 50%;
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: #fff; border: none; font-size: 1.5rem;
    box-shadow: 0 4px 18px rgba(118,75,162,.45);
    cursor: pointer; display: flex; align-items: center; justify-content: center;
    transition: transform .2s;
}
.float-chat-btn:hover { transform: scale(1.08); }
.float-chat-btn .fc-badge {
    position: absolute; top: -4px; right: -4px;
    background: #e63946; color: #fff; border-radius: 50%;
    width: 18px; height: 18px; font-size: .65rem;
    display: none; align-items: center; justify-content: center;
    font-weight: 700;
}

.float-chat-panel {
    position: fixed; bottom: 88px; right: 24px; z-index: 1049;
    width: 320px; background: #fff;
    border-radius: 14px;
    box-shadow: 0 8px 32px rgba(118,75,162,.22);
    display: none; flex-direction: column;
    overflow: hidden;
    max-height: 480px;
}

.fc-header {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: #fff; padding: 12px 16px;
    display: flex; align-items: center; justify-content: space-between;
}
.fc-header span { font-weight: 600; font-size: .9rem; }
.fc-header a {
    color: #fff; text-decoration: none; font-size: .75rem;
    opacity: .85; display: flex; align-items: center; gap: 4px;
}
.fc-header a:hover { opacity: 1; }

.fc-body { display: flex; flex-direction: column; flex: 1; min-height: 0; }

/* Conversation list view */
.fc-conv-list { overflow-y: auto; flex: 1; }
.fc-conv-item {
    display: flex; align-items: center; gap: 10px;
    padding: 9px 14px; cursor: pointer;
    border-bottom: 1px solid #f5f0ff;
    transition: background .15s;
}
.fc-conv-item:hover { background: #f7f3ff; }
.fc-avatar {
    width: 36px; height: 36px; border-radius: 50%;
    background: linear-gradient(135deg, #a78bfa, #764ba2);
    color: #fff; display: flex; align-items: center; justify-content: center;
    font-weight: 700; font-size: .85rem; flex-shrink: 0;
}
.fc-cname  { font-weight: 600; font-size: .82rem; }
.fc-cprev  { font-size: .72rem; color: #999; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.fc-cunread {
    background: #764ba2; color: #fff; border-radius: 50%;
    width: 16px; height: 16px; font-size: .6rem;
    display: flex; align-items: center; justify-content: center;
    flex-shrink: 0; margin-left: auto;
}

/* Message view */
.fc-msg-view { display: none; flex-direction: column; flex: 1; min-height: 0; }
.fc-msg-topbar {
    padding: 8px 12px; border-bottom: 1px solid #ede8fb;
    display: flex; align-items: center; gap: 8px; font-size: .83rem;
}
.fc-msg-topbar button {
    background: none; border: none; color: #764ba2; font-size: 1rem; cursor: pointer; padding: 0;
}
.fc-messages {
    flex: 1; overflow-y: auto; padding: 10px 12px;
    display: flex; flex-direction: column; gap: 6px;
}
.fc-bubble {
    max-width: 80%; padding: 6px 10px; border-radius: 12px;
    font-size: .8rem; line-height: 1.4; align-self: flex-start;
    background: #f0ebff;
}
.fc-bubble.mine {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: #fff; align-self: flex-end; border-bottom-right-radius: 4px;
}
.fc-bubble.theirs { border-bottom-left-radius: 4px; }
.fc-bubble .fc-btime { font-size: .65rem; opacity: .6; display: block; margin-top: 2px; }
.fc-input-row {
    display: flex; gap: 6px; padding: 8px 10px;
    border-top: 1px solid #ede8fb; align-items: center;
}
.fc-input-row input {
    flex: 1; border: 1px solid #ddd; border-radius: 16px;
    font-size: .8rem; padding: 5px 12px; outline: none;
}
.fc-input-row button {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: #fff; border: none; border-radius: 50%;
    width: 30px; height: 30px; display: flex;
    align-items: center; justify-content: center;
    cursor: pointer; font-size: .85rem;
    flex-shrink: 0;
}
</style>

<!-- Floating Button -->
<button class="float-chat-btn" id="fcToggleBtn" title="Internal Chat">
    <i class="ri-chat-3-line"></i>
    <span class="fc-badge" id="fcBadge">0</span>
</button>

<!-- Mini Chat Panel -->
<div class="float-chat-panel" id="fcPanel">
    <div class="fc-header">
        <span><i class="ri-chat-3-line me-1"></i>Messages</span>
        <a href="messaging.php"><i class="ri-external-link-line"></i> Full Chat</a>
    </div>
    <div class="fc-body" id="fcBody">
        <!-- Conversation list -->
        <div id="fcConvView" class="fc-conv-list"></div>

        <!-- Message view -->
        <div id="fcMsgView" class="fc-msg-view">
            <div class="fc-msg-topbar">
                <button id="fcBackBtn" title="Back"><i class="ri-arrow-left-line"></i></button>
                <strong id="fcMsgName" style="flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"></strong>
                <a href="messaging.php" class="btn btn-sm py-0" style="background:linear-gradient(135deg,#667eea,#764ba2);color:#fff;font-size:.7rem;">
                    Expand
                </a>
            </div>
            <div class="fc-messages" id="fcMessages"></div>
            <div class="fc-input-row">
                <input type="text" id="fcInput" placeholder="Message...">
                <button id="fcSendBtn"><i class="ri-send-plane-2-fill"></i></button>
            </div>
        </div>
    </div>
</div>

<script>
(function () {
    let fcOpen       = false;
    let fcConvId     = null;
    let fcLastMsgId  = 0;
    let fcPollMsg    = null;
    const ME_ID      = <?= (int)$_SESSION['user_id'] ?>;

    const fcToggle   = document.getElementById('fcToggleBtn');
    const fcPanel    = document.getElementById('fcPanel');
    const fcBadge    = document.getElementById('fcBadge');
    const fcConvView = document.getElementById('fcConvView');
    const fcMsgView  = document.getElementById('fcMsgView');
    const fcMessages = document.getElementById('fcMessages');
    const fcInput    = document.getElementById('fcInput');
    const fcMsgName  = document.getElementById('fcMsgName');

    function fcAjax(action, extra = {}) {
        const fd = new FormData();
        fd.append('action', action);
        Object.entries(extra).forEach(([k,v]) => fd.append(k,v));
        return fetch('ajax/chat.php', {method:'POST', body: fd}).then(r => r.json());
    }

    // Toggle panel
    fcToggle.addEventListener('click', () => {
        fcOpen = !fcOpen;
        fcPanel.style.display = fcOpen ? 'flex' : 'none';
        if (fcOpen) loadFcConversations();
    });

    // Load conversation list in widget
    function loadFcConversations() {
        fcConvView.innerHTML = '<div class="text-center text-muted py-3 small">Loading...</div>';
        fcAjax('get_conversations').then(data => {
            fcConvView.innerHTML = '';
            if (!data.conversations?.length) {
                fcConvView.innerHTML = '<div class="text-center text-muted py-3 small">No conversations yet.<br><a href="messaging.php">Start one →</a></div>';
                return;
            }
            data.conversations.forEach(c => {
                const name = c.conversation_type === 'group' ? (c.title || 'Group') : (c.other_name || '?');
                const prev = (c.last_message || 'No messages').substring(0, 35);
                const unrd = parseInt(c.unread_count) || 0;
                const div  = document.createElement('div');
                div.className = 'fc-conv-item';
                div.innerHTML = `
                    <div class="fc-avatar">${name.charAt(0).toUpperCase()}</div>
                    <div style="flex:1;min-width:0;">
                        <div class="fc-cname">${escFc(name)}</div>
                        <div class="fc-cprev">${escFc(prev)}</div>
                    </div>
                    ${unrd > 0 ? `<div class="fc-cunread">${unrd}</div>` : ''}
                `;
                div.addEventListener('click', () => openFcConv(parseInt(c.conversation_id), name));
                fcConvView.appendChild(div);
            });
        });
    }

    function openFcConv(convId, name) {
        fcConvId    = convId;
        fcLastMsgId = 0;
        fcConvView.style.display = 'none';
        fcMsgView.style.display  = 'flex';
        fcMsgName.textContent    = name;
        fcMessages.innerHTML     = '';
        loadFcMessages(false);
        clearInterval(fcPollMsg);
        fcPollMsg = setInterval(() => loadFcMessages(true), 5000);
    }

    function loadFcMessages(polling) {
        const body = {conversation_id: fcConvId};
        if (polling && fcLastMsgId > 0) body.after_message_id = fcLastMsgId;
        fcAjax('get_messages', body).then(data => {
            if (!data.success) return;
            const msgs = data.messages;
            if (!msgs.length && !polling) {
                fcMessages.innerHTML = '<div class="text-center text-muted small py-2">No messages yet.</div>';
                return;
            }
            if (!msgs.length) return;
            if (!polling) fcMessages.innerHTML = '';
            msgs.forEach(m => {
                const mine = parseInt(m.sender_id) === ME_ID;
                const b    = document.createElement('div');
                b.className = 'fc-bubble ' + (mine ? 'mine' : 'theirs');
                const t    = m.sent_at ? new Date(m.sent_at.replace(' ','T')).toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'}) : '';
                b.innerHTML = `${escFc(m.message_text)}<span class="fc-btime">${t}</span>`;
                fcMessages.appendChild(b);
                if (parseInt(m.message_id) > fcLastMsgId) fcLastMsgId = parseInt(m.message_id);
            });
            fcMessages.scrollTop = fcMessages.scrollHeight;
        });
    }

    function fcSend() {
        const txt = fcInput.value.trim();
        if (!txt || !fcConvId) return;
        fcInput.value = '';
        fcAjax('send_message', {conversation_id: fcConvId, message_text: txt})
            .then(() => loadFcMessages(true));
    }

    document.getElementById('fcSendBtn').addEventListener('click', fcSend);
    fcInput.addEventListener('keydown', e => { if (e.key==='Enter') { e.preventDefault(); fcSend(); } });
    document.getElementById('fcBackBtn').addEventListener('click', () => {
        clearInterval(fcPollMsg);
        fcConvView.style.display = 'block';
        fcMsgView.style.display  = 'none';
    });

    // Unread badge polling (every 10s)
    function pollUnread() {
        fcAjax('get_unread_count').then(data => {
            const n = data.unread || 0;
            if (n > 0) {
                fcBadge.textContent     = n > 99 ? '99+' : n;
                fcBadge.style.display   = 'flex';
            } else {
                fcBadge.style.display   = 'none';
            }
        });
    }
    pollUnread();
    setInterval(pollUnread, 10000);

    function escFc(s) {
        return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
    }
})();
</script>