<?php
include '../../includes/header.php';
$currentUserId = (int)$_SESSION['user_id'];
?>
<style>
    .chat-wrapper {
        display: flex;
        height: calc(100vh - 200px);
        min-height: 480px;
        border: 1px solid #dee2e6;
        border-radius: 6px;
        overflow: hidden;
        background: #fff;
    }
    .chat-sidebar {
        width: 320px;
        min-width: 260px;
        border-right: 1px solid #dee2e6;
        display: flex;
        flex-direction: column;
    }
    .chat-sidebar-header {
        padding: 12px;
        border-bottom: 1px solid #dee2e6;
    }
    .chat-conversation-list {
        flex: 1;
        overflow-y: auto;
    }
    .chat-conversation-item {
        display: block;
        width: 100%;
        text-align: left;
        padding: 10px 12px;
        border: none;
        border-bottom: 1px solid #f1f1f1;
        background: #fff;
        cursor: pointer;
    }
    .chat-conversation-item:hover, .chat-conversation-item.active {
        background: #f0f4ff;
    }
    .chat-conversation-item .conv-name {
        font-weight: 600;
        display: flex;
        justify-content: space-between;
    }
    .chat-conversation-item .conv-preview {
        font-size: 0.85rem;
        color: #6c757d;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .chat-main {
        flex: 1;
        display: flex;
        flex-direction: column;
        min-width: 0;
    }
    .chat-main-header {
        padding: 12px;
        border-bottom: 1px solid #dee2e6;
        font-weight: 600;
    }
    .chat-messages {
        flex: 1;
        overflow-y: auto;
        padding: 12px;
        background: #fafafa;
    }
    .chat-message {
        max-width: 70%;
        margin-bottom: 10px;
        padding: 8px 12px;
        border-radius: 10px;
        background: #fff;
        border: 1px solid #e5e5e5;
    }
    .chat-message.own {
        margin-left: auto;
        background: #d1e7ff;
        border-color: #b6d4fe;
    }
    .chat-message .msg-sender {
        font-size: 0.75rem;
        font-weight: 600;
        color: #495057;
    }
    .chat-message .msg-time {
        font-size: 0.7rem;
        color: #999;
        margin-left: 6px;
    }
    .chat-input-row {
        padding: 10px;
        border-top: 1px solid #dee2e6;
        display: flex;
        gap: 8px;
    }
    .chat-empty-state {
        margin: auto;
        color: #999;
        text-align: center;
    }
    .user-pick-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 6px 10px;
        cursor: pointer;
        border-radius: 4px;
    }
    .user-pick-item:hover {
        background: #f0f4ff;
    }
    .user-pick-item.selected {
        background: #d1e7ff;
    }
    .msg-attachment-image {
        max-width: 220px;
        max-height: 220px;
        border-radius: 6px;
        display: block;
        margin-top: 4px;
        cursor: pointer;
    }
    .msg-attachment-file {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-top: 4px;
        padding: 6px 10px;
        background: rgba(0,0,0,0.04);
        border-radius: 6px;
        text-decoration: none;
        color: inherit;
    }
    .msg-attachment-file .file-size {
        font-size: 0.75rem;
        color: #6c757d;
    }
    .msg-attachment-audio {
        margin-top: 4px;
        max-width: 260px;
    }
    #chatRecordingIndicator {
        display: none;
        align-items: center;
        gap: 6px;
        color: #dc3545;
        font-size: 0.85rem;
        padding: 0 8px;
    }
    #chatRecordingIndicator .rec-dot {
        width: 10px;
        height: 10px;
        border-radius: 50%;
        background: #dc3545;
        animation: rec-blink 1s infinite;
    }
    @keyframes rec-blink {
        0%, 100% { opacity: 1; }
        50% { opacity: 0.2; }
    }
</style>

<div class="d-flex justify-content-between align-items-center mb-3">
    <h4 class="mb-0"><i class="fas fa-comments me-2"></i>Messages</h4>
</div>

<div class="chat-wrapper">
    <div class="chat-sidebar">
        <div class="chat-sidebar-header">
            <button type="button" class="btn btn-primary btn-sm w-100" data-bs-toggle="modal" data-bs-target="#newMessageModal">
                <i class="fas fa-plus me-1"></i>New Message
            </button>
        </div>
        <div class="chat-conversation-list" id="conversationList">
            <div class="text-center text-muted p-3">Loading conversations&hellip;</div>
        </div>
    </div>
    <div class="chat-main">
        <div class="chat-main-header" id="chatMainHeader">Select a conversation</div>
        <div class="chat-messages" id="chatMessages">
            <div class="chat-empty-state">Choose a conversation from the left, or start a new message.</div>
        </div>
        <div class="chat-input-row d-none" id="chatInputRow">
            <input type="file" id="chatAttachmentInput" class="d-none" accept="image/jpeg,image/png,image/gif,image/webp,.pdf,.doc,.docx,.xls,.xlsx">
            <button type="button" class="btn btn-outline-secondary" id="chatAttachBtn" title="Attach a file"><i class="fas fa-paperclip"></i></button>
            <button type="button" class="btn btn-outline-secondary" id="chatMicBtn" title="Record a voice note"><i class="fas fa-microphone"></i></button>
            <span id="chatRecordingIndicator"><span class="rec-dot"></span><span id="chatRecordingTime">0:00</span></span>
            <textarea id="chatMessageBody" class="form-control" rows="1" placeholder="Type a message..."></textarea>
            <button type="button" class="btn btn-primary" id="chatSendBtn"><i class="fas fa-paper-plane"></i></button>
        </div>
    </div>
</div>

<!-- New Message Modal -->
<div class="modal fade" id="newMessageModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">New Message</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Search users</label>
                    <input type="text" class="form-control" id="userSearchInput" placeholder="Type a username...">
                </div>
                <div id="userSearchResults" class="mb-3" style="max-height: 220px; overflow-y: auto;"></div>
                <div id="selectedUsersLabel" class="text-muted small mb-2"></div>
                <div class="mb-3 d-none" id="groupTitleWrapper">
                    <label class="form-label">Group name</label>
                    <input type="text" class="form-control" id="groupTitleInput" placeholder="e.g. Branch Team">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="startConversationBtn">Start Conversation</button>
            </div>
        </div>
    </div>
</div>

<script>
(function () {
    const currentUserId = <?php echo (int)$currentUserId; ?>;
    const BASE = '/IMS/ajax/';

    let activeConversationId = null;
    let lastMessageId = 0;
    let conversationPollTimer = null;
    let threadPollTimer = null;
    let selectedUsers = {}; // user_id -> username

    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_conversations.php')
            .then(r => r.json())
            .then(data => {
                if (!data.success) return;
                renderConversations(data.conversations || []);
            })
            .catch(() => {});
    }

    function renderConversations(conversations) {
        const list = document.getElementById('conversationList');
        if (!conversations.length) {
            list.innerHTML = '<div class="text-center text-muted p-3">No conversations yet.</div>';
            return;
        }
        list.innerHTML = conversations.map(c => {
            const active = c.conversation_id == activeConversationId ? 'active' : '';
            const unreadBadge = c.unread_count > 0
                ? `<span class="badge bg-danger rounded-pill">${c.unread_count}</span>`
                : '';
            return `<button type="button" class="chat-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>${unreadBadge}</div>
                        <div class="conv-preview">${escapeHtml(c.last_message || 'No messages yet')}</div>
                    </button>`;
        }).join('');

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

    function openConversation(conversationId, displayName) {
        activeConversationId = conversationId;
        lastMessageId = 0;
        document.getElementById('chatMainHeader').textContent = displayName;
        document.getElementById('chatMessages').innerHTML = '';
        document.getElementById('chatInputRow').classList.remove('d-none');

        document.querySelectorAll('.chat-conversation-item').forEach(btn => {
            btn.classList.toggle('active', parseInt(btn.dataset.conversationId, 10) === conversationId);
        });

        if (threadPollTimer) clearInterval(threadPollTimer);
        loadThread(true);
        threadPollTimer = setInterval(() => loadThread(false), 10000);
    }

    function loadThread(scrollToBottom) {
        if (!activeConversationId) return;
        fetch(BASE + 'messages_thread.php?conversation_id=' + activeConversationId + '&after_id=' + lastMessageId)
            .then(r => r.json())
            .then(data => {
                if (!data.success) return;
                appendMessages(data.messages || [], scrollToBottom);
                if ((data.messages || []).length > 0) {
                    loadConversations();
                }
            })
            .catch(() => {});
    }

    function formatFileSize(bytes) {
        bytes = parseInt(bytes, 10) || 0;
        if (bytes < 1024) return bytes + ' B';
        if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
        return (bytes / 1024 / 1024).toFixed(1) + ' MB';
    }

    function renderAttachment(m) {
        if (!m.attachment_path) return '';
        const url = '/IMS/uploads/messages/' + encodeURIComponent(m.attachment_path);
        if (m.attachment_kind === 'voice') {
            return `<audio class="msg-attachment-audio" controls src="${url}"></audio>`;
        }
        if ((m.attachment_type || '').startsWith('image/')) {
            return `<a href="${url}" target="_blank" rel="noopener"><img class="msg-attachment-image" src="${url}" alt="${escapeHtml(m.attachment_name)}"></a>`;
        }
        return `<a class="msg-attachment-file" href="${url}" target="_blank" rel="noopener">
                    <i class="fas fa-file-alt"></i>
                    <span>${escapeHtml(m.attachment_name)}</span>
                    <span class="file-size">${formatFileSize(m.attachment_size)}</span>
                </a>`;
    }

    function appendMessages(messages, scrollToBottom) {
        if (!messages.length) return;
        const container = document.getElementById('chatMessages');
        messages.forEach(m => {
            lastMessageId = Math.max(lastMessageId, parseInt(m.message_id, 10));
            const own = parseInt(m.sender_id, 10) === currentUserId;
            const div = document.createElement('div');
            div.className = 'chat-message' + (own ? ' own' : '');
            div.dataset.messageId = m.message_id;
            const bodyHtml = m.body ? `<div class="msg-body">${escapeHtml(m.body)}</div>` : '';
            div.innerHTML = `<div><span class="msg-sender">${escapeHtml(m.sender_username)}</span><span class="msg-time">${formatTime(m.created_at)}</span><button type="button" class="btn btn-sm btn-link text-muted msg-delete-btn float-end p-0" title="Delete for me" data-message-id="${m.message_id}"><i class="fas fa-times"></i></button></div>
                              ${bodyHtml}
                              ${renderAttachment(m)}`;
            container.appendChild(div);
        });
        if (scrollToBottom !== false) {
            container.scrollTop = container.scrollHeight;
        }
    }

    // Delete-for-me: hides a message from this user's own view only. Other participants
    // and admin monitoring still see it (server-side, message_deletions is per-viewer).
    document.getElementById('chatMessages').addEventListener('click', function (e) {
        const btn = e.target.closest('.msg-delete-btn');
        if (!btn) return;
        if (!confirm('Delete this message for you only? Other participants will still see it.')) return;

        const messageId = btn.dataset.messageId;
        const formData = new URLSearchParams();
        formData.append('message_id', messageId);

        fetch(BASE + 'messages_delete.php', { method: 'POST', body: formData })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    const bubble = document.querySelector(`.chat-message[data-message-id="${messageId}"]`);
                    bubble?.remove();
                } else {
                    alert(data.message || 'Unable to delete message.');
                }
            })
            .catch(() => alert('Unable to delete message.'));
    });

    function sendMessage() {
        const textarea = document.getElementById('chatMessageBody');
        const body = textarea.value.trim();
        if (!body || !activeConversationId) return;

        const formData = new URLSearchParams();
        formData.append('conversation_id', activeConversationId);
        formData.append('body', body);

        fetch(BASE + 'messages_send.php', { method: 'POST', body: formData })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    textarea.value = '';
                    appendMessages([data.message_data], true);
                    loadConversations();
                } else {
                    alert(data.message || 'Unable to send message.');
                }
            })
            .catch(() => alert('Unable to send message.'));
    }

    document.getElementById('chatSendBtn').addEventListener('click', sendMessage);
    document.getElementById('chatMessageBody').addEventListener('keydown', function (e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    });

    function uploadAttachment(file, kind) {
        if (!activeConversationId) return;
        const textarea = document.getElementById('chatMessageBody');
        const formData = new FormData();
        formData.append('conversation_id', activeConversationId);
        formData.append('body', textarea.value.trim());
        formData.append('kind', kind);
        formData.append('attachment', file, file.name || (kind + '.dat'));

        fetch(BASE + 'messages_upload.php', { method: 'POST', body: formData })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    textarea.value = '';
                    appendMessages([data.message_data], true);
                    loadConversations();
                } else {
                    alert(data.message || 'Unable to send attachment.');
                }
            })
            .catch(() => alert('Unable to send attachment.'));
    }

    const attachmentInput = document.getElementById('chatAttachmentInput');
    document.getElementById('chatAttachBtn').addEventListener('click', () => {
        if (!activeConversationId) return;
        attachmentInput.click();
    });
    attachmentInput.addEventListener('change', function () {
        if (this.files && this.files[0]) {
            uploadAttachment(this.files[0], 'file');
        }
        this.value = '';
    });

    // Voice notes
    let mediaRecorder = null;
    let recordedChunks = [];
    let recordingStartedAt = 0;
    let recordingTimerHandle = null;

    function pickRecorderMimeType() {
        const candidates = ['audio/webm;codecs=opus', 'audio/webm', 'audio/ogg', 'audio/mp4'];
        for (const type of candidates) {
            if (window.MediaRecorder && MediaRecorder.isTypeSupported && MediaRecorder.isTypeSupported(type)) {
                return type;
            }
        }
        return '';
    }

    function updateRecordingTimer() {
        const elapsed = Math.floor((Date.now() - recordingStartedAt) / 1000);
        const minutes = Math.floor(elapsed / 60);
        const seconds = elapsed % 60;
        document.getElementById('chatRecordingTime').textContent = minutes + ':' + String(seconds).padStart(2, '0');
    }

    function startRecording() {
        if (!activeConversationId) return;
        if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
            alert('Voice recording is not supported in this browser.');
            return;
        }
        navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => {
            const mimeType = pickRecorderMimeType();
            recordedChunks = [];
            mediaRecorder = mimeType ? new MediaRecorder(stream, { mimeType }) : new MediaRecorder(stream);
            mediaRecorder.addEventListener('dataavailable', e => {
                if (e.data && e.data.size > 0) recordedChunks.push(e.data);
            });
            mediaRecorder.addEventListener('stop', () => {
                stream.getTracks().forEach(track => track.stop());
                const blob = new Blob(recordedChunks, { type: mediaRecorder.mimeType || 'audio/webm' });
                const ext = (mediaRecorder.mimeType || 'audio/webm').includes('mp4') ? 'm4a' : 'webm';
                uploadAttachment(new File([blob], 'voice-note.' + ext, { type: blob.type }), 'voice');
            });
            mediaRecorder.start();
            recordingStartedAt = Date.now();
            document.getElementById('chatRecordingIndicator').style.display = 'flex';
            document.getElementById('chatMicBtn').innerHTML = '<i class="fas fa-stop"></i>';
            recordingTimerHandle = setInterval(updateRecordingTimer, 500);
        }).catch(() => {
            alert('Microphone access was denied or is unavailable.');
        });
    }

    function stopRecording() {
        if (mediaRecorder && mediaRecorder.state !== 'inactive') {
            mediaRecorder.stop();
        }
        clearInterval(recordingTimerHandle);
        document.getElementById('chatRecordingIndicator').style.display = 'none';
        document.getElementById('chatMicBtn').innerHTML = '<i class="fas fa-microphone"></i>';
    }

    document.getElementById('chatMicBtn').addEventListener('click', () => {
        if (mediaRecorder && mediaRecorder.state === 'recording') {
            stopRecording();
        } else {
            startRecording();
        }
    });

    // New conversation modal
    const userSearchInput = document.getElementById('userSearchInput');
    const userSearchResults = document.getElementById('userSearchResults');
    const groupTitleWrapper = document.getElementById('groupTitleWrapper');
    const selectedUsersLabel = document.getElementById('selectedUsersLabel');
    let searchDebounce = null;

    function renderSelectedUsers() {
        const names = Object.values(selectedUsers);
        selectedUsersLabel.textContent = names.length ? ('Selected: ' + names.join(', ')) : '';
        groupTitleWrapper.classList.toggle('d-none', names.length < 2);
    }

    userSearchInput.addEventListener('input', function () {
        clearTimeout(searchDebounce);
        const q = this.value.trim();
        searchDebounce = setTimeout(() => {
            fetch(BASE + 'messages_search_users.php?q=' + encodeURIComponent(q))
                .then(r => r.json())
                .then(data => {
                    if (!data.success) return;
                    userSearchResults.innerHTML = (data.users || []).map(u => {
                        const selected = selectedUsers[u.user_id] ? 'selected' : '';
                        return `<div class="user-pick-item ${selected}" data-user-id="${u.user_id}" data-username="${escapeHtml(u.username)}">
                                    <span>${escapeHtml(u.username)} <small class="text-muted">${escapeHtml(u.role)}</small></span>
                                    ${selected ? '<i class="fas fa-check"></i>' : ''}
                                </div>`;
                    }).join('') || '<div class="text-muted small">No users found.</div>';

                    userSearchResults.querySelectorAll('.user-pick-item').forEach(item => {
                        item.addEventListener('click', () => {
                            const id = item.dataset.userId;
                            const username = item.dataset.username;
                            if (selectedUsers[id]) {
                                delete selectedUsers[id];
                            } else {
                                selectedUsers[id] = username;
                            }
                            renderSelectedUsers();
                            item.classList.toggle('selected');
                            item.querySelector('i')?.remove();
                            if (selectedUsers[id]) {
                                item.insertAdjacentHTML('beforeend', '<i class="fas fa-check"></i>');
                            }
                        });
                    });
                })
                .catch(() => {});
        }, 250);
    });

    document.getElementById('startConversationBtn').addEventListener('click', function () {
        const ids = Object.keys(selectedUsers);
        if (!ids.length) {
            alert('Select at least one user.');
            return;
        }
        const title = document.getElementById('groupTitleInput').value.trim();
        if (ids.length > 1 && !title) {
            alert('Group conversations require a name.');
            return;
        }

        const formData = new URLSearchParams();
        ids.forEach(id => formData.append('participant_ids[]', id));
        if (title) formData.append('title', title);

        fetch(BASE + 'messages_start.php', { method: 'POST', body: formData })
            .then(r => r.json())
            .then(data => {
                if (!data.success) {
                    alert(data.message || 'Unable to start conversation.');
                    return;
                }
                selectedUsers = {};
                renderSelectedUsers();
                userSearchInput.value = '';
                userSearchResults.innerHTML = '';
                document.getElementById('groupTitleInput').value = '';
                const modalEl = document.getElementById('newMessageModal');
                bootstrap.Modal.getInstance(modalEl)?.hide();
                loadConversations();
                setTimeout(() => {
                    const btn = document.querySelector(`.chat-conversation-item[data-conversation-id="${data.conversation_id}"]`);
                    openConversation(data.conversation_id, btn ? btn.dataset.displayName : 'Conversation');
                }, 300);
            })
            .catch(() => alert('Unable to start conversation.'));
    });

    loadConversations();
    conversationPollTimer = setInterval(loadConversations, 15000);
})();
</script>

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