<?php
/**
 * Guards - Messages (Gmail-style View)
 * Enhanced with search, filters, responsive layout, and Quill editor
 */

$auth = $GLOBALS['auth'];
$db = $GLOBALS['db'];

// Check permission
if (!$auth->canAccessPage('guards-messages-gmail')) {
    header('Location: ?page=guard/dashboard');
    exit();
}

$currentUser = $db->fetch("SELECT id, name FROM users WHERE id = ?", [$_SESSION['user_id'] ?? 0]);
if (!$currentUser) {
    header('Location: ?page=guard/dashboard');
    exit();
}

// Get pagination and search parameters
$page = (int)($_GET['p'] ?? 1);
$pageSize = 10;
$offset = ($page - 1) * $pageSize;
$searchQuery = $_GET['search'] ?? '';

// Get unread count
$unreadCount = $db->fetch(
    "SELECT COUNT(*) as count FROM messages 
     WHERE ((recipient_id = ? AND is_read = 0) OR (sender_id = ? AND is_read = 0)) 
     AND parent_message_id IS NULL",
    [$currentUser['id'], $currentUser['id']]
)['count'] ?? 0;

// Build search clause
$searchClause = '';
$searchParams = [$currentUser['id'], $currentUser['id']];
if ($searchQuery) {
    $searchClause = " AND (m.subject LIKE ? OR m.message LIKE ? OR u.name LIKE ?)";
    $searchParams[] = "%$searchQuery%";
    $searchParams[] = "%$searchQuery%";
    $searchParams[] = "%$searchQuery%";
}

// Get all conversations (merged - both sent and received)
$conversations = $db->fetchAll(
    "SELECT m.*, u.name as sender_name, u.id as sender_id_other, u.role as sender_role,
            (SELECT COUNT(*) FROM messages WHERE id = m.id OR parent_message_id = m.id) as reply_count,
            (SELECT MAX(created_at) FROM messages WHERE id = m.id OR parent_message_id = m.id) as last_message_at,
            (SELECT COUNT(*) FROM messages WHERE (id = m.id OR parent_message_id = m.id) AND is_read = 0 AND recipient_id = ?) as unread_count
     FROM messages m
     JOIN users u ON (CASE WHEN m.sender_id = ? THEN m.recipient_id ELSE m.sender_id END) = u.id
     WHERE (m.recipient_id = ? OR m.sender_id = ?) AND m.parent_message_id IS NULL
     $searchClause
     ORDER BY last_message_at DESC
     LIMIT $pageSize OFFSET $offset",
    array_merge([$currentUser['id']], [$currentUser['id']], $searchParams)
);

// Get total count
$countParams = [$currentUser['id'], $currentUser['id']];
if ($searchQuery) {
    $countParams[] = "%$searchQuery%";
    $countParams[] = "%$searchQuery%";
    $countParams[] = "%$searchQuery%";
}

$totalConversations = $db->fetch(
    "SELECT COUNT(*) as count FROM messages m
     WHERE (m.recipient_id = ? OR m.sender_id = ?) AND m.parent_message_id IS NULL
     $searchClause",
    $countParams
)['count'];

$totalPages = ceil($totalConversations / $pageSize);

require_once __DIR__ . '/../../layouts/header.php';
?>

<style>
* {
    box-sizing: border-box;
}

.messaging-container {
    display: grid;
    grid-template-columns: 1fr;
    gap: 1rem;
    height: 100vh;
}

@media (min-width: 1024px) {
    .messaging-container {
        grid-template-columns: 380px 1fr;
    }
}

.conversations-panel {
    display: flex;
    flex-direction: column;
    border: 1px solid #e5e7eb;
    border-radius: 12px;
    background: white;
    overflow: hidden;
}

.conversations-list {
    flex: 1;
    overflow-y: auto;
    min-height: 300px;
}

.conversation-item {
    padding: 0.75rem;
    border-bottom: 1px solid #f3f4f6;
    cursor: pointer;
    transition: all 0.2s ease;
    background: white;
    position: relative;
}

.conversation-item:hover {
    background: #f9fafb;
    border-left: 4px solid #22c55e;
}

.conversation-item.selected {
    background: linear-gradient(135deg, #15803d 0%, #166534 100%);
    color: white;
    border-left: 4px solid #fbbf24;
}

.unread-badge {
    position: absolute;
    top: 0.5rem;
    right: 0.5rem;
    background: #ef4444;
    color: white;
    padding: 0.25rem 0.5rem;
    border-radius: 12px;
    font-size: 0.75rem;
    font-weight: bold;
    min-width: 20px;
    text-align: center;
}

.thread-panel {
    display: none;
    flex-direction: column;
    border: 1px solid #e5e7eb;
    border-radius: 12px;
    background: white;
    overflow: hidden;
}

.thread-panel.active {
    display: flex;
}

@media (max-width: 1023px) {
    .thread-panel.active {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        width: 100%;
        height: 100%;
        z-index: 40;
        border-radius: 0;
        border: none;
    }
    
    .conversations-panel {
        display: none;
    }
    
    .messaging-container {
        grid-template-columns: 1fr;
    }
}

.thread-header {
    padding: 1rem;
    border-bottom: 1px solid #e5e7eb;
    background: linear-gradient(135deg, #dcfce7 0%, #bbf7d0 100%);
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.thread-messages {
    flex: 1;
    overflow-y: auto;
    padding: 1rem;
}

.message-item {
    display: flex;
    margin-bottom: 1rem;
    animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
}

.message-item.own {
    justify-content: flex-end;
}

.message-bubble {
    max-width: 70%;
    padding: 0.75rem 1rem;
    border-radius: 12px;
    word-wrap: break-word;
    overflow-wrap: break-word;
}

.message-bubble.received {
    background: #f3f4f6;
    color: #1f2937;
}

.message-bubble.sent {
    background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
    color: white;
}

.message-time {
    font-size: 0.75rem;
    margin-top: 0.25rem;
    opacity: 0.7;
}

.thread-reply {
    padding: 1rem;
    border-top: 1px solid #e5e7eb;
    background: #f9fafb;
}

.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: #6b7280;
    text-align: center;
}

.empty-state i {
    font-size: 3rem;
    margin-bottom: 1rem;
    opacity: 0.5;
}

.search-bar {
    padding: 1rem;
    border-bottom: 1px solid #e5e7eb;
    display: flex;
    gap: 0.5rem;
}

.search-bar input {
    flex: 1;
    padding: 0.5rem 0.75rem;
    border: 1px solid #d1d5db;
    border-radius: 6px;
    font-size: 0.875rem;
}

.search-bar button {
    padding: 0.5rem 0.75rem;
    background: #22c55e;
    color: white;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: 0.875rem;
}

.modal {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 50;
    align-items: center;
    justify-content: center;
}

.modal.active {
    display: flex;
}

.modal-content {
    background: white;
    border-radius: 12px;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
    width: 95%;
    max-width: 600px;
    max-height: 85vh;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

.modal-header {
    padding: 1rem;
    border-bottom: 1px solid #e5e7eb;
    background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
    color: white;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.modal-body {
    flex: 1;
    overflow-y: auto;
    padding: 1rem;
}

.modal-footer {
    padding: 0.75rem 1rem;
    border-top: 1px solid #e5e7eb;
    background: #f9fafb;
    display: flex;
    gap: 0.5rem;
    justify-content: flex-end;
}

.form-group {
    margin-bottom: 0.75rem;
}

.form-group label {
    display: block;
    font-size: 0.875rem;
    font-weight: 600;
    margin-bottom: 0.25rem;
    color: #374151;
}

.form-group input,
.form-group select,
.form-group textarea {
    width: 100%;
    padding: 0.5rem 0.75rem;
    border: 1px solid #d1d5db;
    border-radius: 6px;
    font-size: 0.875rem;
    font-family: inherit;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
    outline: none;
    border-color: #22c55e;
    box-shadow: 0 0 0 3px rgba(34, 197, 94, 0.1);
}

.attachment-list {
    display: grid;
    gap: 0.5rem;
}

.attachment-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0.5rem 0.75rem;
    background: #f0fdf4;
    border: 1px solid #bbf7d0;
    border-radius: 6px;
    font-size: 0.875rem;
}

.attachment-item button {
    background: none;
    border: none;
    color: #dc2626;
    cursor: pointer;
    padding: 0.25rem;
}

.btn {
    padding: 0.5rem 1rem;
    border: none;
    border-radius: 6px;
    font-size: 0.875rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s ease;
}

.btn-primary {
    background: #22c55e;
    color: white;
}

.btn-primary:hover {
    background: #16a34a;
}

.btn-secondary {
    background: #e5e7eb;
    color: #374151;
}

.btn-secondary:hover {
    background: #d1d5db;
}

.badge-unread {
    display: inline-block;
    background: #ef4444;
    color: white;
    padding: 0.25rem 0.5rem;
    border-radius: 12px;
    font-size: 0.75rem;
    font-weight: bold;
    margin-left: 0.5rem;
}

.header-actions {
    display: flex;
    gap: 1rem;
    align-items: center;
}

.ql-container {
    border: 1px solid #d1d5db !important;
    border-radius: 6px;
    font-size: 0.875rem;
}

.ql-editor {
    min-height: 120px;
    max-height: 150px;
}

.back-button {
    display: none;
}

@media (max-width: 1023px) {
    .back-button {
        display: block;
    }
}
</style>

<div class="mx-auto px-4 py-6 max-w-7xl">
    <!-- Header -->
    <div class="mb-6">
        <div class="flex items-center justify-between mb-4">
            <h1 class="text-3xl font-bold text-gray-900">
                <i class="fas fa-inbox mr-2 text-green-600"></i>Messages
            </h1>
            <button onclick="openComposeModal()" class="px-4 py-2 bg-gradient-to-r from-green-600 to-green-700 text-white rounded-lg hover:from-green-700 hover:to-green-800 transition font-semibold">
                <i class="fas fa-pen mr-2"></i>New Message
                <?php if ($unreadCount > 0): ?>
                    <span class="badge-unread"><?php echo $unreadCount; ?></span>
                <?php endif; ?>
            </button>
        </div>
    </div>

    <!-- Main Layout -->
    <div class="messaging-container">
        <!-- Conversations Panel -->
        <div class="conversations-panel">
            <!-- Search Bar -->
            <div class="search-bar">
                <input type="text" id="searchInput" placeholder="Search conversations..." 
                    value="<?php echo htmlspecialchars($searchQuery); ?>" onkeypress="if(event.key==='Enter')searchConversations()">
                <button onclick="searchConversations()" class="btn btn-primary">
                    <i class="fas fa-search"></i>
                </button>
                <?php if ($searchQuery): ?>
                    <button onclick="clearSearch()" class="btn btn-secondary">
                        <i class="fas fa-times"></i>
                    </button>
                <?php endif; ?>
            </div>

            <!-- Conversations List -->
            <div class="conversations-list" id="conversationsList">
                <?php if (empty($conversations)): ?>
                    <div class="empty-state">
                        <i class="fas fa-inbox"></i>
                        <p>No conversations yet</p>
                    </div>
                <?php else: ?>
                    <?php foreach ($conversations as $conv): ?>
                        <div class="conversation-item" onclick="loadConversation(<?php echo $conv['id']; ?>, this)" data-id="<?php echo $conv['id']; ?>">
                            <div class="flex justify-between items-start mb-1">
                                <p class="font-semibold text-sm text-gray-900 truncate">
                                    <?php echo htmlspecialchars($conv['sender_name']); ?>
                                </p>
                                <?php if ($conv['unread_count'] > 0): ?>
                                    <span class="unread-badge"><?php echo $conv['unread_count']; ?></span>
                                <?php endif; ?>
                            </div>
                            <p class="text-xs text-gray-600 truncate mb-1">
                                <?php echo htmlspecialchars($conv['subject']); ?>
                            </p>
                            <p class="text-xs text-gray-500">
                                <?php echo date('M d, H:i', strtotime($conv['last_message_at'])); ?>
                            </p>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <!-- Pagination -->
            <?php if ($totalPages > 1): ?>
                <div class="border-t border-gray-200 p-2 flex items-center justify-between text-xs text-gray-600">
                    <span>Page <?php echo $page; ?> of <?php echo $totalPages; ?></span>
                    <div class="flex gap-1">
                        <?php if ($page > 1): ?>
                            <a href="?page=guards/messages/gmail-style&p=<?php echo $page - 1; ?><?php echo $searchQuery ? '&search=' . urlencode($searchQuery) : ''; ?>" 
                               class="px-2 py-1 hover:bg-gray-100 rounded">‹</a>
                        <?php endif; ?>
                        <?php if ($page < $totalPages): ?>
                            <a href="?page=guards/messages/gmail-style&p=<?php echo $page + 1; ?><?php echo $searchQuery ? '&search=' . urlencode($searchQuery) : ''; ?>" 
                               class="px-2 py-1 hover:bg-gray-100 rounded">›</a>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <!-- Thread Panel -->
        <div class="thread-panel" id="threadPanel">
            <div class="thread-header">
                <div class="flex-1">
                    <button onclick="goBackToList()" class="back-button mr-2 text-gray-900 hover:text-green-700">
                        <i class="fas fa-arrow-left"></i>
                    </button>
                    <div style="display: inline-block;">
                        <h2 id="threadSubject" class="font-bold text-gray-900 text-lg"></h2>
                        <p id="threadSender" class="text-sm text-gray-700"></p>
                    </div>
                </div>
                <button onclick="closeThread()" class="text-gray-900 hover:text-green-700">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>

            <div class="thread-messages" id="threadMessages"></div>

            <div class="thread-reply">
                <div class="form-group">
                    <label>Reply:</label>
                    <div id="composeEditor" style="height: 100px; background: white;"></div>
                </div>
                <div id="replyAttachments" class="attachment-list hidden mb-3"></div>
                <div class="flex gap-2 items-center justify-between">
                    <button onclick="openReplyAttachmentInput()" class="text-gray-600 hover:text-gray-900">
                        <i class="fas fa-paperclip mr-1"></i>Attach
                    </button>
                    <button onclick="sendReply()" class="btn btn-primary">
                        <i class="fas fa-send mr-1"></i>Send Reply
                    </button>
                </div>
                <input type="file" id="replyAttachmentInput" multiple class="hidden" onchange="handleReplyAttachmentSelect()">
            </div>
        </div>

        <!-- Empty State -->
        <div class="hidden lg:flex empty-state" id="emptyPanel">
            <div>
                <i class="fas fa-envelope-open-text"></i>
                <p>Select a conversation to start messaging</p>
            </div>
        </div>
    </div>
</div>

<!-- Compose Modal -->
<div id="composeModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <span><i class="fas fa-pen mr-2"></i>New Message</span>
            <button onclick="closeComposeModal()" class="text-white hover:text-green-100 bg-none border-none cursor-pointer">
                <i class="fas fa-times"></i>
            </button>
        </div>

        <div class="modal-body">
            <form id="composeForm">
                <div class="form-group">
                    <label>To:</label>
                    <select id="composeRecipient" required>
                        <option value="">Select recipient...</option>
                        <?php 
                        $users = $db->fetchAll("SELECT id, name, role FROM users WHERE id != ? AND active = 1 ORDER BY name", [$currentUser['id']]);
                        foreach ($users as $user):
                        ?>
                            <option value="<?php echo $user['id']; ?>">
                                <?php echo htmlspecialchars($user['name']) . ' (' . $user['role'] . ')'; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="form-group">
                    <label>Subject:</label>
                    <input type="text" id="composeSubject" placeholder="Message subject..." required>
                </div>

                <div class="form-group">
                    <label>Message:</label>
                    <div id="composeEditorQuill" style="height: 150px; background: white;"></div>
                </div>

                <div class="form-group">
                    <label>Attachments:</label>
                    <input type="file" id="composeAttachmentInput" multiple class="hidden" onchange="handleComposeAttachmentSelect()">
                    <button type="button" onclick="document.getElementById('composeAttachmentInput').click()" class="btn btn-secondary">
                        <i class="fas fa-upload mr-1"></i>Choose Files
                    </button>
                    <div id="composeAttachments" class="attachment-list hidden mt-2"></div>
                </div>
            </form>
        </div>

        <div class="modal-footer">
            <button onclick="sendCompose()" class="btn btn-primary">
                <i class="fas fa-send mr-1"></i>Send
            </button>
            <button onclick="closeComposeModal()" class="btn btn-secondary">
                Cancel
            </button>
        </div>
    </div>
</div>

<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>

<script>
let currentThreadId = null;
let replyFiles = [];
let composeFiles = [];
let composeQuill, replyQuill;
let threadOffset = 0;
const MESSAGES_PER_PAGE = 10;

// Initialize Quill editors
document.addEventListener('DOMContentLoaded', function() {
    composeQuill = new Quill('#composeEditorQuill', {
        theme: 'snow',
        modules: {
            toolbar: [['bold', 'italic', 'underline'], [{ 'list': 'ordered'}, { 'list': 'bullet' }]]
        }
    });

    replyQuill = new Quill('#composeEditor', {
        theme: 'snow',
        modules: {
            toolbar: [['bold', 'italic', 'underline'], [{ 'list': 'ordered'}, { 'list': 'bullet' }]]
        }
    });

    // Auto-refresh
    startAutoRefresh();
});

window.addEventListener('beforeunload', stopAutoRefresh);

let autoRefreshInterval;

function startAutoRefresh() {
    autoRefreshInterval = setInterval(() => {
        if (currentThreadId) {
            threadOffset = 0;
            loadThreadMessages();
        }
    }, 60000);
}

function stopAutoRefresh() {
    if (autoRefreshInterval) clearInterval(autoRefreshInterval);
}

function searchConversations() {
    const query = document.getElementById('searchInput').value.trim();
    window.location.href = '?page=guards/messages/gmail-style' + (query ? '&search=' + encodeURIComponent(query) : '');
}

function clearSearch() {
    window.location.href = '?page=guards/messages/gmail-style';
}

function openComposeModal() {
    document.getElementById('composeModal').classList.add('active');
    setTimeout(() => composeQuill.focus(), 100);
}

function closeComposeModal() {
    document.getElementById('composeModal').classList.remove('active');
    document.getElementById('composeForm').reset();
    composeQuill.setContents([]);
    composeFiles = [];
    document.getElementById('composeAttachments').innerHTML = '';
    document.getElementById('composeAttachments').classList.add('hidden');
}

function handleComposeAttachmentSelect() {
    const input = document.getElementById('composeAttachmentInput');
    composeFiles = Array.from(input.files);
    renderComposeAttachments();
}

function renderComposeAttachments() {
    const container = document.getElementById('composeAttachments');
    container.innerHTML = '';
    
    if (composeFiles.length === 0) {
        container.classList.add('hidden');
        return;
    }
    
    composeFiles.forEach((file, idx) => {
        container.innerHTML += `
            <div class="attachment-item">
                <span><i class="fas fa-file mr-1"></i>${file.name}</span>
                <button type="button" onclick="removeComposeAttachment(${idx})" class="hover:text-red-700">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `;
    });
    
    container.classList.remove('hidden');
}

function removeComposeAttachment(idx) {
    composeFiles.splice(idx, 1);
    renderComposeAttachments();
}

function sendCompose() {
    const recipient = document.getElementById('composeRecipient').value;
    const subject = document.getElementById('composeSubject').value.trim();
    const message = composeQuill.root.innerHTML;
    
    if (!recipient || !subject || !message || message === '<br>') {
        Swal.fire('Error', 'Please fill in all fields', 'error');
        return;
    }
    
    const formData = new FormData();
    formData.append('recipient_id', recipient);
    formData.append('subject', subject);
    formData.append('message', message);
    
    composeFiles.forEach(file => formData.append('attachments[]', file));
    
    fetch('?page=api&endpoint=guards/send-message', {
        method: 'POST',
        body: formData
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            Swal.fire('Success', 'Message sent', 'success');
            closeComposeModal();
            location.reload();
        } else {
            Swal.fire('Error', data.error || 'Failed to send', 'error');
        }
    })
    .catch(err => {
        console.error(err);
        Swal.fire('Error', 'Failed to send message', 'error');
    });
}

function loadConversation(messageId, element) {
    currentThreadId = messageId;
    
    document.querySelectorAll('.conversation-item').forEach(el => {
        el.classList.remove('selected');
    });
    element.classList.add('selected');
    
    document.getElementById('threadPanel').classList.add('active');
    document.getElementById('emptyPanel').classList.add('hidden');
    
    threadOffset = 0;
    replyFiles = [];
    replyQuill.setContents([]);
    document.getElementById('replyAttachments').innerHTML = '';
    document.getElementById('replyAttachments').classList.add('hidden');
    
    loadThreadMessages();
}

function loadThreadMessages() {
    const container = document.getElementById('threadMessages');
    
    if (threadOffset === 0) {
        container.innerHTML = '<div style="text-align: center; padding: 2rem; color: #999;"><i class="fas fa-spinner fa-spin"></i> Loading...</div>';
    }
    
    fetch(`?page=api&endpoint=guards/message-thread&id=${currentThreadId}&offset=${threadOffset}&limit=${MESSAGES_PER_PAGE}`)
        .then(res => res.json())
        .then(data => {
            if (!data.success) {
                container.innerHTML = '<div style="color: red; padding: 2rem; text-align: center;">Error loading messages</div>';
                return;
            }
            
            if (threadOffset === 0) {
                container.innerHTML = '';
                const msg = data.thread[0];
                document.getElementById('threadSubject').textContent = msg.subject;
                document.getElementById('threadSender').textContent = `From: ${msg.sender_name} • ${new Date(msg.created_at).toLocaleString()}`;
                
                markMessageAsRead(currentThreadId);
            }
            
            data.thread.forEach(msg => {
                container.innerHTML += createMessageHTML(msg);
            });
            
            container.scrollTop = container.scrollHeight;
        })
        .catch(err => console.error(err));
}

function createMessageHTML(msg) {
    const isOwn = msg.sender_id === parseInt('<?php echo $currentUser['id']; ?>');
    const time = new Date(msg.created_at).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
    
    let attachmentsHtml = '';
    if (msg.attachments && msg.attachments.length > 0) {
        msg.attachments.forEach(att => {
            const sizeKB = (att.file_size / 1024).toFixed(1);
            attachmentsHtml += `
                <a href="?page=api&endpoint=messages/download-attachment&message_id=${msg.id}&index=${msg.attachments.indexOf(att)}" 
                   target="_blank" style="display: inline-block; margin-top: 0.5rem; padding: 0.5rem; background: rgba(0,0,0,0.1); border-radius: 6px; font-size: 0.875rem; text-decoration: none; color: inherit;">
                    <i class="fas fa-file"></i> ${att.original_name} (${sizeKB}KB)
                </a>
            `;
        });
    }
    
    return `
        <div class="message-item ${isOwn ? 'own' : ''}">
            <div class="message-bubble ${isOwn ? 'sent' : 'received'}">
                ${!isOwn ? `<p style="font-weight: 600; font-size: 0.875rem; margin-bottom: 0.25rem; opacity: 0.9;">${msg.sender_name}</p>` : ''}
                <div>${msg.message}</div>
                ${attachmentsHtml}
                <div class="message-time">${time}</div>
            </div>
        </div>
    `;
}

function openReplyAttachmentInput() {
    document.getElementById('replyAttachmentInput').click();
}

function handleReplyAttachmentSelect() {
    const input = document.getElementById('replyAttachmentInput');
    replyFiles = Array.from(input.files);
    renderReplyAttachments();
}

function renderReplyAttachments() {
    const container = document.getElementById('replyAttachments');
    container.innerHTML = '';
    
    if (replyFiles.length === 0) {
        container.classList.add('hidden');
        return;
    }
    
    replyFiles.forEach((file, idx) => {
        container.innerHTML += `
            <div class="attachment-item">
                <span><i class="fas fa-file mr-1"></i>${file.name}</span>
                <button type="button" onclick="removeReplyAttachment(${idx})" class="hover:text-red-700">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `;
    });
    
    container.classList.remove('hidden');
}

function removeReplyAttachment(idx) {
    replyFiles.splice(idx, 1);
    renderReplyAttachments();
}

function sendReply() {
    const message = replyQuill.root.innerHTML;
    
    if (!message || message === '<br>') {
        Swal.fire('Error', 'Please enter a message', 'error');
        return;
    }
    
    const formData = new FormData();
    formData.append('parent_message_id', currentThreadId);
    formData.append('subject', 'Re: ' + document.getElementById('threadSubject').textContent);
    formData.append('message', message);
    
    replyFiles.forEach(file => formData.append('attachments[]', file));
    
    fetch('?page=api&endpoint=guards/send-reply', {
        method: 'POST',
        body: formData
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            replyQuill.setContents([]);
            replyFiles = [];
            document.getElementById('replyAttachments').innerHTML = '';
            document.getElementById('replyAttachments').classList.add('hidden');
            
            threadOffset = 0;
            loadThreadMessages();
            
            Swal.fire('Success', 'Reply sent', 'success');
        } else {
            Swal.fire('Error', data.error || 'Failed to send', 'error');
        }
    })
    .catch(err => {
        console.error(err);
        Swal.fire('Error', 'Failed to send reply', 'error');
    });
}

function closeThread() {
    document.getElementById('threadPanel').classList.remove('active');
    document.getElementById('emptyPanel').classList.remove('hidden');
    document.querySelectorAll('.conversation-item').forEach(el => {
        el.classList.remove('selected');
    });
    currentThreadId = null;
}

function goBackToList() {
    closeThread();
}

function markMessageAsRead(messageId) {
    fetch('?page=api&endpoint=guards/mark-message-read', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message_id: messageId })
    });
}
</script>

<?php require_once __DIR__ . '/../../layouts/footer.php'; ?>
