<?php
/**
 * ============================================================================
 * chat/one-on-one.php - One-on-One Chat Interface
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

$pageTitle = 'Chat';
$userId = getUserId();

// Get database connection
$database = new Database();
$db = $database->getConnection();

$chatClass = new \App\Chat($db);
$messageClass = new \App\Message($db);

// Get chat ID from URL
$chatId = isset($_GET['chat_id']) ? (int)$_GET['chat_id'] : 0;

// If friend_id is provided, create or get chat
if (isset($_GET['friend_id'])) {
    $friendId = (int)$_GET['friend_id'];
    $chatId = $chatClass->createOrGetOneOnOne($userId, $friendId);
    header('Location: ' . APP_URL . '/chat/one-on-one.php?chat_id=' . $chatId);
    exit();
}

// Verify chat exists and user is a member
if (!$chatId || !$chatClass->isMember($chatId, $userId)) {
    $_SESSION['error_message'] = 'Chat not found or access denied';
    header('Location: ' . APP_URL . '/chat/');
    exit();
}

// Get chat details
$chat = $chatClass->getChatDetails($chatId, $userId);
// FIXED: Added $userId parameter to getChatMessages
$messages = $messageClass->getChatMessages($chatId, $userId);

// Mark messages as read
$chatClass->updateLastRead($chatId, $userId);

include_once __DIR__ . '/../includes/meta.php';
include_once __DIR__ . '/../includes/header.php';
?>

<style>
.chat-container {
    height: calc(100vh - 200px);
    display: flex;
    flex-direction: column;
}

.chat-header {
    padding: 15px 20px;
    background: white;
    border-bottom: 1px solid #dee2e6;
    display: flex;
    align-items: center;
    gap: 12px;
}

.chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    background: #f8f9fa;
}

.message {
    margin-bottom: 15px;
    display: flex;
    gap: 10px;
}

.message.sent {
    flex-direction: row-reverse;
}

.message-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    object-fit: cover;
}

.message-content {
    max-width: 60%;
    padding: 10px 15px;
    border-radius: 18px;
    background: white;
    box-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

.message.sent .message-content {
    background: #0d6efd;
    color: white;
}

.message-time {
    font-size: 0.75rem;
    color: #6c757d;
    margin-top: 5px;
}

.message.sent .message-time {
    color: rgba(255,255,255,0.8);
}

.chat-input {
    padding: 15px 20px;
    background: white;
    border-top: 1px solid #dee2e6;
}

.typing-indicator {
    padding: 10px;
    color: #6c757d;
    font-style: italic;
    font-size: 0.9rem;
}

.encrypted-badge {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    font-size: 0.7rem;
    color: #28a745;
    margin-top: 3px;
}
</style>

<div class="container-fluid p-0">
    <div class="chat-container">
        <!-- Chat Header -->
        <div class="chat-header">
            <a href="<?php echo APP_URL; ?>/chat/" class="btn btn-link">
                <i class="bi bi-arrow-left"></i>
            </a>
            <img src="<?php echo getAvatarUrl($chat['display_avatar']); ?>" 
                 class="rounded-circle" 
                 width="40" height="40"
                 alt="<?php echo htmlspecialchars($chat['display_name']); ?>">
            <div class="flex-grow-1">
                <h6 class="mb-0"><?php echo htmlspecialchars($chat['display_name']); ?></h6>
                <small class="text-muted">
                    <?php if ($chat['chat_type'] === 'group'): ?>
                        Group Chat
                    <?php else: ?>
                        <span class="online-status">Online</span>
                    <?php endif; ?>
                </small>
            </div>
            <div class="dropdown">
                <button class="btn btn-link" data-bs-toggle="dropdown">
                    <i class="bi bi-three-dots-vertical"></i>
                </button>
                <ul class="dropdown-menu dropdown-menu-end">
                    <?php if ($chat['chat_type'] === 'group'): ?>
                        <li><a class="dropdown-item" href="<?php echo APP_URL; ?>/chat/group-info.php?chat_id=<?php echo $chatId; ?>">
                            <i class="bi bi-info-circle"></i> Group Info
                        </a></li>
                    <?php endif; ?>
                    <li><a class="dropdown-item" href="#" onclick="searchInChat(); return false;">
                        <i class="bi bi-search"></i> Search
                    </a></li>
                    <li><hr class="dropdown-divider"></li>
                    <li><a class="dropdown-item text-danger" href="#" onclick="leaveChat(); return false;">
                        <i class="bi bi-box-arrow-right"></i> Leave Chat
                    </a></li>
                </ul>
            </div>
        </div>

        <!-- Messages Area -->
        <div class="chat-messages" id="chatMessages">
            <?php if (empty($messages)): ?>
                <div class="text-center text-muted py-5">
                    <i class="bi bi-chat-dots" style="font-size: 3rem;"></i>
                    <p class="mt-3">No messages yet. Start the conversation!</p>
                </div>
            <?php else: ?>
                <?php foreach ($messages as $message): ?>
                    <div class="message <?php echo $message['sender_id'] == $userId ? 'sent' : 'received'; ?>" 
                         data-message-id="<?php echo $message['id']; ?>"
                         data-is-encrypted="<?php echo $message['is_encrypted'] ?? 0; ?>">
                        <?php if ($message['sender_id'] != $userId): ?>
                            <img src="<?php echo getAvatarUrl($message['sender_avatar']); ?>" 
                                 class="message-avatar"
                                 alt="<?php echo htmlspecialchars($message['sender_name']); ?>">
                        <?php endif; ?>
                        
                        <div>
                            <div class="message-content">
                                <?php if ($message['message_type'] === 'image' && $message['media_url']): ?>
                                    <img src="<?php echo htmlspecialchars($message['media_url']); ?>" 
                                         class="img-fluid rounded mb-2" 
                                         style="max-width: 300px;"
                                         alt="Image">
                                <?php endif; ?>
                                
                                <?php if ($message['message_type'] === 'document' && $message['media_url']): ?>
                                    <a href="<?php echo htmlspecialchars($message['media_url']); ?>" 
                                       class="text-decoration-none d-flex align-items-center gap-2 mb-2"
                                       download>
                                        <i class="bi bi-file-earmark"></i>
                                        Document
                                    </a>
                                <?php endif; ?>
                                
                                <div class="message-text">
                                    <?php echo nl2br(htmlspecialchars($message['content'])); ?>
                                </div>
                                
                                <?php if (!empty($message['is_encrypted'])): ?>
                                    <div class="encrypted-badge">
                                        <i class="bi bi-shield-lock-fill"></i>
                                        <span>Encrypted</span>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div class="message-time <?php echo $message['sender_id'] == $userId ? 'text-end' : ''; ?>">
                                <?php echo timeAgo($message['created_at']); ?>
                            </div>
                        </div>
                        
                        <?php if ($message['sender_id'] == $userId): ?>
                            <img src="<?php echo getAvatarUrl($message['sender_avatar']); ?>" 
                                 class="message-avatar"
                                 alt="You">
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <!-- Typing Indicator -->
        <div class="typing-indicator" id="typingIndicator" style="display: none;">
            Someone is typing...
        </div>

        <!-- Input Area -->
        <div class="chat-input">
            <form id="messageForm" class="d-flex gap-2">
                <input type="hidden" name="chat_id" value="<?php echo $chatId; ?>">
                <input type="hidden" id="messageType" name="message_type" value="text">
                <input type="hidden" id="mediaUrl" name="media_url" value="">
                <input type="hidden" id="encrypt" name="encrypt" value="false">
                
                <button type="button" class="btn btn-outline-secondary" onclick="$('#fileInput').click()">
                    <i class="bi bi-paperclip"></i>
                </button>
                
                <input type="file" id="fileInput" class="d-none" accept="image/*,application/pdf,.doc,.docx">
                
                <input type="text" 
                       id="messageInput" 
                       name="content" 
                       class="form-control" 
                       placeholder="Type a message..."
                       autocomplete="off"
                       required>
                
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-send"></i>
                </button>
            </form>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
let lastMessageId = <?php echo !empty($messages) ? end($messages)['id'] : 0; ?>;
let pollingInterval;

$(document).ready(function() {
    // Scroll to bottom
    scrollToBottom();
    
    // Start polling for new messages
    startPolling();
    
    // Handle message form submission
    $('#messageForm').on('submit', function(e) {
        e.preventDefault();
        sendMessage();
    });
    
    // Handle file upload
    $('#fileInput').on('change', function() {
        if (this.files && this.files[0]) {
            uploadFile(this.files[0]);
        }
    });
    
    // Handle typing indicator
    let typingTimer;
    $('#messageInput').on('keyup', function() {
        clearTimeout(typingTimer);
        // Send typing status
        typingTimer = setTimeout(function() {
            // Stop typing
        }, 1000);
    });
});

function scrollToBottom() {
    const messagesDiv = document.getElementById('chatMessages');
    messagesDiv.scrollTop = messagesDiv.scrollHeight;
}

function sendMessage() {
    const formData = new FormData($('#messageForm')[0]);
    
    $.ajax({
        url: '<?php echo APP_URL; ?>/chat/ajax/send-message.php',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            if (response.success) {
                $('#messageInput').val('');
                $('#messageType').val('text');
                $('#mediaUrl').val('');
                appendMessage(response.message);
                scrollToBottom();
                lastMessageId = response.message.id;
            } else {
                alert('Failed to send message: ' + (response.message || 'Unknown error'));
            }
        },
        error: function(xhr, status, error) {
            console.error('Send error:', error);
            alert('Error sending message');
        }
    });
}

function uploadFile(file) {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('chat_id', <?php echo $chatId; ?>);
    
    $.ajax({
        url: '<?php echo APP_URL; ?>/chat/ajax/upload-file.php',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            if (response.success) {
                $('#mediaUrl').val(response.file_url);
                $('#messageType').val(response.file_type);
                $('#messageInput').val(file.name).focus();
            } else {
                alert('Failed to upload file: ' + (response.message || 'Unknown error'));
            }
        },
        error: function() {
            alert('Error uploading file');
        }
    });
}

function startPolling() {
    pollingInterval = setInterval(function() {
        $.ajax({
            url: '<?php echo APP_URL; ?>/chat/ajax/get-messages.php',
            type: 'GET',
            data: {
                chat_id: <?php echo $chatId; ?>,
                after_id: lastMessageId
            },
            success: function(response) {
                if (response.success && response.messages && response.messages.length > 0) {
                    response.messages.forEach(function(message) {
                        appendMessage(message);
                    });
                    lastMessageId = response.messages[response.messages.length - 1].id;
                    scrollToBottom();
                }
            },
            error: function(xhr, status, error) {
                console.error('Polling error:', error);
            }
        });
    }, 3000); // Poll every 3 seconds
}

function appendMessage(message) {
    const isSent = message.sender_id == <?php echo $userId; ?>;
    const isEncrypted = message.is_encrypted == 1;
    
    const messageHtml = `
        <div class="message ${isSent ? 'sent' : 'received'}" 
             data-message-id="${message.id}"
             data-is-encrypted="${isEncrypted ? '1' : '0'}">
            ${!isSent ? `<img src="${getAvatarUrl(message.sender_avatar)}" class="message-avatar" alt="${escapeHtml(message.sender_name)}">` : ''}
            <div>
                <div class="message-content">
                    ${message.message_type === 'image' && message.media_url ? 
                        `<img src="${escapeHtml(message.media_url)}" class="img-fluid rounded mb-2" style="max-width: 300px;" alt="Image">` : ''}
                    ${message.message_type === 'document' && message.media_url ? 
                        `<a href="${escapeHtml(message.media_url)}" class="text-decoration-none d-flex align-items-center gap-2 mb-2" download>
                            <i class="bi bi-file-earmark"></i> Document
                        </a>` : ''}
                    <div class="message-text">${escapeHtml(message.content).replace(/\n/g, '<br>')}</div>
                    ${isEncrypted ? `
                    <div class="encrypted-badge">
                        <i class="bi bi-shield-lock-fill"></i>
                        <span>Encrypted</span>
                    </div>` : ''}
                </div>
                <div class="message-time ${isSent ? 'text-end' : ''}">
                    ${timeAgo(message.created_at)}
                </div>
            </div>
            ${isSent ? `<img src="${getAvatarUrl(message.sender_avatar)}" class="message-avatar" alt="You">` : ''}
        </div>
    `;
    
    $('#chatMessages').append(messageHtml);
}

function getAvatarUrl(avatar) {
    return avatar || '<?php echo APP_URL; ?>/assets/images/default-avatar.png';
}

function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function timeAgo(timestamp) {
    const now = new Date();
    const time = new Date(timestamp);
    const diff = Math.floor((now - time) / 1000);
    
    if (diff < 60) return 'Just now';
    if (diff < 3600) return Math.floor(diff / 60) + 'm ago';
    if (diff < 86400) return Math.floor(diff / 3600) + 'h ago';
    return Math.floor(diff / 86400) + 'd ago';
}

function searchInChat() {
    const query = prompt('Search messages:');
    if (query) {
        window.location.href = '<?php echo APP_URL; ?>/chat/search.php?chat_id=<?php echo $chatId; ?>&q=' + encodeURIComponent(query);
    }
}

function leaveChat() {
    if (confirm('Are you sure you want to leave this chat?')) {
        window.location.href = '<?php echo APP_URL; ?>/chat/leave.php?chat_id=<?php echo $chatId; ?>';
    }
}

// Cleanup on page unload
window.addEventListener('beforeunload', function() {
    if (pollingInterval) {
        clearInterval(pollingInterval);
    }
});
</script>

<?php
include_once __DIR__ . '/../includes/footer.php';
?>