<?php
/**
 * Enhanced Messages/Chat Interface with Real-time Updates
 * OBGYN Research & Collaboration Platform
 */

require_once '../config/config.php';

requireLogin();
if (!isResearcher()) {
    redirect(SITE_URL . '/index.php');
}

$pageTitle = 'Messages';
$userId = getCurrentUserId();

include '../templates/header.php';
?>

<div class="container-fluid">
    <div class="row">
        <?php include 'sidebar.php'; ?>

        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2">
                    <i class="fas fa-envelope"></i> Messages
                    <span id="total-unread-badge" class="badge bg-danger ms-2" style="display: none;">0</span>
                </h1>
                <div class="btn-toolbar">
                    <button id="new-chat-btn" class="btn btn-primary">
                        <i class="fas fa-plus"></i> New Message
                    </button>
                    <button id="refresh-btn" class="btn btn-outline-secondary ms-2">
                        <i class="fas fa-sync-alt"></i> Refresh
                    </button>
                </div>
            </div>

            <!-- Success/Error Messages -->
            <div id="alert-container"></div>

            <div class="row">
                <!-- Chat List -->
                <div class="col-md-4 col-lg-3">
                    <div class="card shadow">
                        <div class="card-header">
                            <h6 class="mb-0">Conversations</h6>
                        </div>
                        <div id="chat-list" class="list-group list-group-flush" style="max-height: 600px; overflow-y: auto;">
                            <div class="text-center py-4">
                                <div class="spinner-border text-primary" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                                <p class="mt-3 small">Loading conversations...</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Chat Messages -->
                <div class="col-md-8 col-lg-9">
                    <div id="chat-container" class="card shadow">
                        <div class="card-body text-center py-5">
                            <i class="fas fa-comments fa-4x text-muted mb-3"></i>
                            <h5>Select a conversation</h5>
                            <p class="text-muted">Choose a conversation from the list or start a new one</p>
                            <button id="start-new-chat-btn" class="btn btn-primary">
                                <i class="fas fa-plus"></i> Start New Conversation
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<!-- New Chat Modal -->
<div class="modal fade" id="newChatModal" tabindex="-1">
    <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">Select Researcher</label>
                    <select id="researcher-select" class="form-select">
                        <option value="">Loading researchers...</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Message</label>
                    <textarea id="initial-message" class="form-control" rows="3" placeholder="Type your first message..."></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button id="send-new-message-btn" type="button" class="btn btn-primary">Send Message</button>
            </div>
        </div>
    </div>
</div>

<script>
// Chat Manager
const ChatManager = {
    currentRoomId: null,
    currentRoomName: '',
    chatRooms: [],
    messages: [],
    autoRefreshInterval: null,
    messageRefreshInterval: null,
    
    init() {
        this.loadChatRooms();
        this.setupEventListeners();
        this.startAutoRefresh();
    },
    
    setupEventListeners() {
        // New chat buttons
        document.getElementById('new-chat-btn').addEventListener('click', () => {
            this.showNewChatModal();
        });
        
        document.getElementById('start-new-chat-btn').addEventListener('click', () => {
            this.showNewChatModal();
        });
        
        // Send new message
        document.getElementById('send-new-message-btn').addEventListener('click', () => {
            this.sendNewMessage();
        });
        
        // Refresh button
        document.getElementById('refresh-btn').addEventListener('click', () => {
            this.loadChatRooms();
        });
        
        // Enter key in message input
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                const messageInput = document.getElementById('message-input');
                if (messageInput && messageInput === document.activeElement) {
                    e.preventDefault();
                    this.sendMessage();
                }
            }
        });
    },
    
    async loadChatRooms() {
        try {
            const response = await fetch('<?php echo SITE_URL; ?>/api/chat.php?action=get_rooms');
            const data = await response.json();
            
            if (data.success) {
                this.chatRooms = data.rooms || [];
                this.renderChatList();
                this.updateUnreadBadge();
            } else {
                this.showAlert('Error loading conversations', 'danger');
            }
        } catch (error) {
            console.error('Error:', error);
            this.showAlert('Failed to load conversations', 'danger');
        }
    },
    
    renderChatList() {
        const container = document.getElementById('chat-list');
        
        if (this.chatRooms.length === 0) {
            container.innerHTML = `
                <div class="list-group-item text-center text-muted py-4">
                    <i class="fas fa-inbox fa-2x mb-2"></i>
                    <p class="mb-0 small">No conversations yet</p>
                    <button class="btn btn-sm btn-primary mt-2" onclick="ChatManager.showNewChatModal()">
                        <i class="fas fa-plus"></i> Start One
                    </button>
                </div>
            `;
            return;
        }
        
        const html = this.chatRooms.map(room => `
            <a href="#" class="list-group-item list-group-item-action ${this.currentRoomId == room.id ? 'active' : ''}"
               onclick="ChatManager.selectRoom(${room.id}, '${this.escapeHtml(room.name || 'Chat')}')">
                <div class="d-flex w-100 justify-content-between">
                    <h6 class="mb-1">
                        ${this.escapeHtml(room.name || 'Chat')}
                        ${room.unread_count > 0 ? `<span class="badge bg-danger ms-2">${room.unread_count}</span>` : ''}
                    </h6>
                    <small class="text-muted">${room.last_message_time ? this.timeAgo(room.last_message_time) : ''}</small>
                </div>
                <p class="mb-0 small text-truncate">
                    ${this.escapeHtml(room.last_message || 'No messages')}
                </p>
            </a>
        `).join('');
        
        container.innerHTML = html;
    },
    
    updateUnreadBadge() {
        const totalUnread = this.chatRooms.reduce((sum, room) => sum + (room.unread_count || 0), 0);
        const badge = document.getElementById('total-unread-badge');
        
        if (totalUnread > 0) {
            badge.textContent = totalUnread;
            badge.style.display = 'inline-block';
        } else {
            badge.style.display = 'none';
        }
    },
    
    async selectRoom(roomId, roomName) {
        this.currentRoomId = roomId;
        this.currentRoomName = roomName;
        
        // Update active state
        document.querySelectorAll('#chat-list .list-group-item').forEach(item => {
            item.classList.remove('active');
        });
        event.target.closest('.list-group-item').classList.add('active');
        
        // Load messages
        await this.loadMessages();
        
        // Start message auto-refresh
        this.startMessageRefresh();
    },
    
    async loadMessages() {
        if (!this.currentRoomId) return;
        
        try {
            const response = await fetch(`<?php echo SITE_URL; ?>/api/chat.php?action=get_messages&room_id=${this.currentRoomId}&limit=100`);
            const data = await response.json();
            
            if (data.success) {
                this.messages = data.messages || [];
                this.renderChat();
                
                // Mark as read
                await this.markRoomAsRead();
            } else {
                this.showAlert('Error loading messages', 'danger');
            }
        } catch (error) {
            console.error('Error:', error);
            this.showAlert('Failed to load messages', 'danger');
        }
    },
    
    renderChat() {
        const container = document.getElementById('chat-container');
        
        if (!this.currentRoomId) {
            container.innerHTML = `
                <div class="card-body text-center py-5">
                    <i class="fas fa-comments fa-4x text-muted mb-3"></i>
                    <h5>Select a conversation</h5>
                    <p class="text-muted">Choose a conversation from the list or start a new one</p>
                    <button class="btn btn-primary" onclick="ChatManager.showNewChatModal()">
                        <i class="fas fa-plus"></i> Start New Conversation
                    </button>
                </div>
            `;
            return;
        }
        
        const messagesHtml = this.messages.length === 0 ? `
            <div class="text-center text-muted py-5">
                <i class="fas fa-comments fa-3x mb-3"></i>
                <p>No messages yet. Start the conversation!</p>
            </div>
        ` : this.messages.map(msg => `
            <div class="mb-3 ${msg.sender_id == <?php echo $userId; ?> ? 'text-end' : ''}">
                <div class="d-inline-block" style="max-width: 70%;">
                    ${msg.sender_id != <?php echo $userId; ?> ? `
                        <small class="text-muted d-block mb-1">
                            ${this.escapeHtml(msg.sender_name)}
                        </small>
                    ` : ''}
                    <div class="p-3 rounded ${msg.sender_id == <?php echo $userId; ?> ? 'bg-primary text-white' : 'bg-light'}">
                        ${this.escapeHtml(msg.message).replace(/\n/g, '<br>')}
                    </div>
                    <small class="text-muted d-block mt-1">
                        ${this.formatTime(msg.created_at)}
                    </small>
                </div>
            </div>
        `).join('');
        
        container.innerHTML = `
            <div class="card-header d-flex justify-content-between align-items-center">
                <h6 class="mb-0">${this.escapeHtml(this.currentRoomName)}</h6>
                <div class="btn-group">
                    <button class="btn btn-sm btn-outline-secondary" onclick="ChatManager.showRoomInfo()">
                        <i class="fas fa-info-circle"></i>
                    </button>
                    <button class="btn btn-sm btn-outline-danger" onclick="ChatManager.leaveRoom()">
                        <i class="fas fa-sign-out-alt"></i>
                    </button>
                </div>
            </div>
            <div class="card-body" style="height: 500px; overflow-y: auto;" id="messageContainer">
                ${messagesHtml}
            </div>
            <div class="card-footer">
                <div class="d-flex gap-2">
                    <input type="text" id="message-input" class="form-control" placeholder="Type your message..." maxlength="1000">
                    <button id="send-btn" class="btn btn-primary" onclick="ChatManager.sendMessage()">
                        <i class="fas fa-paper-plane"></i> Send
                    </button>
                </div>
            </div>
        `;
        
        // Scroll to bottom
        this.scrollToBottom();
        
        // Focus input
        document.getElementById('message-input').focus();
    },
    
    async sendMessage() {
        const input = document.getElementById('message-input');
        const message = input.value.trim();
        
        if (!message || !this.currentRoomId) return;
        
        try {
            const response = await fetch('<?php echo SITE_URL; ?>/api/chat.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    action: 'send_message',
                    room_id: this.currentRoomId,
                    message: message
                })
            });
            
            const data = await response.json();
            
            if (data.success) {
                input.value = '';
                await this.loadMessages(); // Refresh messages
            } else {
                this.showAlert('Failed to send message', 'danger');
            }
        } catch (error) {
            console.error('Error:', error);
            this.showAlert('Failed to send message', 'danger');
        }
    },
    
    async markRoomAsRead() {
        if (!this.currentRoomId) return;
        
        try {
            await fetch('<?php echo SITE_URL; ?>/api/chat.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    action: 'mark_read',
                    room_id: this.currentRoomId
                })
            });
            
            // Update local data
            this.chatRooms.forEach(room => {
                if (room.id == this.currentRoomId) {
                    room.unread_count = 0;
                }
            });
            this.renderChatList();
            this.updateUnreadBadge();
        } catch (error) {
            console.error('Error marking as read:', error);
        }
    },
    
    showNewChatModal() {
        const modal = new bootstrap.Modal(document.getElementById('newChatModal'));
        modal.show();
        this.loadResearchers();
    },
    
    async loadResearchers() {
        try {
            const response = await fetch('<?php echo SITE_URL; ?>/api/search.php?q=&type=researchers&limit=50');
            const data = await response.json();
            
            const select = document.getElementById('researcher-select');
            if (data.success && data.results) {
                select.innerHTML = '<option value="">Select a researcher...</option>' +
                    data.results.map(user => 
                        `<option value="${user.id}">${this.escapeHtml(user.first_name + ' ' + user.last_name)}</option>`
                    ).join('');
            } else {
                select.innerHTML = '<option value="">No researchers found</option>';
            }
        } catch (error) {
            console.error('Error:', error);
            document.getElementById('researcher-select').innerHTML = '<option value="">Error loading researchers</option>';
        }
    },
    
    async sendNewMessage() {
        const researcherId = document.getElementById('researcher-select').value;
        const message = document.getElementById('initial-message').value.trim();
        
        if (!researcherId || !message) {
            this.showAlert('Please select a researcher and enter a message', 'warning');
            return;
        }
        
        try {
            const response = await fetch('<?php echo SITE_URL; ?>/api/chat.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    action: 'start_conversation',
                    user_id: researcherId,
                    message: message
                })
            });
            
            const data = await response.json();
            
            if (data.success) {
                bootstrap.Modal.getInstance(document.getElementById('newChatModal')).hide();
                document.getElementById('initial-message').value = '';
                this.showAlert('Message sent successfully!', 'success');
                this.loadChatRooms(); // Refresh chat list
            } else {
                this.showAlert(data.message || 'Failed to send message', 'danger');
            }
        } catch (error) {
            console.error('Error:', error);
            this.showAlert('Failed to send message', 'danger');
        }
    },
    
    startAutoRefresh() {
        // Refresh chat list every 30 seconds
        this.autoRefreshInterval = setInterval(() => {
            this.loadChatRooms();
        }, 30000);
    },
    
    startMessageRefresh() {
        // Stop previous interval
        if (this.messageRefreshInterval) {
            clearInterval(this.messageRefreshInterval);
        }
        
        // Refresh messages every 10 seconds when a room is selected
        this.messageRefreshInterval = setInterval(() => {
            if (this.currentRoomId) {
                this.loadMessages();
            }
        }, 10000);
    },
    
    scrollToBottom() {
        const container = document.getElementById('messageContainer');
        if (container) {
            container.scrollTop = container.scrollHeight;
        }
    },
    
    showAlert(message, type = 'info') {
        const container = document.getElementById('alert-container');
        const alert = document.createElement('div');
        alert.className = `alert alert-${type} alert-dismissible fade show`;
        alert.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        container.appendChild(alert);
        
        // Auto-dismiss after 3 seconds
        setTimeout(() => {
            alert.remove();
        }, 3000);
    },
    
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    },
    
    timeAgo(dateString) {
        const date = new Date(dateString);
        const now = new Date();
        const seconds = Math.floor((now - date) / 1000);
        
        const intervals = {
            year: 31536000,
            month: 2592000,
            week: 604800,
            day: 86400,
            hour: 3600,
            minute: 60
        };
        
        for (const [unit, secondsInUnit] of Object.entries(intervals)) {
            const interval = Math.floor(seconds / secondsInUnit);
            if (interval >= 1) {
                return interval === 1 ? `1 ${unit} ago` : `${interval} ${unit}s ago`;
            }
        }
        
        return 'Just now';
    },
    
    formatTime(dateString) {
        const date = new Date(dateString);
        return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    },
    
    showRoomInfo() {
        // Placeholder for room info modal
        this.showAlert('Room info feature coming soon', 'info');
    },
    
    leaveRoom() {
        if (confirm('Are you sure you want to leave this conversation?')) {
            this.currentRoomId = null;
            this.currentRoomName = '';
            this.messages = [];
            this.renderChat();
            this.renderChatList();
        }
    }
};

// Initialize on page load
document.addEventListener('DOMContentLoaded', () => {
    ChatManager.init();
});

// Cleanup on page unload
window.addEventListener('beforeunload', () => {
    if (ChatManager.autoRefreshInterval) {
        clearInterval(ChatManager.autoRefreshInterval);
    }
    if (ChatManager.messageRefreshInterval) {
        clearInterval(ChatManager.messageRefreshInterval);
    }
});
</script>

<style>
.list-group-item {
    transition: background-color 0.3s ease;
}

.list-group-item:hover {
    background-color: #f8f9fa !important;
}

.list-group-item.active {
    background-color: #007bff !important;
    border-color: #007bff;
}

#messageContainer {
    scroll-behavior: smooth;
}

#refresh-btn .fa-sync-alt {
    transition: transform 0.3s ease;
}

#refresh-btn:active .fa-sync-alt {
    transform: rotate(360deg);
}

#message-input {
    resize: none;
}
</style>

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