<?php
require_once '../config/db.php';
require_once 'layout.php';

header('Content-Type: text/html; charset=utf-8');

// Fetch Messages as "Chats" (since we don't have a robust chat groupings table yet populated)
// Group by chat_id to simulate chat rooms list
try {
    // This query gets the latest message for each chat_id available
    $sql = "SELECT m.*, u.username, u.email, 
            (SELECT COUNT(*) FROM messages WHERE chat_id = m.chat_id) as total_msgs
            FROM messages m
            JOIN users u ON m.sender_id = u.id
            WHERE m.id IN (
                SELECT MAX(id) FROM messages GROUP BY chat_id
            )
            ORDER BY m.created_at DESC";
    
    $stmt = $pdo->query($sql);
    $chats = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    die("Error DB: " . $e->getMessage());
}

renderAdminSidebar('chats');
?>

<div class="grid grid-cols-1 lg:grid-cols-3 gap-6 h-[calc(100vh-140px)]">
    
    <!-- Chat List -->
    <div class="col-span-1 bg-dark-800 rounded-2xl border border-dark-700 flex flex-col shadow-xl overflow-hidden">
        <div class="p-4 border-b border-dark-700">
            <h3 class="font-bold text-white mb-2">Chats Activos</h3>
            <div class="relative">
                <i class="fas fa-search absolute left-3 top-3 text-gray-500 text-xs"></i>
                <input type="text" placeholder="Buscar chat o usuarios..." class="w-full bg-dark-900 border border-dark-700 rounded-lg py-2 pl-8 pr-4 text-sm text-white focus:border-brand-500 focus:ring-0">
            </div>
        </div>
        <div class="flex-1 overflow-y-auto">
            <?php if (count($chats) > 0): ?>
                <?php foreach ($chats as $chat): ?>
                <div class="p-4 border-b border-dark-700 hover:bg-dark-700/50 cursor-pointer transition group">
                    <div class="flex justify-between items-start mb-1">
                        <h4 class="font-bold text-white text-sm">
                            <?php echo $chat['chat_id'] == 1 ? 'Global Chat 🌎' : 'Chat #' . $chat['chat_id']; ?>
                        </h4>
                        <span class="text-xs text-gray-500"><?php echo date('H:i', strtotime($chat['created_at'])); ?></span>
                    </div>
                    <p class="text-xs text-gray-400 truncate mb-2">
                        <span class="text-brand-400 font-medium"><?php echo htmlspecialchars($chat['username']); ?>:</span> 
                        <?php echo htmlspecialchars(substr($chat['content'], 0, 50)); ?>...
                    </p>
                    <div class="flex items-center justify-between">
                         <span class="px-2 py-0.5 rounded-full bg-dark-900 text-gray-500 text-[10px] border border-dark-700">
                            <?php echo $chat['total_msgs']; ?> msgs
                        </span>
                        <?php if($chat['type'] === 'gift' || $chat['type'] === 'payment'): ?>
                            <span class="text-xs text-yellow-500"><i class="fas fa-gift"></i> Regalo</span>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="p-8 text-center text-gray-500">
                    <i class="fas fa-comment-slash text-3xl mb-2 opacity-30"></i>
                    <p>No hay mensajes recientes.</p>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Active Chat View (Placeholder/Mock) -->
    <div class="col-span-1 lg:col-span-2 bg-dark-800 rounded-2xl border border-dark-700 flex flex-col shadow-xl overflow-hidden relative">
        <!-- Header -->
        <div class="p-4 border-b border-dark-700 flex justify-between items-center bg-dark-800/80 backdrop-blur">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-full bg-brand-600 flex items-center justify-center text-white font-bold">G</div>
                <div>
                    <h3 class="font-bold text-white">Global Chat 🌎</h3>
                    <p class="text-xs text-green-400">● En vivo</p>
                </div>
            </div>
            <div class="flex gap-2">
                <button class="p-2 text-gray-400 hover:text-white hover:bg-dark-700 rounded-lg transition" title="Borrar Historial">
                    <i class="fas fa-trash-alt"></i>
                </button>
                <button class="p-2 text-gray-400 hover:text-red-400 hover:bg-dark-700 rounded-lg transition" title="Bloquear Chat">
                    <i class="fas fa-ban"></i>
                </button>
            </div>
        </div>

        <!-- Messages Area (Static for Admin View) -->
        <div class="flex-1 overflow-y-auto p-6 space-y-4 bg-dark-900/50">
            <!-- Mocked Messages for Visualization -->
            <div class="flex justify-center my-4">
                <span class="text-xs text-gray-600 bg-dark-900 px-3 py-1 rounded-full border border-dark-700">Hoy</span>
            </div>
            
            <?php 
            // Fetch last 10 messages of Chat 1 for realistic view
            $stmt = $pdo->prepare("SELECT m.*, u.username FROM messages m JOIN users u ON m.sender_id = u.id WHERE chat_id = 1 ORDER BY created_at DESC LIMIT 10");
            $stmt->execute();
            $msgs = array_reverse($stmt->fetchAll(PDO::FETCH_ASSOC));
            
            foreach($msgs as $msg): 
                $isSystem = $msg['type'] === 'gift' || $msg['type'] === 'payment';
            ?>
                <div class="flex gap-3 group">
                    <div class="w-8 h-8 rounded-full bg-gray-700 flex-shrink-0 flex items-center justify-center text-xs text-white font-bold">
                        <?php echo strtoupper(substr($msg['username'], 0, 1)); ?>
                    </div>
                    <div class="flex-1">
                        <div class="flex items-baseline gap-2">
                            <span class="text-sm font-bold text-gray-300"><?php echo htmlspecialchars($msg['username']); ?></span>
                            <span class="text-[10px] text-gray-600"><?php echo date('H:i', strtotime($msg['created_at'])); ?></span>
                        </div>
                        
                        <?php if($isSystem): 
                            $meta = json_decode($msg['meta_data'] ?? '{}');
                        ?>
                            <div class="mt-1 inline-block bg-gradient-to-r from-brand-900/50 to-purple-900/50 border border-brand-500/30 rounded-lg p-3 text-sm text-brand-200">
                                <i class="fas fa-gift mr-1 text-yellow-400"></i> 
                                <b><?php echo $msg['type'] === 'gift' ? 'Envió un Regalo' : 'Envió un Pago'; ?></b>
                                <?php if(isset($meta->amount)): ?>
                                    <span class="block text-xs mt-1 text-brand-300 opacity-80">Monto: <?php echo $meta->amount; ?> 💎</span>
                                <?php endif; ?>
                            </div>
                        <?php else: ?>
                            <p class="text-sm text-gray-400 mt-0.5"><?php echo htmlspecialchars($msg['content']); ?></p>
                        <?php endif; ?>
                        
                        <div class="opacity-0 group-hover:opacity-100 transition-opacity mt-1 flex gap-2">
                            <button class="text-[10px] text-red-500 hover:underline">Borrar</button>
                            <button class="text-[10px] text-yellow-500 hover:underline">Warn</button>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>

        </div>

        <!-- Admin Input -->
        <div class="p-4 border-t border-dark-700 bg-dark-800">
            <div class="flex gap-2">
                <input type="text" placeholder="Enviar mensaje como Sistema..." class="flex-1 bg-dark-900 border border-dark-700 rounded-xl px-4 py-2.5 text-sm text-white focus:border-brand-500 focus:ring-0">
                <button class="bg-brand-600 hover:bg-brand-700 text-white rounded-xl px-4 transition">
                    <i class="fas fa-paper-plane"></i>
                </button>
            </div>
        </div>
    </div>
</div>

<?php renderAdminFooter(); ?>
