<?php

use App\Models\User;
use Illuminate\Support\Facades\Broadcast;

/*
|--------------------------------------------------------------------------
| Broadcast Channels
|--------------------------------------------------------------------------
|
| Here you may register all of the event broadcasting channels that your
| application supports. The given channel authorization callbacks are
| used to check if an authenticated user can listen to the channel.
|
*/

// Private channel for individual users (notifications, messages, etc.)
Broadcast::channel('App.Models.User.{id}', function (User $user, int $id) {
    return $user->id === $id;
});

// Private channel for coaches
Broadcast::channel('coach.{coachId}', function (User $user, int $coachId) {
    return $user->hasRole('coach') && $user->id === $coachId;
});

// Private channel for clients
Broadcast::channel('client.{clientId}', function (User $user, int $clientId) {
    return $user->hasRole('client') && $user->client && $user->client->id === $clientId;
});

// Private channel for coach-client chat
Broadcast::channel('chat.{coachId}.{clientId}', function (User $user, int $coachId, int $clientId) {
    if ($user->hasRole('coach') && $user->id === $coachId) {
        return ['id' => $user->id, 'name' => $user->name, 'role' => 'coach'];
    }

    if ($user->hasRole('client') && $user->client && $user->client->id === $clientId) {
        return ['id' => $user->id, 'name' => $user->name, 'role' => 'client'];
    }

    return false;
});

// Private channel for admin-coach chat
Broadcast::channel('admin-chat.{adminId}.{coachId}', function (User $user, int $adminId, int $coachId) {
    if ($user->hasRole('admin') && $user->id === $adminId) {
        return ['id' => $user->id, 'name' => $user->name, 'role' => 'admin'];
    }

    if ($user->hasRole('coach') && $user->id === $coachId) {
        return ['id' => $user->id, 'name' => $user->name, 'role' => 'coach'];
    }

    return false;
});

// Admin channel for system notifications
Broadcast::channel('admin', function (User $user) {
    return $user->hasRole('admin');
});
