<?php
require_once 'includes/auth.php';
require_once 'includes/header.php';
$chatId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
?>

<div x-data="chatDetail(<?= $chatId ?>)" class="flex flex-col h-[calc(100vh-140px)]">
    
    <!-- Chat Header -->
    <div class="flex items-center justify-between p-4 bg-surface border-b border-gray-700 rounded-t-xl">
        <div class="flex items-center gap-4">
            <a href="chats.php" class="text-gray-400 hover:text-white"><i class="fas fa-arrow-left"></i></a>
            <div>
                <h3 class="text-lg font-medium text-white">Conversation #<span x-text="chatId"></span></h3>
                <div class="text-xs text-gray-400 flex items-center gap-2">
                    <span class="w-2 h-2 bg-green-500 rounded-full animate-pulse"></span> Live Monitor
                </div>
            </div>
        </div>
        <div class="flex items-center gap-3">
             <button @click="refreshMessages()" class="p-2 text-gray-400 hover:text-white"><i class="fas fa-sync-alt"></i></button>
             <button class="p-2 text-red-400 hover:text-red-300 border border-red-500/30 rounded bg-red-500/10 text-xs font-bold uppercase tracking-wide">
                 Force Close
             </button>
        </div>
    </div>

    <!-- Chat Area -->
    <div class="flex-1 bg-darker overflow-hidden flex relative border-x border-gray-700">
        
        <!-- Messages -->
        <div class="flex-1 overflow-y-auto p-6 space-y-4" id="messagesContainer">
            <template x-for="msg in messages" :key="msg.id">
                <div class="flex w-full" :class="msg.sender_id == currentUserId ? 'justify-end' : 'justify-start'">
                    
                    <!-- Avatar (Left) -->
                    <img x-show="msg.sender_id != currentUserId" :src="msg.sender_avatar || 'https://ui-avatars.com/api/?name='+msg.sender_real_name" class="w-8 h-8 rounded-full mr-3 border border-gray-700">
                    
                    <div class="max-w-[70%] group relative">
                        <!-- Sender Name -->
                        <div class="text-[10px] text-gray-500 mb-1 px-1" :class="msg.sender_id == currentUserId ? 'text-right' : 'text-left'">
                            <span x-text="msg.sender_real_name"></span>
                            <span x-show="msg.sender_alias" class="text-primary font-bold ml-1" x-text="'(as \\'' + msg.sender_alias + '\\')'"></span>
                            <span x-show="msg.sender_is_bot == 1" class="text-secondary font-bold ml-1">BOT</span>
                            <span x-show="msg.sent_by_admin_id" class="text-red-400 font-bold ml-1">(ADMIN)</span>
                        </div>

                        <!-- Bubble -->
                        <div class="p-3 rounded-2xl text-sm relative"
                            :class="{
                                'bg-primary text-white rounded-tr-none': msg.sender_id == currentUserId,
                                'bg-surface text-gray-200 border border-gray-700 rounded-tl-none': msg.sender_id != currentUserId
                            }">
                            <p x-text="msg.body_text"></p>
                            
                            <!-- Admin Actions (Hover) -->
                            <div class="absolute -top-3 -right-3 hidden group-hover:flex gap-1 bg-dark border border-gray-600 rounded-full p-1 shadow-lg z-10">
                                <button @click="deleteMessage(msg.id)" class="w-6 h-6 flex items-center justify-center rounded-full bg-red-500/20 text-red-400 hover:bg-red-500 hover:text-white transition-colors text-xs" title="Delete">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </div>

                        <!-- Time -->
                        <div class="text-[10px] text-gray-600 mt-1 px-1" :class="msg.sender_id == currentUserId ? 'text-right' : 'text-left'" x-text="formatTime(msg.created_at)"></div>
                    </div>

                    <!-- Avatar (Right) -->
                    <img x-show="msg.sender_id == currentUserId" :src="msg.sender_avatar || 'https://ui-avatars.com/api/?name='+msg.sender_real_name" class="w-8 h-8 rounded-full ml-3 border border-gray-700">
                </div>
            </template>
            
            <div x-show="loading" class="flex justify-center py-4">
                <i class="fas fa-circle-notch fa-spin text-gray-600"></i>
            </div>
        </div>
    </div>

    <!-- Input Area -->
    <div class="bg-surface p-4 border-t border-b border-x border-gray-700 rounded-b-xl">
        <div class="flex flex-col gap-3">
            
            <!-- Send As Control -->
            <div class="flex items-center gap-3 text-xs text-gray-400">
                <span>Send as:</span>
                <select x-model="sendAsBotId" class="bg-dark border border-gray-600 rounded px-2 py-1 focus:outline-none focus:border-primary text-white">
                    <option value="">System Message</option>
                    <template x-for="bot in bots" :key="bot.id">
                        <option :value="bot.id" x-text="bot.username + ' (Bot)'"></option>
                    </template>
                </select>
            </div>

            <div class="flex items-center gap-3">
                <div class="relative flex-1">
                    <input x-model="newMessage" @keydown.enter="sendMessage()" type="text" placeholder="Type a message..." class="w-full bg-dark border border-gray-600 rounded-lg pl-4 pr-10 py-3 text-gray-200 focus:outline-none focus:border-primary">
                    <button class="absolute right-3 top-3 text-gray-500 hover:text-white">
                        <i class="fas fa-paperclip"></i>
                    </button>
                </div>
                <button @click="sendMessage()" class="bg-primary hover:bg-indigo-600 text-white px-6 py-3 rounded-lg font-medium transition-colors shadow-lg shadow-primary/20">
                    <i class="fas fa-paper-plane"></i>
                </button>
            </div>
        </div>
    </div>

</div>

<script>
function chatDetail(chatId) {
    return {
        chatId: chatId,
        messages: [],
        bots: [], // List of bots available to impersonate
        currentUserId: null, // Logic to determine "right" side. Usually Admin takes right side if acting as someone.
        newMessage: '',
        sendAsBotId: '',
        loading: false,

        init() {
            this.fetchMessages();
            this.fetchBots(); // To populate "Send as" dropdown
            setInterval(() => this.fetchMessages(true), 3000); // Fast polling for "Live" feel
        },

        fetchMessages(silent = false) {
            if (!silent) this.loading = true;
            fetch(`/backend-php/public/api/admin/conversations/${this.chatId}/messages`)
                .then(res => res.json())
                .then(data => {
                    this.messages = data;
                    if (!silent) {
                        this.loading = false;
                        this.scrollToBottom();
                    }
                    
                    // Determine layout side. If we are impersonating a bot, that bot should be on right?
                    // Or standard view: User A Left, User B Right?
                    // Let's assume User A is Left, User B is Right for now.
                    // But for "Chat" UI, we usually want "Me" on the right.
                    // Since Admin is observing, maybe strictly Time based is better, but bubbles help.
                    // Let's set currentUserId to the 'User B' of the conversation arbitrarily or handle dynamically.
                    if (data.length > 0 && !this.currentUserId) {
                        // Just pick the second participant as "Right" side for visual balance
                        // Or if one is a bot, make the bot "Right" so Admin feels like the bot.
                        const bot = data.find(m => m.sender_is_bot == 1);
                        if (bot) this.currentUserId = bot.sender_id;
                        else this.currentUserId = data[0].sender_id; // Fallback
                    }
                });
        },
        
        fetchBots() {
            // We need an endpoint to get all bots for the dropdown.
            // Re-using seed-users endpoint or similar.
            fetch('/backend-php/public/api/admin/seed-users')
                .then(res => res.json())
                .then(data => {
                    this.bots = data;
                    // Auto-select if one of the participants is a bot
                    // This logic would require knowing participants first.
                });
        },

        sendMessage() {
            if (!this.newMessage.trim()) return;
            
            // Logic to find recipient. 
            // In a conversation, if I send as User A, recipient is User B.
            // I need to know participants.
            // The API `sendMessageAsAdmin` expects `recipient_id`.
            // I should probably update `sendMessageAsAdmin` to accept `conversation_id` directly to simplify.
            // Let's assume I updated it or I can derive it.
            
            // For now, simpler: Admin sends message to the conversation.
            // Backend handles "who receives".
            
            fetch('/backend-php/public/api/admin/messages/send', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    conversation_id: this.chatId, // Backend needs to support this!
                    body_text: this.newMessage,
                    as_bot_id: this.sendAsBotId
                })
            }).then(() => {
                this.newMessage = '';
                this.fetchMessages(true);
                this.scrollToBottom();
            });
        },

        deleteMessage(id) {
            if(!confirm('Delete this message?')) return;
            fetch(`/backend-php/public/api/admin/messages/${id}`, { method: 'DELETE' })
                .then(() => this.fetchMessages(true));
        },

        scrollToBottom() {
            setTimeout(() => {
                const container = document.getElementById('messagesContainer');
                container.scrollTop = container.scrollHeight;
            }, 100);
        },

        formatTime(dateStr) {
            return new Date(dateStr).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
        }
    }
}
</script>

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