<?php

namespace App\Events;

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

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

    public $conversation;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Conversation $conversation)
    {
        $this->conversation = $conversation;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        // Broadcast to ticket channel if conversation has a ticket
        if ($this->conversation->ticket_id) {
            return new \Illuminate\Broadcasting\PrivateChannel('ticket.' . $this->conversation->ticket_id);
        }
        
        // Fallback to conversation channel
        return new Channel('conversation.' . $this->conversation->id);
    }

    /**
     * Get the data to broadcast.
     *
     * @return array
     */
    public function broadcastWith()
    {
        return [
            'conversation' => [
                'id' => $this->conversation->id,
                'ticket_id' => $this->conversation->ticket_id,
                'title' => $this->conversation->title,
                'type' => $this->conversation->type,
                'status' => $this->conversation->status,
                'updated_at' => $this->conversation->updated_at,
            ]
        ];
    }

    /**
     * The event's broadcast name.
     *
     * @return string
     */
    public function broadcastAs()
    {
        return 'ConversationUpdated';
    }
}
