<?php
require_once '../includes/init.php';

// Check admin access
if (!isAuthenticated() || !$_SESSION['is_admin']) {
    redirect(APP_URL . '/login.php');
}

$user1Id = intval($_GET['user1'] ?? 0);
$user2Id = intval($_GET['user2'] ?? 0);

if (!$user1Id || !$user2Id) {
    redirect(APP_URL . '/admin/chats.php');
}

$db = getDB();

// Get both users' info with status
$stmt = $db->prepare("SELECT id, unique_id, name, profile_photo, email, mobile, status, last_seen, last_activity, created_at FROM users WHERE id IN (?, ?)");
$stmt->execute([$user1Id, $user2Id]);
$users = $stmt->fetchAll();

if (count($users) !== 2) {
    redirect(APP_URL . '/admin/chats.php?error=users_not_found');
}

$user1 = $users[0]['id'] == $user1Id ? $users[0] : $users[1];
$user2 = $users[0]['id'] == $user2Id ? $users[0] : $users[1];

// Get conversation messages with theme info
$stmt = $db->prepare("
    SELECT m.*, 
           u1.name as sender_name,
           u1.profile_photo as sender_photo,
           u2.name as receiver_name,
           u2.profile_photo as receiver_photo,
           ct1.background_color as sender_theme_bg,
           ct1.message_color as sender_theme_msg,
           ct1.text_color as sender_theme_text,
           ct2.background_color as receiver_theme_bg,
           ct2.message_color as receiver_theme_msg,
           ct2.text_color as receiver_theme_text
    FROM messages m
    LEFT JOIN users u1 ON m.sender_id = u1.id
    LEFT JOIN users u2 ON m.receiver_id = u2.id
    LEFT JOIN chat_themes ct1 ON (ct1.user_id = m.sender_id AND ct1.chat_with_id = m.receiver_id)
    LEFT JOIN chat_themes ct2 ON (ct2.user_id = m.receiver_id AND ct2.chat_with_id = m.sender_id)
    WHERE ((m.sender_id = ? AND m.receiver_id = ?) OR (m.sender_id = ? AND m.receiver_id = ?))
    AND m.is_deleted_for_all = 0
    ORDER BY m.created_at ASC
");
$stmt->execute([$user1Id, $user2Id, $user2Id, $user1Id]);
$messages = $stmt->fetchAll();

// Get conversation stats
$stmt = $db->prepare("
    SELECT 
        COUNT(*) as total_messages,
        COUNT(CASE WHEN message_type = 'image' THEN 1 END) as images,
        COUNT(CASE WHEN message_type = 'video' THEN 1 END) as videos,
        COUNT(CASE WHEN message_type = 'gif' THEN 1 END) as gifs,
        COUNT(CASE WHEN message_type = 'voice' THEN 1 END) as voice_messages,
        COUNT(CASE WHEN is_forwarded = 1 THEN 1 END) as forwarded_messages,
        MIN(created_at) as first_message,
        MAX(created_at) as last_message
    FROM messages 
    WHERE ((sender_id = ? AND receiver_id = ?) OR (sender_id = ? AND receiver_id = ?))
    AND is_deleted_for_all = 0
");
$stmt->execute([$user1Id, $user2Id, $user2Id, $user1Id]);
$stats = $stmt->fetch();

$pageTitle = 'Conversation - ' . $user1['name'] . ' & ' . $user2['name'];

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

<div class="min-h-screen bg-slate-50 dark:bg-slate-900">
    <!-- Header -->
    <div class="bg-white dark:bg-slate-800 border-b border-slate-200 dark:border-slate-700">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex items-center justify-between h-16">
                <div class="flex items-center gap-4">
                    <a href="chats.php" class="text-slate-600 dark:text-slate-400 hover:text-primary transition-colors">
                        <span class="material-symbols-outlined">arrow_back</span>
                    </a>
                    <div>
                        <h1 class="text-lg font-semibold text-slate-900 dark:text-slate-100">Conversation View</h1>
                        <p class="text-sm text-slate-500 dark:text-slate-400">
                            <?php echo htmlspecialchars($user1['name']); ?> ↔ <?php echo htmlspecialchars($user2['name']); ?>
                        </p>
                    </div>
                </div>
                <div class="flex items-center gap-2">
                    <a href="export-chat.php?user1=<?php echo $user1Id; ?>&user2=<?php echo $user2Id; ?>" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors text-sm font-medium">
                        <span class="material-symbols-outlined text-base align-middle me-1">download</span>
                        Export Chat
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- User Info Cards -->
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
            <!-- User 1 Card -->
            <div class="bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 p-6">
                <div class="flex items-center gap-4 mb-4">
                    <div class="relative">
                        <?php if ($user1['profile_photo']): ?>
                            <img src="../<?php echo htmlspecialchars($user1['profile_photo']); ?>" 
                                 alt="<?php echo htmlspecialchars($user1['name']); ?>" 
                                 class="w-16 h-16 rounded-full object-cover border-2 border-slate-200 dark:border-slate-700">
                        <?php else: ?>
                            <div class="w-16 h-16 rounded-full bg-slate-200 dark:bg-slate-700 flex items-center justify-center">
                                <span class="material-symbols-outlined text-2xl text-slate-500 dark:text-slate-400">person</span>
                            </div>
                        <?php endif; ?>
                        <div id="online-indicator-<?php echo $user1['id']; ?>" class="absolute bottom-0 right-0 w-4 h-4 rounded-full border-2 border-white dark:border-slate-800 transition-colors" 
                             style="background-color: <?php 
                                 $lastActivity1 = new DateTime($user1['last_activity'] ?? $user1['created_at']);
                                 $now1 = new DateTime();
                                 $interval1 = $now1->diff($lastActivity1);
                                 if ($interval1->i < 2) echo '#10b981'; // green for online
                                 elseif ($interval1->i < 5) echo '#f59e0b'; // yellow for away
                                 else echo '#6b7280'; // gray for offline
                             ?>;"></div>
                    </div>
                    <div>
                        <h3 class="font-semibold text-slate-900 dark:text-slate-100"><?php echo htmlspecialchars($user1['name']); ?></h3>
                        <p class="text-sm text-slate-500 dark:text-slate-400"><?php echo htmlspecialchars($user1['email']); ?></p>
                        <p class="text-sm text-slate-500 dark:text-slate-400"><?php echo htmlspecialchars($user1['mobile']); ?></p>
                    </div>
                </div>
                <div class="grid grid-cols-2 gap-4 text-sm">
                    <div>
                        <span class="text-slate-500 dark:text-slate-400">Status:</span>
                        <span class="ml-2 px-2 py-1 rounded-full text-xs font-medium 
                            <?php 
                            $lastActivity1 = new DateTime($user1['last_activity'] ?? $user1['created_at']);
                            $now1 = new DateTime();
                            $interval1 = $now1->diff($lastActivity1);
                            if ($interval1->i < 2) {
                                echo 'bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400';
                                $status1 = 'Online';
                            } elseif ($interval1->i < 5) {
                                echo 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/20 dark:text-yellow-400';
                                $status1 = 'Away';
                            } else {
                                echo 'bg-slate-100 text-slate-700 dark:bg-slate-700 dark:text-slate-400';
                                $status1 = 'Offline';
                            }
                            ?>">
                            <?php echo $status1; ?>
                        </span>
                    </div>
                    <div>
                        <span class="text-slate-500 dark:text-slate-400">User ID:</span>
                        <span class="ml-2 text-slate-900 dark:text-slate-100"><?php echo htmlspecialchars($user1['unique_id']); ?></span>
                    </div>
                    <div>
                        <span class="text-slate-500 dark:text-slate-400">Last Seen:</span>
                        <span class="ml-2 text-slate-900 dark:text-slate-100"><?php echo $user1['last_seen'] ? date('M j, g:i A', strtotime($user1['last_seen'])) : 'Never'; ?></span>
                    </div>
                    <div>
                        <span class="text-slate-500 dark:text-slate-400">Last Activity:</span>
                        <span class="ml-2 text-slate-900 dark:text-slate-100"><?php echo date('M j, g:i A', strtotime($user1['last_activity'] ?? $user1['created_at'])); ?></span>
                    </div>
                </div>
            </div>

            <!-- User 2 Card -->
            <div class="bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 p-6">
                <div class="flex items-center gap-4 mb-4">
                    <div class="relative">
                        <?php if ($user2['profile_photo']): ?>
                            <img src="../<?php echo htmlspecialchars($user2['profile_photo']); ?>" 
                                 alt="<?php echo htmlspecialchars($user2['name']); ?>" 
                                 class="w-16 h-16 rounded-full object-cover border-2 border-slate-200 dark:border-slate-700">
                        <?php else: ?>
                            <div class="w-16 h-16 rounded-full bg-slate-200 dark:bg-slate-700 flex items-center justify-center">
                                <span class="material-symbols-outlined text-2xl text-slate-500 dark:text-slate-400">person</span>
                            </div>
                        <?php endif; ?>
                        <div id="online-indicator-<?php echo $user2['id']; ?>" class="absolute bottom-0 right-0 w-4 h-4 rounded-full border-2 border-white dark:border-slate-800 transition-colors" 
                             style="background-color: <?php 
                                 $lastActivity2 = new DateTime($user2['last_activity'] ?? $user2['created_at']);
                                 $now2 = new DateTime();
                                 $interval2 = $now2->diff($lastActivity2);
                                 if ($interval2->i < 2) echo '#10b981'; // green for online
                                 elseif ($interval2->i < 5) echo '#f59e0b'; // yellow for away
                                 else echo '#6b7280'; // gray for offline
                             ?>;"></div>
                    </div>
                    <div>
                        <h3 class="font-semibold text-slate-900 dark:text-slate-100"><?php echo htmlspecialchars($user2['name']); ?></h3>
                        <p class="text-sm text-slate-500 dark:text-slate-400"><?php echo htmlspecialchars($user2['email']); ?></p>
                        <p class="text-sm text-slate-500 dark:text-slate-400"><?php echo htmlspecialchars($user2['mobile']); ?></p>
                    </div>
                </div>
                <div class="grid grid-cols-2 gap-4 text-sm">
                    <div>
                        <span class="text-slate-500 dark:text-slate-400">Status:</span>
                        <span class="ml-2 px-2 py-1 rounded-full text-xs font-medium 
                            <?php 
                            $lastActivity2 = new DateTime($user2['last_activity'] ?? $user2['created_at']);
                            $now2 = new DateTime();
                            $interval2 = $now2->diff($lastActivity2);
                            if ($interval2->i < 2) {
                                echo 'bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400';
                                $status2 = 'Online';
                            } elseif ($interval2->i < 5) {
                                echo 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/20 dark:text-yellow-400';
                                $status2 = 'Away';
                            } else {
                                echo 'bg-slate-100 text-slate-700 dark:bg-slate-700 dark:text-slate-400';
                                $status2 = 'Offline';
                            }
                            ?>">
                            <?php echo $status2; ?>
                        </span>
                    </div>
                    <div>
                        <span class="text-slate-500 dark:text-slate-400">User ID:</span>
                        <span class="ml-2 text-slate-900 dark:text-slate-100"><?php echo htmlspecialchars($user2['unique_id']); ?></span>
                    </div>
                    <div>
                        <span class="text-slate-500 dark:text-slate-400">Last Seen:</span>
                        <span class="ml-2 text-slate-900 dark:text-slate-100"><?php echo $user2['last_seen'] ? date('M j, g:i A', strtotime($user2['last_seen'])) : 'Never'; ?></span>
                    </div>
                    <div>
                        <span class="text-slate-500 dark:text-slate-400">Last Activity:</span>
                        <span class="ml-2 text-slate-900 dark:text-slate-100"><?php echo date('M j, g:i A', strtotime($user2['last_activity'] ?? $user2['created_at'])); ?></span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Conversation Stats -->
        <div class="bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 p-6 mb-6">
            <h2 class="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-4">Conversation Statistics</h2>
            <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4">
                <div class="text-center">
                    <div class="text-2xl font-bold text-primary"><?php echo $stats['total_messages']; ?></div>
                    <div class="text-sm text-slate-500 dark:text-slate-400">Total Messages</div>
                </div>
                <div class="text-center">
                    <div class="text-2xl font-bold text-blue-600"><?php echo $stats['images']; ?></div>
                    <div class="text-sm text-slate-500 dark:text-slate-400">Images</div>
                </div>
                <div class="text-center">
                    <div class="text-2xl font-bold text-green-600"><?php echo $stats['videos']; ?></div>
                    <div class="text-sm text-slate-500 dark:text-slate-400">Videos</div>
                </div>
                <div class="text-center">
                    <div class="text-2xl font-bold text-purple-600"><?php echo $stats['gifs']; ?></div>
                    <div class="text-sm text-slate-500 dark:text-slate-400">GIFs</div>
                </div>
                <div class="text-center">
                    <div class="text-2xl font-bold text-orange-600"><?php echo $stats['voice_messages']; ?></div>
                    <div class="text-sm text-slate-500 dark:text-slate-400">Voice</div>
                </div>
                <div class="text-center">
                    <div class="text-2xl font-bold text-pink-600"><?php echo $stats['forwarded_messages']; ?></div>
                    <div class="text-sm text-slate-500 dark:text-slate-400">Forwarded</div>
                </div>
                <div class="text-center">
                    <div class="text-2xl font-bold text-slate-600"><?php echo $stats['total_messages'] > 0 ? date('M j, Y', strtotime($stats['last_message'])) : 'N/A'; ?></div>
                    <div class="text-sm text-slate-500 dark:text-slate-400">Last Message</div>
                </div>
            </div>
        </div>

        <!-- Messages with Theme Display -->
        <div class="bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700">
            <div class="p-4 border-b border-slate-200 dark:border-slate-700">
                <div class="flex items-center justify-between">
                    <h2 class="text-lg font-semibold text-slate-900 dark:text-slate-100">Messages (<?php echo count($messages); ?>)</h2>
                    <div class="flex items-center gap-4">
                        <!-- Theme Sync Button -->
                        <button onclick="syncThemes()" class="px-3 py-1.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors text-sm font-medium">
                            <span class="material-symbols-outlined text-sm align-middle">sync</span>
                            Sync Themes
                        </button>
                        <!-- Dark Mode Toggle -->
                        <button onclick="toggleDarkMode()" class="px-3 py-1.5 bg-slate-600 text-white rounded-lg hover:bg-slate-700 transition-colors text-sm font-medium">
                            <span class="material-symbols-outlined text-sm align-middle" id="darkModeIcon">dark_mode</span>
                            Dark Mode
                        </button>
                    </div>
                </div>
            </div>
            <div class="max-h-96 overflow-y-auto" id="messages-container" style="background-color: #ffffff; transition: background-color 0.3s ease;">
                <?php if (empty($messages)): ?>
                    <div class="p-8 text-center">
                        <span class="material-symbols-outlined text-4xl text-slate-300 dark:text-slate-600">chat</span>
                        <p class="mt-2 text-slate-500 dark:text-slate-400">No messages found</p>
                    </div>
                <?php else: ?>
                    <?php 
                    $currentDate = '';
                    foreach ($messages as $msg): 
                        $msgDate = date('Y-m-d', strtotime($msg['created_at']));
                        if ($msgDate !== $currentDate) {
                            $currentDate = $msgDate;
                            echo '<div class="px-4 py-2 bg-slate-50 dark:bg-slate-700 border-b border-slate-200 dark:border-slate-600">';
                            echo '<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">' . date('F j, Y', strtotime($msg['created_at'])) . '</span>';
                            echo '</div>';
                        }
                    ?>
                        <div class="p-4 border-b border-slate-100 dark:border-slate-700 last:border-b-0">
                            <div class="flex items-start gap-3">
                                <!-- Sender Avatar -->
                                <div class="flex-shrink-0">
                                    <?php if ($msg['sender_photo']): ?>
                                        <img src="../<?php echo htmlspecialchars($msg['sender_photo']); ?>" 
                                             alt="<?php echo htmlspecialchars($msg['sender_name']); ?>" 
                                             class="w-8 h-8 rounded-full object-cover">
                                    <?php else: ?>
                                        <div class="w-8 h-8 rounded-full bg-slate-200 dark:bg-slate-700 flex items-center justify-center">
                                            <span class="material-symbols-outlined text-sm text-slate-500 dark:text-slate-400">person</span>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                
                                <!-- Message Content with Theme -->
                                <div class="flex-1 min-w-0">
                                    <div class="flex items-center gap-2 mb-1">
                                        <span class="font-medium text-slate-900 dark:text-slate-100"><?php echo htmlspecialchars($msg['sender_name']); ?></span>
                                        <span class="text-xs text-slate-500 dark:text-slate-400"><?php echo date('g:i A', strtotime($msg['created_at'])); ?></span>
                                        <?php if ($msg['is_forwarded']): ?>
                                            <span class="text-xs text-blue-600 dark:text-blue-400">
                                                <span class="material-symbols-outlined text-xs align-middle">forward</span> Forwarded
                                            </span>
                                        <?php endif; ?>
                                        <!-- Theme Info -->
                                        <div class="flex items-center gap-2 text-xs">
                                            <div class="flex items-center gap-1">
                                                <div class="w-3 h-3 rounded-full border border-slate-300" style="background-color: <?php echo $msg['sender_theme_bg'] ?: '#ffffff'; ?>"></div>
                                                <span class="text-slate-500">Sender Theme</span>
                                            </div>
                                            <div class="flex items-center gap-1">
                                                <div class="w-3 h-3 rounded-full border border-slate-300" style="background-color: <?php echo $msg['receiver_theme_bg'] ?: '#ffffff'; ?>"></div>
                                                <span class="text-slate-500">Receiver Theme</span>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Message Type Display with Theme -->
                                    <div class="relative">
                                        <?php if ($msg['message_type'] === 'text'): ?>
                                            <div class="rounded-lg p-3 transition-all duration-300" 
                                                 style="background-color: <?php echo $msg['sender_theme_msg'] ?: '#1162d4'; ?>; color: <?php echo $msg['sender_theme_text'] ?: '#ffffff'; ?>;">
                                                <p class="text-[15px] leading-[1.4] font-normal"><?php echo nl2br(htmlspecialchars($msg['message'])); ?></p>
                                            </div>
                                        <?php elseif ($msg['message_type'] === 'image'): ?>
                                            <div class="rounded-lg p-3 transition-all duration-300" 
                                                 style="background-color: <?php echo $msg['sender_theme_msg'] ?: '#1162d4'; ?>;">
                                                <img src="../<?php echo htmlspecialchars($msg['file_url']); ?>" 
                                                     alt="Image" 
                                                     class="max-w-xs rounded-lg cursor-pointer hover:opacity-80 transition-opacity"
                                                     onclick="window.open('../<?php echo htmlspecialchars($msg['file_url']); ?>', '_blank')">
                                                <?php if ($msg['message']): ?>
                                                    <p class="text-[15px] leading-[1.4] font-normal mt-2" style="color: <?php echo $msg['sender_theme_text'] ?: '#ffffff'; ?>;"><?php echo nl2br(htmlspecialchars($msg['message'])); ?></p>
                                                <?php endif; ?>
                                            </div>
                                        <?php elseif ($msg['message_type'] === 'video'): ?>
                                            <div class="rounded-lg p-3 transition-all duration-300" 
                                                 style="background-color: <?php echo $msg['sender_theme_msg'] ?: '#1162d4'; ?>;">
                                                <video src="../<?php echo htmlspecialchars($msg['file_url']); ?>" 
                                                       controls 
                                                       class="max-w-xs rounded-lg"></video>
                                                <?php if ($msg['message']): ?>
                                                    <p class="text-[15px] leading-[1.4] font-normal mt-2" style="color: <?php echo $msg['sender_theme_text'] ?: '#ffffff'; ?>;"><?php echo nl2br(htmlspecialchars($msg['message'])); ?></p>
                                                <?php endif; ?>
                                            </div>
                                        <?php elseif ($msg['message_type'] === 'gif'): ?>
                                            <div class="rounded-lg p-3 transition-all duration-300" 
                                                 style="background-color: <?php echo $msg['sender_theme_msg'] ?: '#1162d4'; ?>;">
                                                <img src="../<?php echo htmlspecialchars($msg['file_url']); ?>" 
                                                     alt="GIF" 
                                                     class="max-w-xs rounded-lg">
                                                <?php if ($msg['message']): ?>
                                                    <p class="text-[15px] leading-[1.4] font-normal mt-2" style="color: <?php echo $msg['sender_theme_text'] ?: '#ffffff'; ?>;"><?php echo nl2br(htmlspecialchars($msg['message'])); ?></p>
                                                <?php endif; ?>
                                            </div>
                                        <?php elseif ($msg['message_type'] === 'voice'): ?>
                                            <div class="rounded-lg p-3 transition-all duration-300" 
                                                 style="background-color: <?php echo $msg['sender_theme_msg'] ?: '#1162d4'; ?>;">
                                                <div class="flex items-center gap-3">
                                                    <span class="material-symbols-outlined" style="color: <?php echo $msg['sender_theme_text'] ?: '#ffffff'; ?>;">mic</span>
                                                    <span class="text-sm font-normal" style="color: <?php echo $msg['sender_theme_text'] ?: '#ffffff'; ?>;">Voice Message</span>
                                                    <audio src="../<?php echo htmlspecialchars($msg['file_url']); ?>" controls class="text-sm"></audio>
                                                </div>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
// Dark Mode Toggle
function toggleDarkMode() {
    const container = document.getElementById('messages-container');
    const icon = document.getElementById('darkModeIcon');
    const isDark = container.style.backgroundColor === 'rgb(31, 41, 55)' || container.classList.contains('dark-mode');
    
    if (isDark) {
        // Switch to light mode
        container.style.backgroundColor = '#ffffff';
        container.classList.remove('dark-mode');
        icon.textContent = 'dark_mode';
        
        // Update all text colors
        document.querySelectorAll('.dark\\:text-slate-100').forEach(el => {
            el.style.color = '#1e293b';
        });
    } else {
        // Switch to dark mode
        container.style.backgroundColor = '#1f2937';
        container.classList.add('dark-mode');
        icon.textContent = 'light_mode';
        
        // Update all text colors
        document.querySelectorAll('.dark\\:text-slate-100').forEach(el => {
            el.style.color = '#f8fafc';
        });
    }
}

// Sync Themes Function
function syncThemes() {
    // Show loading state
    const button = event.target;
    const originalText = button.innerHTML;
    button.innerHTML = '<span class="material-symbols-outlined text-sm align-middle animate-spin">sync</span> Syncing...';
    button.disabled = true;
    
    // Simulate theme sync (in real app, this would make an API call)
    setTimeout(() => {
        // Get theme colors from first message and apply to all
        const messages = document.querySelectorAll('[data-message-id]');
        if (messages.length > 0) {
            const firstTheme = messages[0].querySelector('.rounded-lg');
            const bgColor = firstTheme.style.backgroundColor;
            const textColor = firstTheme.style.color;
            
            // Apply same theme to all messages
            messages.forEach(msg => {
                const bubble = msg.querySelector('.rounded-lg');
                if (bubble) {
                    bubble.style.backgroundColor = bgColor;
                    bubble.style.color = textColor;
                }
            });
        }
        
        button.innerHTML = '<span class="material-symbols-outlined text-sm align-middle">check</span> Synced!';
        button.classList.remove('bg-blue-600', 'hover:bg-blue-700');
        button.classList.add('bg-green-600');
        
        setTimeout(() => {
            button.innerHTML = originalText;
            button.disabled = false;
            button.classList.remove('bg-green-600');
            button.classList.add('bg-blue-600', 'hover:bg-blue-700');
        }, 2000);
    }, 1500);
}

// Auto-refresh for online status
function updateOnlineStatus() {
    // Fetch latest user status from API
    fetch('../api/user-status.php')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.users) {
                data.users.forEach(user => {
                    const indicator = document.getElementById(`online-indicator-${user.id}`);
                    const statusBadge = document.querySelector(`[data-user-status="${user.id}"]`);
                    
                    if (indicator) {
                        // Update indicator color based on status
                        if (user.current_status === 'online') {
                            indicator.style.backgroundColor = '#10b981'; // green
                        } else if (user.current_status === 'away') {
                            indicator.style.backgroundColor = '#f59e0b'; // yellow
                        } else {
                            indicator.style.backgroundColor = '#6b7280'; // gray
                        }
                    }
                    
                    // Update status badge if exists
                    if (statusBadge) {
                        statusBadge.textContent = user.current_status.charAt(0).toUpperCase() + user.current_status.slice(1);
                        statusBadge.className = statusBadge.className.replace(/bg-\w+-100 text-\w+-700 dark:bg-\w+-900\/20 dark:text-\w+-400/g, 
                            user.current_status === 'online' ? 'bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400' :
                            user.current_status === 'away' ? 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/20 dark:text-yellow-400' :
                            'bg-slate-100 text-slate-700 dark:bg-slate-700 dark:text-slate-400'
                        );
                    }
                });
            }
        })
        .catch(error => console.error('Error updating status:', error));
}

// Update online status every 30 seconds
setInterval(updateOnlineStatus, 30000);

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    updateOnlineStatus();
});
</script>

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