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

requireLogin();

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

// Get database connection
$database = \App\Database::getInstance();
$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'];
    
    // Check if user is blocked
    $blockCheck = "SELECT id FROM user_blocks 
                   WHERE (blocker_id = ? AND blocked_id = ?) 
                   OR (blocker_id = ? AND blocked_id = ?)";
    $stmt = $db->prepare($blockCheck);
    $stmt->execute([$userId, $friendId, $friendId, $userId]);
    
    if ($stmt->fetch()) {
        $_SESSION['error_message'] = 'Cannot start chat with this user';
        header('Location: ' . APP_URL . '/chat/');
        exit();
    }
    
    $chatId = $chatClass->createOrGetOneOnOne($userId, $friendId);
    if ($chatId) {
        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);
$messages = $messageClass->getChatMessages($chatId, $userId);

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

include_once __DIR__ . '/../includes/meta.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title><?php echo htmlspecialchars($chat['display_name']); ?> - Chat</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    
    <!-- SweetAlert2 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    
    <style>
        * {
            -webkit-tap-highlight-color: transparent;
        }
        
        body {
            margin: 0;
            padding: 0;
            overflow: hidden;
            background: #fff;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
        }
        
        .chat-container {
            height: 100vh;
            height: 100dvh; /* Dynamic viewport height for mobile */
            display: flex;
            flex-direction: column;
            background: #fff;
            position: relative;
        }
        
        /* Header */
        .chat-header {
            padding: 10px 12px;
            background: #fff;
            border-bottom: 1px solid #e4e6eb;
            display: flex;
            align-items: center;
            gap: 12px;
            flex-shrink: 0;
            position: sticky;
            top: 0;
            z-index: 100;
            box-shadow: 0 1px 2px rgba(0,0,0,0.05);
        }
        
        .back-btn {
            width: 36px;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            color: #050505;
            text-decoration: none;
            transition: background 0.2s;
        }
        
        .back-btn:hover, .back-btn:active {
            background: #f0f2f5;
        }
        
        .chat-header-avatar {
            position: relative;
        }
        
        .online-dot {
            position: absolute;
            bottom: 0;
            right: 0;
            width: 12px;
            height: 12px;
            background: #31a24c;
            border: 2px solid #fff;
            border-radius: 50%;
        }
        
        .chat-header-info {
            flex: 1;
            min-width: 0;
        }
        
        .chat-header-name {
            font-weight: 600;
            font-size: 16px;
            margin: 0;
            color: #050505;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .chat-header-status {
            font-size: 13px;
            color: #65676b;
            margin: 0;
        }
        
        .chat-header-status.online {
            color: #31a24c;
        }
        
        .header-actions {
            display: flex;
            gap: 8px;
        }
        
        .header-btn {
            width: 36px;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            color: #0084ff;
            background: transparent;
            border: none;
            cursor: pointer;
            transition: background 0.2s;
        }
        
        .header-btn:hover, .header-btn:active {
            background: #f0f2f5;
        }
        
        /* Messages */
        .chat-messages {
            flex: 1;
            overflow-y: auto;
            overflow-x: hidden;
            padding: 16px 12px;
            background: #fff;
            -webkit-overflow-scrolling: touch;
        }
        
        .date-divider {
            text-align: center;
            margin: 16px 0;
        }
        
        .date-divider span {
            display: inline-block;
            background: #fff;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
            color: #65676b;
            font-weight: 500;
            box-shadow: 0 1px 2px rgba(0,0,0,0.1);
        }
        
        .message {
            display: flex;
            gap: 8px;
            margin-bottom: 2px;
            max-width: 100%;
        }
        
        .message.sent {
            flex-direction: row-reverse;
        }
        
        .message-avatar {
            width: 28px;
            height: 28px;
            border-radius: 50%;
            object-fit: cover;
            flex-shrink: 0;
            align-self: flex-end;
        }
        
        .message.sent .message-avatar {
            visibility: hidden;
        }
        
        .message-bubble {
            max-width: 75%;
            padding: 8px 12px;
            border-radius: 18px;
            background: #f0f2f5;
            color: #050505;
            word-wrap: break-word;
            font-size: 15px;
            line-height: 1.4;
        }
        
        .message.sent .message-bubble {
            background: #0084ff;
            color: #fff;
        }
        
        .message-time {
            font-size: 11px;
            color: #65676b;
            margin-top: 2px;
            text-align: center;
            padding: 0 8px;
        }
        
        .message.sent .message-time {
            text-align: right;
        }
        
        .message-media img {
            max-width: 100%;
            border-radius: 12px;
            margin-bottom: 4px;
            cursor: pointer;
        }
        
        /* Input Area */
        .chat-input {
            padding: 8px 12px 8px 12px; 
            padding-bottom: max(8px, env(safe-area-inset-bottom));
            background: #fff;
            border-top: 1px solid #e4e6eb;
            flex-shrink: 0;
        }
        
        .input-wrapper {
            display: flex;
            gap: 8px;
            align-items: center;
        }
        
        .input-actions {
            display: flex;
            gap: 4px;
        }
        
        .input-btn {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            background: transparent;
            border: none;
            color: #0084ff;
            cursor: pointer;
            font-size: 20px;
        }
        
        .input-btn:active {
            background: rgba(0, 132, 255, 0.1);
        }
        
        .message-input {
            flex: 1;
            border: 1px solid #ccd0d5;
            border-radius: 20px;
            padding: 8px 16px;
            font-size: 15px;
            outline: none;
            background: #f0f2f5;
            border: none;
            resize: none;
            max-height: 100px;
        }
        
        .send-btn {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background: #0084ff;
            color: #fff;
            border: none;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-size: 18px;
            transition: background 0.2s;
        }
        
        .send-btn:active {
            background: #0073e6;
        }
        
        .send-btn:disabled {
            background: #bcc0c4;
            cursor: not-allowed;
        }
        
        /* Typing Indicator */
        .typing-indicator {
            padding: 8px 12px;
            font-size: 13px;
            color: #65676b;
            font-style: italic;
            display: none;
        }
        
        .typing-indicator.active {
            display: block;
        }
        
        .typing-dots {
            display: inline-flex;
            gap: 3px;
            margin-left: 4px;
        }
        
        .typing-dots span {
            width: 6px;
            height: 6px;
            background: #65676b;
            border-radius: 50%;
            animation: typing 1.4s infinite;
        }
        
        .typing-dots span:nth-child(2) {
            animation-delay: 0.2s;
        }
        
        .typing-dots span:nth-child(3) {
            animation-delay: 0.4s;
        }
        
        @keyframes typing {
            0%, 60%, 100% {
                opacity: 0.3;
                transform: translateY(0);
            }
            30% {
                opacity: 1;
                transform: translateY(-3px);
            }
        }
        
        /* Loading */
        .loading-spinner {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 2px solid #f3f3f3;
            border-top: 2px solid #0084ff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* Connection Status */
        .connection-status {
            position: fixed;
            top: 50px;
            left: 50%;
            transform: translateX(-50%);
            background: #fff;
            padding: 6px 16px;
            border-radius: 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
            font-size: 13px;
            z-index: 1000;
            display: none;
        }
        
        .connection-status.connected {
            display: block;
            color: #31a24c;
        }
        
        .connection-status.disconnected {
            display: block;
            color: #dc3545;
        }
        
        /* SweetAlert2 Customization */
        .swal2-popup {
            font-size: 14px !important;
        }
        
        /* Mobile optimizations */
        @media (max-width: 768px) {
            .chat-header {
                padding: 8px;
            }
            
            .message-bubble {
                max-width: 80%;
            }
        }
        
        /* Prevent zoom on input focus (iOS) */
        @media screen and (-webkit-min-device-pixel-ratio: 0) {
            select, textarea, input {
                font-size: 16px !important;
            }
        }
    </style>
</head>
<body>

<div class="connection-status" id="connectionStatus">
    <i class="bi bi-circle-fill"></i> <span id="connectionText"></span>
</div>

<div class="chat-container">
    <!-- Header -->
    <div class="chat-header">
        <a href="<?php echo APP_URL; ?>/chat/" class="back-btn">
            <i class="bi bi-arrow-left"></i>
        </a>
        
        <div class="chat-header-avatar">
            <img src="<?php echo getAvatarUrl($chat['display_avatar']); ?>" 
                 class="rounded-circle" 
                 width="40" 
                 height="40"
                 alt="<?php echo htmlspecialchars($chat['display_name']); ?>">
            <?php if ($chat['is_online']): ?>
                <span class="online-dot"></span>
            <?php endif; ?>
        </div>
        
        <div class="chat-header-info">
            <h6 class="chat-header-name"><?php echo htmlspecialchars($chat['display_name']); ?></h6>
            <p class="chat-header-status <?php echo $chat['is_online'] ? 'online' : ''; ?>" id="userStatus">
                <?php echo $chat['is_online'] ? 'Active now' : 'Offline'; ?>
            </p>
        </div>
        
        <div class="header-actions">
            <button class="header-btn" onclick="makeCall()" title="Call">
                <i class="bi bi-telephone-fill"></i>
            </button>
            <button class="header-btn" onclick="openMenu()" title="More">
                <i class="bi bi-three-dots-vertical"></i>
            </button>
        </div>
    </div>

    <!-- Messages -->
    <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: 48px; opacity: 0.3;"></i>
                <p class="mt-3">No messages yet. Say hi! 👋</p>
            </div>
        <?php else: ?>
            <?php 
            $lastDate = '';
            foreach ($messages as $message): 
                $messageDate = date('Y-m-d', strtotime($message['created_at']));
                if ($messageDate != $lastDate):
                    $lastDate = $messageDate;
            ?>
                <div class="date-divider">
                    <span><?php echo formatDate($messageDate); ?></span>
                </div>
            <?php endif; ?>
                <div class="message <?php echo $message['sender_id'] == $userId ? 'sent' : 'received'; ?>" 
                     data-message-id="<?php echo $message['id']; ?>">
                    <img src="<?php echo getAvatarUrl($message['sender_avatar']); ?>" 
                         class="message-avatar"
                         alt="">
                    <div>
                        <div class="message-bubble">
                            <?php if ($message['message_type'] === 'image' && $message['media_url']): ?>
                                <div class="message-media">
                                    <img src="<?php echo htmlspecialchars($message['media_url']); ?>" 
                                         alt="Image"
                                         onclick="viewImage('<?php echo htmlspecialchars($message['media_url']); ?>')">
                                </div>
                            <?php endif; ?>
                            
                            <?php echo nl2br(htmlspecialchars($message['content'])); ?>
                        </div>
                        <div class="message-time">
                            <?php echo date('g:i A', strtotime($message['created_at'])); ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <!-- Typing Indicator -->
    <div class="typing-indicator" id="typingIndicator">
        <span id="typingText">Typing</span>
        <span class="typing-dots">
            <span></span>
            <span></span>
            <span></span>
        </span>
    </div>

    <!-- Input -->
    <div class="chat-input">
        <form id="messageForm" onsubmit="return false;">
            <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="recipientId" value="<?php echo $chat['friend_id']; ?>">
            
            <div class="input-wrapper">
                <div class="input-actions">
                    <button type="button" class="input-btn" onclick="$('#imageInput').click()" title="Photo">
                        <i class="bi bi-image"></i>
                    </button>
                </div>
                
                <input type="file" id="imageInput" class="d-none" accept="image/*">
                
                <textarea id="messageInput" 
                       name="content" 
                       class="message-input" 
                       placeholder="Message..."
                       rows="1"
                       autocomplete="off"></textarea>
                
                <button type="submit" class="send-btn" id="sendButton">
                    <i class="bi bi-send-fill"></i>
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
const chatId = <?php echo $chatId; ?>;
const userId = <?php echo $userId; ?>;
const recipientId = <?php echo $chat['friend_id']; ?>;
let ws = null;
let lastMessageId = <?php echo !empty($messages) ? end($messages)['id'] : 0; ?>;
let typingTimer = null;
let isTyping = false;

$(document).ready(function() {
    scrollToBottom();
    initWebSocket();
    
    // Auto-resize textarea
    $('#messageInput').on('input', function() {
        this.style.height = 'auto';
        this.style.height = (this.scrollHeight) + 'px';
    });
    
    // Form submission
    $('#messageForm').on('submit', function(e) {
        e.preventDefault();
        sendMessage();
    });
    
    // File upload
    $('#imageInput').on('change', function() {
        if (this.files && this.files[0]) {
            uploadFile(this.files[0]);
        }
    });
    
    // Typing indicator
    $('#messageInput').on('input', function() {
        if (!isTyping && $(this).val().trim()) {
            isTyping = true;
            sendTypingStatus(true);
        }
        
        clearTimeout(typingTimer);
        typingTimer = setTimeout(function() {
            if (isTyping) {
                isTyping = false;
                sendTypingStatus(false);
            }
        }, 1000);
    });
});

// Initialize WebSocket
function initWebSocket() {
    try {
        ws = new WebSocket('ws://localhost:8080');
        
        ws.onopen = function() {
            console.log('Connected');
            ws.send(JSON.stringify({
                type: 'auth',
                user_id: userId,
                token: 'session_token'
            }));
        };
        
        ws.onmessage = function(event) {
            const data = JSON.parse(event.data);
            handleWebSocketMessage(data);
        };
        
        ws.onerror = function() {
            console.log('WebSocket error');
            startPolling();
        };
        
        ws.onclose = function() {
            setTimeout(initWebSocket, 5000);
        };
    } catch (e) {
        startPolling();
    }
}

function handleWebSocketMessage(data) {
    switch (data.type) {
        case 'new_message':
            if (data.chat_id === chatId) {
                appendMessage(data.message);
                lastMessageId = data.message.id;
                scrollToBottom();
                markAsRead();
            }
            break;
        case 'typing':
            if (data.chat_id === chatId) {
                showTypingIndicator(data.typing);
            }
            break;
        case 'user_status':
            if (data.user_id === recipientId) {
                updateUserStatus(data.online);
            }
            break;
    }
}

// Send message
function sendMessage() {
    const content = $('#messageInput').val().trim();
    
    if (!content) return;
    
    // Disable send button
    $('#sendButton').prop('disabled', true).html('<span class="loading-spinner"></span>');
    
    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('').css('height', 'auto');
                $('#messageType').val('text');
                $('#mediaUrl').val('');
                
                // Send via WebSocket
                if (ws && ws.readyState === WebSocket.OPEN) {
                    ws.send(JSON.stringify({
                        type: 'message',
                        chat_id: chatId,
                        recipient_id: recipientId,
                        message_id: response.message.id
                    }));
                }
                
                appendMessage(response.message);
                lastMessageId = response.message.id;
                scrollToBottom();
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Failed to send',
                    text: response.message || 'Could not send message. Please try again.',
                    toast: true,
                    position: 'top',
                    showConfirmButton: false,
                    timer: 3000
                });
            }
        },
        error: function(xhr) {
            console.error('Send error:', xhr);
            const errorMsg = xhr.responseJSON?.message || 'Network error. Please check your connection.';
            
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: errorMsg,
                toast: true,
                position: 'top',
                showConfirmButton: false,
                timer: 3000
            });
        },
        complete: function() {
            $('#sendButton').prop('disabled', false).html('<i class="bi bi-send-fill"></i>');
        }
    });
}

// Append message
function appendMessage(message) {
    const isSent = message.sender_id == userId;
    
    let mediaHtml = '';
    if (message.message_type === 'image' && message.media_url) {
        mediaHtml = `<div class="message-media">
            <img src="${escapeHtml(message.media_url)}" alt="Image" onclick="viewImage('${escapeHtml(message.media_url)}')">
        </div>`;
    }
    
    const messageHtml = `
        <div class="message ${isSent ? 'sent' : 'received'}" data-message-id="${message.id}">
            <img src="${getAvatarUrl(message.sender_avatar)}" class="message-avatar" alt="">
            <div>
                <div class="message-bubble">
                    ${mediaHtml}
                    ${escapeHtml(message.content).replace(/\n/g, '<br>')}
                </div>
                <div class="message-time">
                    ${formatTime(message.created_at)}
                </div>
            </div>
        </div>
    `;
    
    $('#chatMessages').append(messageHtml);
}

function sendTypingStatus(typing) {
    if (ws && ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({
            type: 'typing',
            chat_id: chatId,
            recipient_id: recipientId,
            typing: typing
        }));
    }
}

function showTypingIndicator(show) {
    if (show) {
        $('#typingIndicator').addClass('active');
        scrollToBottom();
    } else {
        $('#typingIndicator').removeClass('active');
    }
}

function markAsRead() {
    if (ws && ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({
            type: 'read',
            chat_id: chatId,
            recipient_id: recipientId
        }));
    }
}

function updateUserStatus(online) {
    if (online) {
        $('#userStatus').text('Active now').addClass('online');
        $('.online-dot').show();
    } else {
        $('#userStatus').text('Offline').removeClass('online');
        $('.online-dot').hide();
    }
}

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

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

function uploadFile(file) {
    if (file.size > 10 * 1024 * 1024) {
        Swal.fire({
            icon: 'error',
            title: 'File too large',
            text: 'Maximum file size is 10MB',
            toast: true,
            position: 'top',
            showConfirmButton: false,
            timer: 3000
        });
        return;
    }
    
    Swal.fire({
        title: 'Uploading...',
        html: '<div class="loading-spinner"></div>',
        showConfirmButton: false,
        allowOutsideClick: false
    });
    
    const formData = new FormData();
    formData.append('file', file);
    formData.append('chat_id', chatId);
    
    $.ajax({
        url: '<?php echo APP_URL; ?>/chat/ajax/upload-file.php',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            Swal.close();
            if (response.success) {
                $('#mediaUrl').val(response.file_url);
                $('#messageType').val(response.file_type);
                $('#messageInput').val(file.name).focus();
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Upload failed',
                    text: response.message,
                    toast: true,
                    position: 'top',
                    showConfirmButton: false,
                    timer: 3000
                });
            }
        },
        error: function() {
            Swal.close();
            Swal.fire({
                icon: 'error',
                title: 'Upload failed',
                text: 'Could not upload file',
                toast: true,
                position: 'top',
                showConfirmButton: false,
                timer: 3000
            });
        }
    });
}

function viewImage(url) {
    Swal.fire({
        imageUrl: url,
        imageAlt: 'Image',
        showCloseButton: true,
        showConfirmButton: false,
        width: '90%'
    });
}

function makeCall() {
    Swal.fire({
        icon: 'info',
        title: 'Voice/Video Call',
        text: 'Calling feature coming soon!',
        confirmButtonText: 'OK'
    });
}

function openMenu() {
    Swal.fire({
        title: 'Options',
        showCancelButton: true,
        showDenyButton: true,
        showConfirmButton: true,
        confirmButtonText: '<i class="bi bi-flag"></i> Report',
        confirmButtonColor: '#dc3545',
        denyButtonText: '<i class="bi bi-slash-circle"></i> Block',
        denyButtonColor: '#6c757d',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            reportUser();
        } else if (result.isDenied) {
            blockUser();
        }
    });
}

function blockUser() {
    Swal.fire({
        title: 'Block User?',
        text: "You won't be able to message each other",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#dc3545',
        confirmButtonText: 'Yes, block'
    }).then((result) => {
        if (result.isConfirmed) {
            $.post('<?php echo APP_URL; ?>/chat/ajax/block-user.php', {
                user_id: recipientId
            }, function(response) {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'User Blocked',
                        text: response.message,
                        timer: 2000
                    }).then(() => {
                        window.location.href = '<?php echo APP_URL; ?>/chat/';
                    });
                } else {
                    Swal.fire('Error', response.message, 'error');
                }
            });
        }
    });
}

function reportUser() {
    Swal.fire({
        title: 'Report User',
        html: `
            <select id="reportType" class="swal2-input">
                <option value="">Select reason...</option>
                <option value="spam">Spam</option>
                <option value="harassment">Harassment</option>
                <option value="fake_profile">Fake Profile</option>
                <option value="inappropriate_content">Inappropriate Content</option>
                <option value="scam">Scam/Fraud</option>
                <option value="other">Other</option>
            </select>
            <textarea id="reportDescription" class="swal2-textarea" placeholder="Additional details (optional)"></textarea>
        `,
        showCancelButton: true,
        confirmButtonText: 'Submit Report',
        confirmButtonColor: '#dc3545',
        preConfirm: () => {
            const type = $('#reportType').val();
            const description = $('#reportDescription').val();
            
            if (!type) {
                Swal.showValidationMessage('Please select a reason');
                return false;
            }
            
            return { type, description };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            $.post('<?php echo APP_URL; ?>/chat/ajax/report-user.php', {
                user_id: recipientId,
                chat_id: chatId,
                report_type: result.value.type,
                description: result.value.description
            }, function(response) {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Report Submitted',
                        text: response.message,
                        timer: 3000
                    });
                } else {
                    Swal.fire('Error', response.message, 'error');
                }
            });
        }
    });
}

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 formatTime(timestamp) {
    const date = new Date(timestamp);
    return date.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true });
}

window.addEventListener('beforeunload', function() {
    if (ws) ws.close();
});
</script>

</body>
</html>