<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use App\Models\GameSession;
use Illuminate\Support\Facades\Log;

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

    public $session;

    public function __construct(GameSession $session)
    {
        $this->session = $session->load(['user', 'partner', 'game']);
        
        // إضافة logging للتأكد من إنشاء Event
        Log::info("🎉 PartnerJoined Event created for session {$session->id}");
    }

    /**
     * Get the channels the event should broadcast on.
     */
    public function broadcastOn(): array
    {
        $channel = 'game-session.' . $this->session->id;
        Log::info("📡 Broadcasting PartnerJoined on channel: {$channel}");
        
        return [
            new PrivateChannel($channel),
        ];
    }

    /**
     * The event's broadcast name.
     */
    public function broadcastAs()
    {
        Log::info("📡 Broadcasting as: partner.joined");
        return 'partner.joined';
    }

    /**
     * Get the data to broadcast.
     */
    public function broadcastWith()
    {
        $data = [
            'session' => $this->session,
            'game' => $this->session->game,
            'message' => 'تم انضمام الشريك بنجاح!',
            'player1' => $this->session->user,
            'player2' => $this->session->partner,
        ];
        
        Log::info("📡 Broadcasting data: " . json_encode([
            'session_id' => $this->session->id,
            'status' => $this->session->status,
            'player1_name' => $this->session->user->name,
            'player2_name' => $this->session->partner->name ?? 'Unknown',
        ]));
        
        return $data;
    }

    /**
     * Determine if this event should broadcast.
     */
    public function broadcastWhen()
    {
        $shouldBroadcast = $this->session->status === 'active' && 
                          $this->session->partner_id !== null;
        
        Log::info("📡 Should broadcast: " . ($shouldBroadcast ? 'YES' : 'NO'));
        
        return $shouldBroadcast;
    }
}