<?php

namespace App\Events;

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

class MessageSent implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;

    public function __construct(Message $message)
    {
        $this->message = $message;
    }

    public function broadcastOn()
    {
        $channels = [
            new PrivateChannel('chat.' . $this->message->conversation_id)
        ];

        // Add personal notification channels for both sender and receiver
        if ($this->message->sender_type === 'emp') {
            $channels[] = new PrivateChannel('emp.' . $this->message->sender_id);
        } else {
            $channels[] = new PrivateChannel('user.' . $this->message->sender_id);
        }

        if ($this->message->receiver_type === 'emp') {
            $channels[] = new PrivateChannel('emp.' . $this->message->receiver_id);
        } else {
            $channels[] = new PrivateChannel('user.' . $this->message->receiver_id);
        }

        return $channels;
    }

    public function broadcastAs()
    {
        return 'MessageSent';
    }

    public function broadcastWith()
    {
        return [
            'id' => $this->message->id,
            'message' => $this->message->message,
            'sender_id' => $this->message->sender_id,
            'sender_type' => $this->message->sender_type,
            'receiver_id' => $this->message->receiver_id,
            'receiver_type' => $this->message->receiver_type,
            'conversation_id' => $this->message->conversation_id,
            'message_type' => $this->message->message_type,
            'attachment_path' => $this->message->attachment_path,
            'is_read' => $this->message->is_read,
            'created_at' => now()->format('Y-m-d h:i:s A'),
            'sender' => [
                'id' => $this->message->sender_id,
                'name' => $this->message->getSenderName(),
                'image' => $this->message->getSenderImage()
            ]
        ];
    }
}
