<?php

namespace App\Events;

use App\Models\Message;
use App\Models\Conversation;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class ConversationEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $conversation;
    public $message;

    /**
     * Create a new event instance.
     */
    public function __construct(Conversation $conversation, Message $message)
    {
        $this->conversation = $conversation;
        $this->message = $message;
    }

    public function broadcastAs()
    {
        return 'conversation-event';
    }

    /**
     * Get the channels the event should broadcast on.
     */
    public function broadcastOn()
    {
        $userIds = $this->conversation->participants()->pluck('users.id')->toArray();
        $result = [];
        foreach ($userIds as $userId) {
            $result[] = new Channel('conversations.' . $this->conversation->id . '.' . $userId);
        }
        return $result;
    }
}
