<?php

include '../../includes/header.php';

$auth = new Auth($conn);
$auth->enforceSuperAdminPrivileges($_SESSION['user_id']);
?>

<style>
    .monitor-wrapper {
        display: flex;
        height: calc(100vh - 200px);
        min-height: 480px;
        border: 1px solid #dee2e6;
        border-radius: 6px;
        overflow: hidden;
        background: #fff;
    }
    .monitor-list {
        width: 340px;
        min-width: 260px;
        border-right: 1px solid #dee2e6;
        overflow-y: auto;
    }
    .monitor-conversation-item {
        display: block;
        width: 100%;
        text-align: left;
        padding: 10px 12px;
        border: none;
        border-bottom: 1px solid #f1f1f1;
        background: #fff;
        cursor: pointer;
    }
    .monitor-conversation-item:hover, .monitor-conversation-item.active {
        background: #f0f4ff;
    }
    .monitor-conversation-item .conv-name {
        font-weight: 600;
        display: flex;
        justify-content: space-between;
    }
    .monitor-conversation-item .conv-preview {
        font-size: 0.85rem;
        color: #6c757d;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .monitor-main {
        flex: 1;
        display: flex;
        flex-direction: column;
        min-width: 0;
    }
    .monitor-main-header {
        padding: 12px;
        border-bottom: 1px solid #dee2e6;
        font-weight: 600;
    }
    .monitor-messages {
        flex: 1;
        overflow-y: auto;
        padding: 12px;
        background: #fafafa;
    }
    .monitor-message {
        max-width: 70%;
        margin-bottom: 10px;
        padding: 8px 12px;
        border-radius: 10px;
        background: #fff;
        border: 1px solid #e5e5e5;
    }
    .monitor-message .msg-sender {
        font-size: 0.75rem;
        font-weight: 600;
        color: #495057;
    }
    .monitor-message .msg-time {
        font-size: 0.7rem;
        color: #999;
        margin-left: 6px;
    }
    .monitor-message .msg-deleted-note {
        font-size: 0.7rem;
        color: #dc3545;
        margin-top: 2px;
    }
    .monitor-empty-state {
        margin: auto;
        color: #999;
        text-align: center;
    }
</style>

<div class="container-fluid mt-4">
    <div class="row">
        <div class="col-12">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="../dashboard/admin.php">Dashboard</a></li>
                    <li class="breadcrumb-item active">Messages</li>
                </ol>
            </nav>
            <h2><i class="fas fa-comments"></i> Messages Monitor</h2>
            <p class="text-muted">Read-only oversight of every conversation in the system. Super admin only.</p>
        </div>
    </div>

    <div class="monitor-wrapper mt-3">
        <div class="monitor-list" id="monitorConversationList">
            <div class="text-center text-muted p-3">Loading conversations&hellip;</div>
        </div>
        <div class="monitor-main">
            <div class="monitor-main-header" id="monitorMainHeader">Select a conversation</div>
            <div class="monitor-messages" id="monitorMessages">
                <div class="monitor-empty-state">Choose a conversation from the left to view its full history.</div>
            </div>
        </div>
    </div>
</div>

<script>
(function () {
    const BASE = '/IMS/ajax/admin/';
    let activeConversationId = null;

    function escapeHtml(str) {
        const div = document.createElement('div');
        div.textContent = str == null ? '' : String(str);
        return div.innerHTML;
    }

    function formatTime(dateStr) {
        if (!dateStr) return '';
        const d = new Date(dateStr.replace(' ', 'T'));
        if (isNaN(d.getTime())) return dateStr;
        return d.toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
    }

    function loadConversations() {
        fetch(BASE + 'messages_monitor_conversations.php')
            .then(r => r.json())
            .then(data => {
                if (!data.success) return;
                renderConversations(data.conversations || []);
            })
            .catch(() => {});
    }

    function renderConversations(conversations) {
        const list = document.getElementById('monitorConversationList');
        if (!conversations.length) {
            list.innerHTML = '<div class="text-center text-muted p-3">No conversations exist yet.</div>';
            return;
        }
        list.innerHTML = conversations.map(c => {
            const active = c.conversation_id == activeConversationId ? 'active' : '';
            return `<button type="button" class="monitor-conversation-item ${active}" data-conversation-id="${c.conversation_id}" data-display-name="${escapeHtml(c.display_name)}">
                        <div class="conv-name"><span>${escapeHtml(c.display_name)}</span><span class="text-muted small">${c.message_count}</span></div>
                        <div class="conv-preview">${escapeHtml(c.last_message || 'No messages yet')}</div>
                    </button>`;
        }).join('');

        list.querySelectorAll('.monitor-conversation-item').forEach(btn => {
            btn.addEventListener('click', () => {
                openConversation(parseInt(btn.dataset.conversationId, 10), btn.dataset.displayName);
            });
        });
    }

    function openConversation(conversationId, displayName) {
        activeConversationId = conversationId;
        document.getElementById('monitorMainHeader').textContent = displayName;
        document.querySelectorAll('.monitor-conversation-item').forEach(btn => {
            btn.classList.toggle('active', parseInt(btn.dataset.conversationId, 10) === conversationId);
        });
        loadThread();
    }

    function loadThread() {
        const container = document.getElementById('monitorMessages');
        container.innerHTML = '<div class="text-center text-muted p-3">Loading&hellip;</div>';

        fetch(BASE + 'messages_monitor_thread.php?conversation_id=' + activeConversationId)
            .then(r => r.json())
            .then(data => {
                if (!data.success) {
                    container.innerHTML = '<div class="alert alert-danger m-2">' + escapeHtml(data.error || 'Failed to load messages') + '</div>';
                    return;
                }
                renderMessages(data.messages || []);
            })
            .catch(() => {
                container.innerHTML = '<div class="alert alert-danger m-2">Failed to load messages.</div>';
            });
    }

    function renderMessages(messages) {
        const container = document.getElementById('monitorMessages');
        if (!messages.length) {
            container.innerHTML = '<div class="monitor-empty-state">No messages in this conversation.</div>';
            return;
        }
        container.innerHTML = messages.map(m => {
            const bodyHtml = m.body ? `<div class="msg-body">${escapeHtml(m.body)}</div>` : '';
            const deletedNote = m.deleted_for_usernames
                ? `<div class="msg-deleted-note"><i class="fas fa-eye-slash"></i> Deleted for: ${escapeHtml(m.deleted_for_usernames)}</div>`
                : '';
            const attachment = m.attachment_path
                ? `<div class="text-muted small mt-1"><i class="fas fa-paperclip"></i> ${escapeHtml(m.attachment_name || 'attachment')}</div>`
                : '';
            return `<div class="monitor-message">
                        <div><span class="msg-sender">${escapeHtml(m.sender_username)}</span><span class="msg-time">${formatTime(m.created_at)}</span></div>
                        ${bodyHtml}
                        ${attachment}
                        ${deletedNote}
                    </div>`;
        }).join('');
        container.scrollTop = container.scrollHeight;
    }

    loadConversations();
})();
</script>

<?php include '../../includes/footer.php'; ?>
