<?php
/**
 * Admin - Messages (Create/View)
 * Send and receive messages with clients, guards, and staff
 */

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

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

// Get current admin user
$user = $db->fetch("SELECT id, name FROM users WHERE id = ? AND role IN ('admin', 'manager')", [$_SESSION['user_id'] ?? 0]);
if (!$user) {
    header('Location: ?page=admin/dashboard');
    exit();
}

// Get recipients (clients, guards, managers, controllers)
$recipients = $db->fetchAll(
    "SELECT id, name, role FROM users WHERE role IN ('client', 'guard', 'manager', 'controller') AND active = 1 ORDER BY role DESC, name"
);

// Get messages (received)
$messages = $db->fetchAll(
    "SELECT m.*, u.name as sender_name
     FROM messages m
     JOIN users u ON m.sender_id = u.id
     WHERE m.recipient_id = ?
     ORDER BY m.created_at DESC
     LIMIT 50",
    [$_SESSION['user_id']]
);

// Get sent messages
$sentMessages = $db->fetchAll(
    "SELECT m.*, u.name as recipient_name
     FROM messages m
     JOIN users u ON m.recipient_id = u.id
     WHERE m.sender_id = ?
     ORDER BY m.created_at DESC
     LIMIT 50",
    [$_SESSION['user_id']]
);

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

<script>
// Tab switching
function switchMessageTab(tab) {
    document.getElementById('compose').classList.add('hidden');
    document.getElementById('inbox').classList.add('hidden');
    document.getElementById('sent').classList.add('hidden');
    document.getElementById(tab).classList.remove('hidden');
    
    document.querySelectorAll('.message-tab-btn').forEach(btn => {
        btn.classList.remove('bg-blue-600', 'text-white');
        btn.classList.add('text-gray-700', 'hover:bg-gray-100');
    });
    
    const activeBtn = document.querySelector('.message-tab-btn[data-tab="' + tab + '"]');
    if (activeBtn) {
        activeBtn.classList.add('bg-blue-600', 'text-white');
        activeBtn.classList.remove('text-gray-700', 'hover:bg-gray-100');
    }
}

// Store current message ID for reply
let currentMessageId = null;
let replyAttachments = [];
let replyQuill = null;
let threadOffset = 0;
let threadLimit = 10;
let threadTotal = 0;

function showMessageDetail(element, msg) {
    currentMessageId = msg.id;
    replyAttachments = [];
    threadOffset = 0;
    
    // Show modal
    document.getElementById('messageDetailModal').classList.remove('hidden');
    
    // Initialize Quill editor for reply (only once)
    if (!replyQuill) {
        replyQuill = new Quill('#replyQuillEditor', {
            theme: 'snow',
            placeholder: 'Type your reply...',
            modules: {
                toolbar: [
                    [{ 'header': [1, 2, false] }],
                    ['bold', 'italic', 'underline', 'strike'],
                    ['blockquote', 'code-block'],
                    [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                    [{ 'color': [] }, { 'background': [] }],
                    ['link'],
                    ['clean']
                ]
            }
        });
    } else {
        replyQuill.setContents([]);
    }
    
    // Reset reply form
    document.getElementById('replyAttachmentsPreview').innerHTML = '';
    document.getElementById('replyAttachmentsPreview').classList.add('hidden');
    
    // Load thread
    loadMessageThread();
    
    // Mark as read
    markMessageAsRead(msg.id);
}

function loadMessageThread() {
    const threadContainer = document.getElementById('messageThread');
    const loadingIndicator = document.getElementById('threadLoadingIndicator');
    
    loadingIndicator.classList.remove('hidden');
    
    fetch(`?page=api&endpoint=admin/message-thread&id=${currentMessageId}&limit=${threadLimit}&offset=${threadOffset}`)
        .then(res => res.json())
        .then(data => {
            loadingIndicator.classList.add('hidden');
            
            if (data.success) {
                threadTotal = data.total;
                
                // Clear thread if first load
                if (threadOffset === 0) {
                    threadContainer.innerHTML = '';
                    document.getElementById('modalSubject').textContent = data.thread[0]?.subject || 'Message';
                }
                
                // Add messages to thread
                data.thread.forEach((msg, index) => {
                    const bubble = createMessageBubble(msg);
                    threadContainer.appendChild(bubble);
                });
                
                // Show/hide load older button
                const loadOlderSection = document.getElementById('loadOlderSection');
                if (data.has_more) {
                    loadOlderSection.classList.remove('hidden');
                } else {
                    loadOlderSection.classList.add('hidden');
                }
                
                // Auto-scroll to bottom
                const contentArea = threadContainer.parentElement;
                contentArea.scrollTop = contentArea.scrollHeight;
            } else {
                Swal.fire('Error', data.error || 'Failed to load thread', 'error');
            }
        })
        .catch(err => {
            loadingIndicator.classList.add('hidden');
            console.error('Error loading thread:', err);
        });
}

function loadOlderMessages() {
    threadOffset += threadLimit;
    
    const loadOlderSection = document.getElementById('loadOlderSection');
    loadOlderSection.classList.add('hidden');
    
    fetch(`?page=api&endpoint=admin/message-thread&id=${currentMessageId}&limit=${threadLimit}&offset=${threadOffset}`)
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                const threadContainer = document.getElementById('messageThread');
                const contentArea = threadContainer.parentElement;
                const scrollHeightBefore = contentArea.scrollHeight;
                
                // Prepend messages to thread
                data.thread.reverse().forEach((msg) => {
                    const bubble = createMessageBubble(msg);
                    threadContainer.insertBefore(bubble, threadContainer.firstChild);
                });
                
                // Maintain scroll position
                contentArea.scrollTop = contentArea.scrollHeight - scrollHeightBefore;
                
                // Show/hide load older button
                if (data.has_more) {
                    loadOlderSection.classList.remove('hidden');
                }
            }
        })
        .catch(err => console.error('Error loading older messages:', err));
}

function createMessageBubble(msg) {
    const isOwn = msg.sender_id === parseInt(document.querySelector('[data-user-id]')?.dataset.userId || 0);
    const dateTime = new Date(msg.created_at).toLocaleString();
    
    const bubble = document.createElement('div');
    bubble.className = `flex ${isOwn ? 'justify-end' : 'justify-start'}`;
    
    let contentHtml = `<div class="text-gray-800 leading-relaxed">${msg.message}</div>`;
    
    // Add attachments if any
    if (msg.attachments && msg.attachments.length > 0) {
        contentHtml += `
            <div class="mt-4 pt-4 border-t border-gray-300">
                <p class="text-xs font-bold text-gray-700 mb-2 uppercase tracking-widest">
                    <i class="fas fa-paperclip mr-2"></i>Attachments
                </p>
                <div class="space-y-2">
        `;
        msg.attachments.forEach(att => {
            contentHtml += `
                <a href="${att.file_path}" target="_blank" class="flex items-center gap-2 text-blue-600 hover:text-blue-700 text-sm">
                    <i class="fas fa-download"></i>
                    <span>${att.original_name}</span>
                    <span class="text-xs text-gray-500">(${(att.file_size / 1024).toFixed(1)} KB)</span>
                </a>
            `;
        });
        contentHtml += `</div></div>`;
    }
    
    bubble.innerHTML = `
        <div class="max-w-2xl ${isOwn ? 'bg-blue-100 rounded-bl-xl' : 'bg-white rounded-br-xl border border-gray-200'} rounded-xl p-4 rounded-tl-none">
            <div class="flex items-center justify-between mb-2 pb-2 border-b border-gray-300">
                <span class="font-semibold ${isOwn ? 'text-blue-900' : 'text-gray-800'}">${msg.sender_name}</span>
                <span class="text-xs ${isOwn ? 'text-blue-700' : 'text-gray-600'}">${dateTime}</span>
            </div>
            ${contentHtml}
        </div>
    `;
    
    return bubble;
}

function markMessageAsRead(messageId) {
    fetch('?page=api&endpoint=admin/mark-message-read', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ message_id: messageId })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success && data.unread_count !== undefined) {
            const badge = document.getElementById('inboxBadge');
            if (badge) {
                badge.textContent = data.unread_count;
                if (data.unread_count === 0) {
                    badge.classList.add('hidden');
                }
            }
        }
    })
    .catch(err => console.error('Error marking message as read:', err));
}

function closeMessageDetail() {
    document.getElementById('messageDetailModal').classList.add('hidden');
    currentMessageId = null;
    replyAttachments = [];
}

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

function handleReplyAttachmentSelect() {
    const input = document.getElementById('replyAttachmentInput');
    const newFiles = Array.from(input.files);
    
    if (replyAttachments.length + newFiles.length > 5) {
        Swal.fire('Error', 'Maximum 5 attachments allowed', 'error');
        return;
    }
    
    newFiles.forEach(file => {
        if (file.size > 5 * 1024 * 1024) {
            Swal.fire('Error', `File ${file.name} exceeds 5MB limit`, 'error');
            return;
        }
        replyAttachments.push(file);
        addReplyAttachmentPreview(file);
    });
    
    input.value = '';
}

function addReplyAttachmentPreview(file) {
    const preview = document.getElementById('replyAttachmentsPreview');
    preview.classList.remove('hidden');
    
    const item = document.createElement('div');
    item.className = 'flex items-center justify-between p-3 bg-blue-50 border border-blue-200 rounded-lg text-sm';
    item.innerHTML = `
        <span class="flex items-center gap-2 flex-1 min-w-0">
            <i class="fas fa-file text-blue-500 flex-shrink-0"></i>
            <span class="truncate text-gray-700 font-medium">${file.name}</span>
            <span class="text-xs text-gray-500 flex-shrink-0">(${(file.size / 1024).toFixed(1)} KB)</span>
        </span>
        <button type="button" class="ml-2 text-red-500 hover:text-red-700 flex-shrink-0" onclick="removeReplyAttachment(this)">
            <i class="fas fa-trash-alt"></i>
        </button>
    `;
    preview.appendChild(item);
}

function removeReplyAttachment(btn) {
    const items = document.getElementById('replyAttachmentsPreview').querySelectorAll('div');
    const index = Array.from(items).indexOf(btn.parentElement);
    replyAttachments.splice(index, 1);
    btn.parentElement.remove();
    
    if (replyAttachments.length === 0) {
        document.getElementById('replyAttachmentsPreview').classList.add('hidden');
    }
}

async function sendReplyMessage() {
    if (!replyQuill) {
        Swal.fire('Error', 'Editor not initialized', 'error');
        return;
    }
    
    const replyText = replyQuill.root.innerHTML.trim();
    
    if ((!replyText || replyText === '<p><br></p>') && replyAttachments.length === 0) {
        Swal.fire('Error', 'Please enter a message or attach a file', 'error');
        return;
    }
    
    if (!currentMessageId) {
        Swal.fire('Error', 'No message selected', 'error');
        return;
    }
    
    try {
        const formData = new FormData();
        formData.append('parent_message_id', currentMessageId);
        formData.append('subject', 'Re: ' + document.getElementById('modalSubject').textContent);
        formData.append('message', replyText);
        
        replyAttachments.forEach((file, index) => {
            formData.append('attachments[]', file);
        });
        
        const response = await fetch('?page=api&endpoint=admin/send-reply', {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        
        if (result.success) {
            Swal.fire('Success', 'Reply sent successfully', 'success').then(() => {
                closeMessageDetail();
                setTimeout(() => location.reload(), 500);
            });
        } else {
            Swal.fire('Error', result.message || 'Failed to send reply', 'error');
        }
    } catch (error) {
        console.error('Error:', error);
        Swal.fire('Error', 'An error occurred while sending the reply', 'error');
    }
}
</script>

<div class="container mx-auto px-4 py-8 max-w-7xl" data-user-id="<?php echo $_SESSION['user_id']; ?>">
    <!-- Header -->
    <div class="mb-8">
        <div class="bg-gradient-to-r from-blue-600 to-blue-700 rounded-lg p-8 text-white shadow-lg">
            <h1 class="text-4xl font-bold">
                <i class="fas fa-envelope mr-3"></i><?php echo Language::get('messages'); ?>
            </h1>
            <p class="text-blue-100 mt-2">Send and receive messages with clients, guards, and staff</p>
        </div>
    </div>

    <!-- Tabs -->
    <div class="flex gap-2 mb-6 bg-white rounded-lg shadow border border-gray-200 p-2 overflow-x-auto">
        <button data-tab="compose" class="message-tab-btn px-6 py-3 font-semibold bg-blue-600 text-white rounded-lg whitespace-nowrap transition" onclick="switchMessageTab('compose')">
            <i class="fas fa-pen mr-2"></i><?php echo Language::get('compose'); ?>
        </button>
        <button data-tab="inbox" class="message-tab-btn px-6 py-3 font-semibold text-gray-700 hover:bg-gray-100 rounded-lg whitespace-nowrap transition" onclick="switchMessageTab('inbox')">
            <i class="fas fa-inbox mr-2"></i><?php echo Language::get('inbox'); ?> <span id="inboxBadge" class="ml-2 text-sm bg-red-500 text-white rounded-full px-3 py-1"><?php echo count(array_filter($messages, fn($m) => !$m['is_read'])); ?></span>
        </button>
        <button data-tab="sent" class="message-tab-btn px-6 py-3 font-semibold text-gray-700 hover:bg-gray-100 rounded-lg whitespace-nowrap transition" onclick="switchMessageTab('sent')">
            <i class="fas fa-paper-plane mr-2"></i><?php echo Language::get('sent'); ?>
        </button>
    </div>

    <!-- Compose Tab -->
    <div id="compose" class="block">
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
            <div class="lg:col-span-1">
                <div class="bg-white rounded-xl shadow-lg border border-gray-200 p-7 sticky top-20">
                    <h2 class="text-2xl font-bold text-gray-800 mb-6 flex items-center gap-2">
                        <i class="fas fa-pen text-blue-600"></i>
                        <?php echo Language::get('send_message'); ?>
                    </h2>
                    
                    <form id="messageForm" class="space-y-5">
                        <!-- Recipient -->
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2 uppercase tracking-wide"><?php echo Language::get('recipient'); ?> *</label>
                            <select id="recipientId" name="recipient_id" required class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition font-medium">
                                <option value="">Select a recipient...</option>
                                <?php foreach ($recipients as $recipient): ?>
                                    <option value="<?php echo $recipient['id']; ?>">
                                        <?php echo htmlspecialchars($recipient['name']); ?> 
                                        (<?php echo ucfirst($recipient['role']); ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <!-- Subject -->
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2 uppercase tracking-wide"><?php echo Language::get('subject'); ?> *</label>
                            <input type="text" id="subject" name="subject" required class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition font-medium" placeholder="Enter message subject...">
                        </div>

                        <!-- Message with Quill Editor -->
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2 uppercase tracking-wide"><?php echo Language::get('message'); ?> *</label>
                            <div id="messageEditor" class="bg-white border-2 border-gray-300 rounded-lg overflow-hidden focus-within:border-blue-500 focus-within:ring-2 focus-within:ring-blue-200 transition" style="height: 250px;"></div>
                        </div>

                        <!-- Attachments -->
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2 uppercase tracking-wide"><?php echo Language::get('attachments'); ?></label>
                            <div id="dragDropZone" class="border-3 border-dashed border-gray-300 rounded-lg p-6 text-center cursor-pointer hover:border-blue-500 hover:bg-blue-50 transition bg-gradient-to-br from-gray-50 to-white" ondrop="handleDrop(event)" ondragover="event.preventDefault(); this.style.borderColor='#3b82f6'; this.style.backgroundColor='#f0f9ff';" ondragleave="this.style.borderColor='#d1d5db'; this.style.backgroundColor='transparent';" onclick="document.getElementById('attachmentInput').click()">
                                <i class="fas fa-cloud-upload-alt text-4xl text-blue-400 mb-3"></i>
                                <p class="text-sm font-semibold text-gray-700">Click to upload or drag and drop</p>
                                <p class="text-xs text-gray-500 mt-1">Max 5 files, 5MB each (PDF, DOC, XLS, JPG, PNG, etc.)</p>
                            </div>
                            <input type="file" id="attachmentInput" multiple accept=".pdf,.doc,.docx,.xls,.xlsx,.txt,.jpg,.jpeg,.png,.gif" style="display:none;" onchange="handleFileSelect(event)">
                            <div id="fileList" class="mt-4 space-y-2"></div>
                        </div>

                        <!-- Submit -->
                        <button type="button" onclick="submitMessage(event)" class="w-full px-6 py-4 bg-gradient-to-r from-blue-600 to-blue-700 text-white rounded-lg hover:from-blue-700 hover:to-blue-800 font-bold transition shadow-lg text-lg uppercase tracking-wide">
                            <i class="fas fa-paper-plane mr-3"></i><?php echo Language::get('send_message'); ?>
                        </button>
                    </form>
                </div>
            </div>

            <div class="lg:col-span-1">
                <div class="bg-gradient-to-br from-gray-50 to-white rounded-xl border-2 border-dashed border-gray-300 p-8 text-center">
                    <i class="fas fa-inbox text-5xl text-gray-300 mb-4"></i>
                    <p class="text-gray-600 font-medium text-lg">Select compose to send a new message</p>
                    <p class="text-sm text-gray-500 mt-2">Your conversation history will appear here</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Inbox Tab -->
    <div id="inbox" class="hidden">
        <div class="bg-white rounded-xl shadow-lg border border-gray-200 overflow-hidden">
            <div class="px-6 py-5 border-b border-gray-200 bg-gradient-to-r from-gray-50 to-gray-100">
                <h2 class="text-xl font-bold text-gray-800 flex items-center gap-2">
                    <i class="fas fa-inbox text-blue-600"></i>
                    <?php echo Language::get('inbox'); ?>
                </h2>
            </div>

            <?php if (!empty($messages)): ?>
                <div class="divide-y divide-gray-100">
                    <?php foreach ($messages as $msg): 
                        $attachments = !empty($msg['attachments']) ? json_decode($msg['attachments'], true) : [];
                        $messagePreview = strip_tags($msg['message']);
                        $messagePreview = substr($messagePreview, 0, 80) . (strlen($messagePreview) > 80 ? '...' : '');
                        $isUnread = $msg['is_read'] == 0;
                    ?>
                        <div class="px-6 py-4 hover:bg-blue-50 transition cursor-pointer border-l-4 <?php echo $isUnread ? 'border-l-blue-600 bg-blue-50' : 'border-l-transparent'; ?>" onclick="showMessageDetail(this, <?php echo htmlspecialchars(json_encode($msg)); ?>)">
                            <div class="flex items-start justify-between gap-4">
                                <div class="flex-1 min-w-0">
                                    <div class="flex items-center gap-2 mb-1">
                                        <p class="font-bold text-gray-900 <?php echo $isUnread ? 'text-lg' : ''; ?>"><?php echo htmlspecialchars($msg['sender_name']); ?></p>
                                        <?php if ($isUnread): ?>
                                            <span class="inline-block w-2 h-2 bg-blue-600 rounded-full animate-pulse"></span>
                                        <?php endif; ?>
                                    </div>
                                    <p class="text-gray-700 font-semibold truncate"><?php echo htmlspecialchars($msg['subject']); ?></p>
                                    <div class="flex items-center gap-2 mt-2">
                                        <p class="text-sm text-gray-600 line-clamp-1"><?php echo htmlspecialchars($messagePreview); ?></p>
                                        <?php if (!empty($attachments)): ?>
                                            <span class="inline-flex items-center gap-1 px-2.5 py-1 bg-blue-100 text-blue-700 rounded-full text-xs font-semibold flex-shrink-0 whitespace-nowrap">
                                                <i class="fas fa-paperclip"></i><?php echo count($attachments); ?>
                                            </span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div class="text-right ml-4 flex-shrink-0 whitespace-nowrap">
                                    <p class="text-xs text-gray-500 font-medium"><?php echo date('M d', strtotime($msg['created_at'])); ?></p>
                                    <p class="text-xs text-gray-500"><?php echo date('H:i', strtotime($msg['created_at'])); ?></p>
                                    <?php if ($isUnread): ?>
                                        <div class="mt-2 w-2 h-2 bg-blue-600 rounded-full mx-auto"></div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <div class="p-12 text-center text-gray-500">
                    <i class="fas fa-inbox text-5xl mb-4 opacity-30"></i>
                    <p class="font-medium"><?php echo Language::get('no_messages'); ?></p>
                    <p class="text-sm mt-2">You don't have any received messages yet</p>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Sent Tab -->
    <div id="sent" class="hidden">
        <div class="bg-white rounded-xl shadow-lg border border-gray-200 overflow-hidden">
            <div class="px-6 py-5 border-b border-gray-200 bg-gradient-to-r from-gray-50 to-gray-100">
                <h2 class="text-xl font-bold text-gray-800 flex items-center gap-2">
                    <i class="fas fa-paper-plane text-green-600"></i>
                    <?php echo Language::get('sent'); ?>
                </h2>
            </div>

            <?php if (!empty($sentMessages)): ?>
                <div class="divide-y divide-gray-100">
                    <?php foreach ($sentMessages as $msg): 
                        $attachments = !empty($msg['attachments']) ? json_decode($msg['attachments'], true) : [];
                        $messagePreview = strip_tags($msg['message']);
                        $messagePreview = substr($messagePreview, 0, 80) . (strlen($messagePreview) > 80 ? '...' : '');
                    ?>
                        <div class="px-6 py-4 hover:bg-green-50 transition cursor-pointer border-l-4 border-l-transparent" onclick="showMessageDetail(this, <?php echo htmlspecialchars(json_encode($msg)); ?>)">
                            <div class="flex items-start justify-between gap-4">
                                <div class="flex-1 min-w-0">
                                    <div class="flex items-center gap-2 mb-1">
                                        <p class="font-bold text-gray-900">To: <?php echo htmlspecialchars($msg['recipient_name']); ?></p>
                                    </div>
                                    <p class="text-gray-700 font-semibold truncate"><?php echo htmlspecialchars($msg['subject']); ?></p>
                                    <div class="flex items-center gap-2 mt-2">
                                        <p class="text-sm text-gray-600 line-clamp-1"><?php echo htmlspecialchars($messagePreview); ?></p>
                                        <?php if (!empty($attachments)): ?>
                                            <span class="inline-flex items-center gap-1 px-2.5 py-1 bg-green-100 text-green-700 rounded-full text-xs font-semibold flex-shrink-0 whitespace-nowrap">
                                                <i class="fas fa-paperclip"></i><?php echo count($attachments); ?>
                                            </span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div class="text-right ml-4 flex-shrink-0 whitespace-nowrap">
                                    <p class="text-xs text-gray-500 font-medium"><?php echo date('M d', strtotime($msg['created_at'])); ?></p>
                                    <p class="text-xs text-gray-500"><?php echo date('H:i', strtotime($msg['created_at'])); ?></p>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <div class="p-12 text-center text-gray-500">
                    <i class="fas fa-paper-plane text-5xl mb-4 opacity-30"></i>
                    <p class="font-medium"><?php echo Language::get('no_messages'); ?></p>
                    <p class="text-sm mt-2">You haven't sent any messages yet</p>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Message Detail Modal -->
<div id="messageDetailModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-xl shadow-2xl max-w-4xl w-full max-h-[90vh] overflow-hidden flex flex-col">
        <!-- Header -->
        <div class="sticky top-0 bg-gradient-to-r from-blue-600 to-blue-700 text-white p-6 flex items-center justify-between">
            <div class="flex-1">
                <h3 id="modalSubject" class="text-2xl font-bold"></h3>
                <p id="modalSender" class="text-blue-100 text-sm mt-2"></p>
            </div>
            <button onclick="closeMessageDetail()" class="text-white hover:bg-blue-800 rounded-full p-3 transition">
                <i class="fas fa-times text-2xl"></i>
            </button>
        </div>

        <!-- Message Content -->
        <div class="flex-1 overflow-y-auto p-8 space-y-4 bg-gray-50">
            <!-- Load Older Messages Button -->
            <div id="loadOlderSection" class="hidden text-center">
                <button onclick="loadOlderMessages()" class="px-6 py-2 text-sm font-semibold text-blue-600 hover:text-blue-700 border border-blue-300 rounded-full hover:bg-blue-50 transition">
                    <i class="fas fa-arrow-up mr-2"></i>Load Older Messages
                </button>
            </div>

            <!-- Message Thread Container -->
            <div id="messageThread" class="space-y-4"></div>

            <!-- Loading Indicator -->
            <div id="threadLoadingIndicator" class="hidden text-center py-4">
                <i class="fas fa-spinner fa-spin text-blue-600 text-2xl"></i>
            </div>
        </div>

        <!-- Reply Section -->
        <div class="border-t bg-gray-50 p-8 max-h-96 overflow-y-auto">
            <div class="space-y-4">
                <label class="block text-sm font-bold text-gray-800 uppercase tracking-wide">
                    <i class="fas fa-reply mr-2 text-blue-600"></i>Reply to Message
                </label>
                
                <!-- Quill Editor for Reply -->
                <div id="replyQuillEditor" class="bg-white rounded-lg border-2 border-gray-300 focus-within:border-blue-500 transition" style="height: 200px;"></div>
                
                <!-- Reply Actions -->
                <div class="flex items-center justify-between pt-4">
                    <button onclick="openReplyAttachmentInput()" class="inline-flex items-center gap-2 text-gray-600 hover:text-blue-600 transition font-semibold">
                        <i class="fas fa-paperclip text-lg"></i>
                        <span>Add Attachments</span>
                    </button>
                    <div class="flex gap-3">
                        <button onclick="closeMessageDetail()" class="px-6 py-2 text-gray-700 bg-white border-2 border-gray-300 rounded-lg hover:bg-gray-100 transition font-semibold">
                            Cancel
                        </button>
                        <button onclick="sendReplyMessage()" class="px-6 py-2 text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition font-semibold flex items-center gap-2">
                            <i class="fas fa-paper-plane"></i>
                            Send Reply
                        </button>
                    </div>
                </div>
                
                <!-- Reply Attachments Display -->
                <div id="replyAttachmentsPreview" class="hidden space-y-2 mt-4"></div>
                <input id="replyAttachmentInput" type="file" multiple accept=".pdf,.doc,.docx,.xls,.xlsx,.txt,.jpg,.jpeg,.png,.gif" style="display: none;" onchange="handleReplyAttachmentSelect()">
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
// Initialize Quill editor
const quill = new Quill('#messageEditor', {
    theme: 'snow',
    placeholder: 'Type your message...',
    modules: {
        toolbar: [
            [{ 'header': [1, 2, false] }],
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ 'list': 'ordered'}, { 'list': 'bullet' }],
            [{ 'color': [] }, { 'background': [] }],
            ['link'],
            ['clean']
        ]
    }
});

// File management
const files = [];

function handleFileSelect(event) {
    const newFiles = Array.from(event.target.files);
    newFiles.forEach(file => {
        if (file.size <= 5 * 1024 * 1024 && files.length < 5) {
            files.push(file);
            addFileToList(file);
        } else if (file.size > 5 * 1024 * 1024) {
            Swal.fire('Error', file.name + ' exceeds 5MB limit', 'error');
        }
    });
}

function handleDrop(e) {
    e.preventDefault();
    const items = e.dataTransfer.items;
    if (items) {
        Array.from(items).forEach(item => {
            if (item.kind === 'file') {
                const file = item.getAsFile();
                if (files.length < 5 && file.size <= 5 * 1024 * 1024) {
                    files.push(file);
                    addFileToList(file);
                }
            }
        });
    }
}

function addFileToList(file) {
    const fileList = document.getElementById('fileList');
    const item = document.createElement('div');
    item.className = 'flex items-center justify-between p-3 bg-blue-50 border border-blue-200 rounded-lg text-sm';
    const fileIndex = files.indexOf(file);
    item.innerHTML = `
        <span class="flex items-center gap-2 flex-1 min-w-0">
            <i class="fas fa-file text-blue-500 flex-shrink-0"></i>
            <span class="truncate text-gray-700 font-medium">${file.name}</span>
            <span class="text-xs text-gray-500 flex-shrink-0">(${(file.size / 1024).toFixed(1)} KB)</span>
        </span>
        <button type="button" class="ml-2 text-red-500 hover:text-red-700 flex-shrink-0" onclick="removeFile(${fileIndex})">
            <i class="fas fa-trash-alt"></i>
        </button>
    `;
    fileList.appendChild(item);
}

function removeFile(index) {
    files.splice(index, 1);
    const fileList = document.getElementById('fileList');
    fileList.innerHTML = '';
    files.forEach((file, idx) => {
        const item = document.createElement('div');
        item.className = 'flex items-center justify-between p-3 bg-blue-50 border border-blue-200 rounded-lg text-sm';
        item.innerHTML = `
            <span class="flex items-center gap-2 flex-1 min-w-0">
                <i class="fas fa-file text-blue-500 flex-shrink-0"></i>
                <span class="truncate text-gray-700 font-medium">${file.name}</span>
                <span class="text-xs text-gray-500 flex-shrink-0">(${(file.size / 1024).toFixed(1)} KB)</span>
            </span>
            <button type="button" class="ml-2 text-red-500 hover:text-red-700 flex-shrink-0" onclick="removeFile(${idx})">
                <i class="fas fa-trash-alt"></i>
            </button>
        `;
        fileList.appendChild(item);
    });
}

function submitMessage(event) {
    event.preventDefault();
    
    const recipientId = document.getElementById('recipientId').value;
    const subject = document.getElementById('subject').value;
    const messageContent = quill.root.innerHTML.trim();
    
    if (!recipientId) {
        Swal.fire('Error', 'Please select a recipient', 'error');
        return;
    }
    if (!subject.trim()) {
        Swal.fire('Error', 'Please enter a subject', 'error');
        return;
    }
    if (!messageContent || messageContent === '<p><br></p>') {
        Swal.fire('Error', 'Please enter a message', 'error');
        return;
    }

    if (files.length > 5) {
        Swal.fire('Error', 'Maximum 5 files allowed', 'error');
        return;
    }
    
    const formData = new FormData();
    formData.append('recipient_id', recipientId);
    formData.append('subject', subject);
    formData.append('message', messageContent);
    formData.append('priority', 'normal');

    files.forEach((file) => {
        formData.append('attachments[]', file);
    });

    const btn = event.target;
    const originalText = btn.innerHTML;
    btn.disabled = true;
    btn.classList.add('opacity-75', 'cursor-not-allowed', 'animate-pulse');
    btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Sending...';

    fetch('?page=api&endpoint=admin/send-message', {
        method: 'POST',
        body: formData
    })
    .then(r => r.json())
    .then(data => {
        btn.classList.remove('opacity-75', 'cursor-not-allowed', 'animate-pulse');
        if (data.success) {
            btn.innerHTML = '<i class="fas fa-check mr-2"></i>Sent!';
            btn.classList.add('bg-green-500', 'hover:bg-green-600');
            setTimeout(() => {
                Swal.fire('Success', 'Message sent successfully', 'success').then(() => {
                    document.getElementById('recipientId').value = '';
                    document.getElementById('subject').value = '';
                    quill.setContents([]);
                    files.length = 0;
                    document.getElementById('fileList').innerHTML = '';
                    btn.disabled = false;
                    btn.innerHTML = originalText;
                    btn.classList.remove('bg-green-500', 'hover:bg-green-600');
                    setTimeout(() => {
                        location.reload();
                    }, 500);
                });
            }, 500);
        } else {
            btn.disabled = false;
            btn.innerHTML = originalText;
            Swal.fire('Error', data.error || 'Failed to send message', 'error');
        }
    })
    .catch(err => {
        console.error('Error:', err);
        btn.disabled = false;
        btn.innerHTML = originalText;
        btn.classList.remove('opacity-75', 'cursor-not-allowed', 'animate-pulse');
        Swal.fire('Error', 'Network error sending message', 'error');
    });
}

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

