<template>
    <div>
        <div v-for="message in messages" :key="message.id">
            <p><strong>{{ message.sender.name }}:</strong> {{ message.message }}</p>
        </div>
        <input v-model="newMessage" placeholder="Type a message..." />
        <button @click="sendMessage">Send</button>
    </div>
</template>

<script>
import Echo from 'laravel-echo';

export default {
    data() {
        return {
            messages: [],
            newMessage: '',
            receiverId: 1, // Set to the receiver's ID dynamically
        };
    },
    mounted() {
        this.getMessages();

        // Listen for new messages using Pusher
        Echo.channel(`chat.${this.receiverId}`)
            .listen('MessageSent', (event) => {
                this.messages.push(event.message); // Add new message dynamically
            });
    },
    methods: {
        async getMessages() {
            const response = await axios.get(`/api/messages/${this.receiverId}`);
            this.messages = response.data.messages;
        },
        async sendMessage() {
            await axios.post('/api/messages/send', {
                receiver_id: this.receiverId,
                message: this.newMessage,
            });
            this.newMessage = '';
        },
    },
};
</script>
