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

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

$pageTitle = 'Chat Monitor';
$db = getDB();

// Get all active conversations with recent messages
$stmt = $db->query("
    SELECT 
        u1.id as user1_id, u1.name as user1_name, u1.unique_id as user1_unique, u1.profile_photo as user1_photo,
        u2.id as user2_id, u2.name as user2_name, u2.unique_id as user2_unique, u2.profile_photo as user2_photo,
        m.message, m.message_type, m.created_at,
        COUNT(*) as message_count
    FROM messages m
    JOIN users u1 ON (m.sender_id = u1.id OR m.receiver_id = u1.id)
    JOIN users u2 ON (m.sender_id = u2.id OR m.receiver_id = u2.id)
    WHERE u1.id < u2.id
    AND ((m.sender_id = u1.id AND m.receiver_id = u2.id) OR (m.sender_id = u2.id AND m.receiver_id = u1.id))
    AND m.is_deleted_for_all = 0
    GROUP BY u1.id, u2.id
    ORDER BY m.created_at DESC
    LIMIT 50
");
$conversations = $stmt->fetchAll();

// Get specific chat if selected
$selectedUser1 = isset($_GET['user1']) ? intval($_GET['user1']) : 0;
$selectedUser2 = isset($_GET['user2']) ? intval($_GET['user2']) : 0;
$chatMessages = [];

if ($selectedUser1 && $selectedUser2) {
    $stmt = $db->prepare("
        SELECT m.*, 
            sender.name as sender_name, sender.unique_id as sender_unique,
            receiver.name as receiver_name, receiver.unique_id as receiver_unique
        FROM messages m
        JOIN users sender ON m.sender_id = sender.id
        JOIN users receiver ON m.receiver_id = receiver.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 DESC
        LIMIT 100
    ");
    $stmt->execute([$selectedUser1, $selectedUser2, $selectedUser2, $selectedUser1]);
    $chatMessages = $stmt->fetchAll();
}

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

<div class="min-h-screen bg-slate-50 dark:bg-slate-900">
    <!-- Admin Header -->
    <header class="bg-white dark:bg-slate-800 border-b border-slate-200 dark:border-slate-700 sticky top-0 z-20">
        <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="dashboard.php" class="text-slate-600 dark:text-slate-400 hover:text-primary">
                        <span class="material-symbols-outlined">arrow_back</span>
                    </a>
                    <div class="text-primary flex items-center gap-2">
                        <span class="material-symbols-outlined text-2xl">chat</span>
                        <span class="font-bold text-lg">Chat Monitor</span>
                    </div>
                </div>
                <div class="text-sm text-slate-500">
                    <?php echo count($conversations); ?> active conversations
                </div>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <?php if (!$selectedUser1 || !$selectedUser2): ?>
        <!-- Conversations List -->
        <div class="bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 overflow-hidden">
            <div class="p-4 border-b border-slate-200 dark:border-slate-700">
                <h3 class="font-semibold text-slate-900 dark:text-white">Active Conversations</h3>
                <p class="text-sm text-slate-500">Click on a conversation to view messages</p>
            </div>
            <div class="divide-y divide-slate-200 dark:divide-slate-700">
                <?php if (empty($conversations)): ?>
                <div class="p-8 text-center">
                    <span class="material-symbols-outlined text-4xl text-slate-300 mb-2">chat_bubble_outline</span>
                    <p class="text-slate-500">No active conversations</p>
                </div>
                <?php else: ?>
                    <?php foreach ($conversations as $conv): ?>
                    <a href="?user1=<?php echo $conv['user1_id']; ?>&user2=<?php echo $conv['user2_id']; ?>" class="flex items-center justify-between p-4 hover:bg-slate-50 dark:hover:bg-slate-700/50 transition-colors">
                        <div class="flex items-center gap-4">
                            <div class="flex -space-x-2">
                                <?php if ($conv['user1_photo']): ?>
                                <img src="../uploads/images/<?php echo htmlspecialchars($conv['user1_photo']); ?>" class="w-10 h-10 rounded-full border-2 border-white dark:border-slate-800 object-cover">
                                <?php else: ?>
                                <div class="w-10 h-10 rounded-full bg-primary/10 border-2 border-white dark:border-slate-800 flex items-center justify-center">
                                    <span class="material-symbols-outlined text-primary text-sm">person</span>
                                </div>
                                <?php endif; ?>
                                <?php if ($conv['user2_photo']): ?>
                                <img src="../uploads/images/<?php echo htmlspecialchars($conv['user2_photo']); ?>" class="w-10 h-10 rounded-full border-2 border-white dark:border-slate-800 object-cover">
                                <?php else: ?>
                                <div class="w-10 h-10 rounded-full bg-slate-200 dark:bg-slate-700 border-2 border-white dark:border-slate-800 flex items-center justify-center">
                                    <span class="material-symbols-outlined text-slate-500 text-sm">person</span>
                                </div>
                                <?php endif; ?>
                            </div>
                            <div>
                                <p class="font-medium text-slate-900 dark:text-white">
                                    <?php echo htmlspecialchars($conv['user1_name']); ?> & <?php echo htmlspecialchars($conv['user2_name']); ?>
                                </p>
                                <p class="text-sm text-slate-500">
                                    @<?php echo htmlspecialchars($conv['user1_unique']); ?> & @<?php echo htmlspecialchars($conv['user2_unique']); ?>
                                </p>
                                <p class="text-xs text-slate-400 mt-1">
                                    <?php echo $conv['message_count']; ?> messages
                                </p>
                            </div>
                        </div>
                        <span class="material-symbols-outlined text-slate-400">chevron_right</span>
                    </a>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
        <?php else: ?>
        <!-- Chat View -->
        <div class="mb-4">
            <a href="chats.php" class="text-primary hover:underline flex items-center gap-1">
                <span class="material-symbols-outlined text-sm">arrow_back</span>
                Back to conversations
            </a>
        </div>

        <!-- Chat Messages -->
        <div class="bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 overflow-hidden">
            <div class="p-4 border-b border-slate-200 dark:border-slate-700">
                <h3 class="font-semibold text-slate-900 dark:text-white">Conversation</h3>
            </div>
            <div class="max-h-[600px] overflow-y-auto p-4 space-y-4">
                <?php if (empty($chatMessages)): ?>
                <p class="text-center text-slate-500">No messages in this conversation</p>
                <?php else: ?>
                    <?php foreach (array_reverse($chatMessages) as $msg): ?>
                    <div class="flex items-start gap-3 <?php echo $msg['sender_id'] == $selectedUser1 ? '' : 'flex-row-reverse'; ?>">
                        <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center shrink-0">
                            <span class="material-symbols-outlined text-primary text-sm">person</span>
                        </div>
                        <div class="flex-1 <?php echo $msg['sender_id'] == $selectedUser1 ? '' : 'text-right'; ?>">
                            <p class="text-xs text-slate-500 mb-1">
                                <?php echo htmlspecialchars($msg['sender_name']); ?> (@<?php echo htmlspecialchars($msg['sender_unique']); ?>)
                                <span class="mx-1">•</span>
                                <?php echo formatDateTime($msg['created_at']); ?>
                            </p>
                            <div class="inline-block bg-slate-100 dark:bg-slate-700 rounded-lg px-4 py-2 max-w-[80%] text-left">
                                <?php if ($msg['message_type'] === 'image'): ?>
                                <img src="../<?php echo htmlspecialchars($msg['file_url']); ?>" class="max-w-xs rounded-lg mb-2">
                                <?php endif; ?>
                                <?php if ($msg['message_type'] === 'video'): ?>
                                <video src="../<?php echo htmlspecialchars($msg['file_url']); ?>" controls class="max-w-xs rounded-lg mb-2"></video>
                                <?php endif; ?>
                                <?php if ($msg['message']): ?>
                                <p class="text-sm text-slate-900 dark:text-white"><?php echo nl2br(htmlspecialchars($msg['message'])); ?></p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>

        <!-- Actions -->
        <div class="mt-4 flex gap-3">
            <form method="POST" action="chat-action.php" onsubmit="return confirm('Delete all messages in this conversation? This action cannot be undone.')">
                <input type="hidden" name="action" value="delete_conversation">
                <input type="hidden" name="user1" value="<?php echo $selectedUser1; ?>">
                <input type="hidden" name="user2" value="<?php echo $selectedUser2; ?>">
                <button type="submit" class="px-4 py-2 bg-red-500 text-white rounded-lg font-medium hover:bg-red-600 transition-colors flex items-center gap-2">
                    <span class="material-symbols-outlined text-sm">delete</span>
                    Delete Conversation
                </button>
            </form>
            <form method="POST" action="export-chat.php" target="_blank">
                <input type="hidden" name="user1" value="<?php echo $selectedUser1; ?>">
                <input type="hidden" name="user2" value="<?php echo $selectedUser2; ?>">
                <button type="submit" class="px-4 py-2 bg-slate-200 dark:bg-slate-700 text-slate-700 dark:text-slate-300 rounded-lg font-medium hover:bg-slate-300 transition-colors flex items-center gap-2">
                    <span class="material-symbols-outlined text-sm">download</span>
                    Export
                </button>
            </form>
        </div>
        <?php endif; ?>
    </main>
</div>

<?php $hideFooter = true; include '../includes/footer.php'; ?>
