@extends('layouts.admin')

@section('title', 'Live Chat')

@section('content')
<div class="container mx-auto px-4 py-6">
    <h1 class="text-2xl font-semibold mb-4">Live Chat</h1>

    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
        <!-- Users List -->
        <div class="bg-white rounded-lg shadow-md p-4">
            <h2 class="text-lg font-semibold mb-4">Users</h2>
            <div class="space-y-2">
                @foreach($users as $user)
                    <div class="p-3 hover:bg-gray-100 rounded cursor-pointer" onclick="selectUser({{ $user->id }}, '{{ $user->name }}')">
                        <div class="flex items-center">
                            <div class="w-10 h-10 rounded-full bg-blue-500 flex items-center justify-center text-white font-bold mr-3">
                                {{ strtoupper(substr($user->name, 0, 2)) }}
                            </div>
                            <div>
                                <div class="font-semibold">{{ $user->name }}</div>
                                <div class="text-sm text-gray-500">{{ $user->email }}</div>
                            </div>
                        </div>
                    </div>
                @endforeach
            </div>
        </div>

        <!-- Chat Area -->
        <div class="md:col-span-2 bg-white rounded-lg shadow-md flex flex-col" style="height: 600px;">
            <div class="p-4 border-b">
                <h2 class="text-lg font-semibold" id="chatUserName">Select a user to start chatting</h2>
            </div>

            <div class="flex-1 p-4 overflow-y-auto" id="chatMessages">
                @foreach($messages as $message)
                    <div class="mb-4 {{ $message->sender_id == auth()->id() ? 'text-right' : '' }}">
                        <div class="inline-block max-w-xs lg:max-w-md px-4 py-2 rounded-lg {{ $message->sender_id == auth()->id() ? 'bg-blue-500 text-white' : 'bg-gray-200' }}">
                            <div class="text-sm font-semibold mb-1">{{ $message->sender->name }}</div>
                            <div>{{ $message->message }}</div>
                            <div class="text-xs mt-1 opacity-75">{{ $message->created_at->format('H:i') }}</div>
                        </div>
                    </div>
                @endforeach
            </div>

            <form action="{{ route('admin.marketing.live-chat.send') }}" method="POST" class="p-4 border-t" id="chatForm">
                @csrf
                <input type="hidden" name="receiver_id" id="receiverId">
                <div class="flex gap-2">
                    <input type="text" name="message" id="messageInput" placeholder="Type a message..." class="flex-1 px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                    <button type="submit" class="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700">Send</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
let selectedUserId = null;

function selectUser(userId, userName) {
    selectedUserId = userId;
    document.getElementById('receiverId').value = userId;
    document.getElementById('chatUserName').textContent = userName;
    loadMessages(userId);
}

function loadMessages(userId) {
    fetch(`/admin/marketing/live-chat/messages/${userId}`)
        .then(response => response.json())
        .then(messages => {
            const chatMessages = document.getElementById('chatMessages');
            chatMessages.innerHTML = '';
            messages.forEach(message => {
                const isMe = message.sender_id == {{ auth()->id() }};
                const messageDiv = document.createElement('div');
                messageDiv.className = `mb-4 ${isMe ? 'text-right' : ''}`;
                messageDiv.innerHTML = `
                    <div class="inline-block max-w-xs lg:max-w-md px-4 py-2 rounded-lg ${isMe ? 'bg-blue-500 text-white' : 'bg-gray-200'}">
                        <div class="text-sm font-semibold mb-1">${message.sender.name}</div>
                        <div>${message.message}</div>
                        <div class="text-xs mt-1 opacity-75">${new Date(message.created_at).toLocaleTimeString('en-US', {hour: '2-digit', minute:'2-digit'})}</div>
                    </div>
                `;
                chatMessages.appendChild(messageDiv);
            });
            chatMessages.scrollTop = chatMessages.scrollHeight;
        });
}

// Auto-refresh messages every 5 seconds
setInterval(() => {
    if (selectedUserId) {
        loadMessages(selectedUserId);
    }
}, 5000);
</script>
@endsection

