<?php

use App\Models\Booking;
use App\Models\Trip;
use Illuminate\Support\Facades\Broadcast;

/*
|--------------------------------------------------------------------------
| Broadcast Channels — NjiaPanda
|--------------------------------------------------------------------------
|
| route.{from}.{to}.{date}  — Public channel: anyone can subscribe to see
|                              live listings on a given corridor/date.
|
| trip.{tripId}              — Private: only the driver and booked riders.
|
| trip.{tripId}.live         — Private: same — receives GPS pings.
|
*/

// Public route feed — no auth needed
Broadcast::channel('route.{from}.{to}.{date}', fn() => true);

// Trip channel — driver or a confirmed/pending rider
Broadcast::channel('trip.{tripId}', function ($user, int $tripId) {
    $trip = Trip::find($tripId);
    if (!$trip) {
        return false;
    }
    if ($trip->driver_id === $user->id) {
        return true;
    }
    return Booking::where('trip_id', $tripId)
        ->where('rider_id', $user->id)
        ->whereIn('status', ['pending', 'confirmed', 'completed'])
        ->exists();
});

// Live GPS channel — same rules as trip channel
Broadcast::channel('trip.{tripId}.live', function ($user, int $tripId) {
    $trip = Trip::find($tripId);
    if (!$trip) {
        return false;
    }
    if ($trip->driver_id === $user->id) {
        return true;
    }
    return Booking::where('trip_id', $tripId)
        ->where('rider_id', $user->id)
        ->whereIn('status', ['confirmed', 'completed'])
        ->exists();
});
