<?php

use App\Models\Appointment;
use App\Models\Cart;
use App\Models\Patient;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\Facades\File;

/*
|--------------------------------------------------------------------------
| 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.
|
*/

Broadcast::channel('App.Models.User.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});
Broadcast::channel('dhkjkiplqe84sdaqf17nqg', function ($user) {
    if ($user instanceof Patient) {
        $appointments = Appointment::select("appointments.*")
            ->where("appointments.patient_id", $user->id)
            ->orderBy('appointments.created_at', 'desc')
            ->first();
        $cart = Cart::where("appointment_id", $appointments->id)->first();
        if (!$cart)
            $card_id = null;
        else
            $card_id =  $cart->id;
        $filePath = public_path("assets/profiles/{$user->id}.png");

        if (File::exists($filePath)) {
            $user->url = "/assets/profiles/{$user->id}.png";
        } else {
            $user->url = null;
        }
        return [
            'id' => $user->id,
            'name' => $user->first_name . ' ' . $user->last_name,
            'address' => $user->address,
            'city' => $user->city,
            'state' => $user->state,
            'country' => $user->country,
            'url' => $user->url,
            'zip_code' => $user->zip_code,
            'type' => $user instanceof Patient ? "patient" : "agent",
            'time' => time(),
            'appointment' => $appointments,
            'order_id' => $card_id

        ];
    } else {
        $appointments = Appointment::select("appointments.*")
            //->where("appointments.telemed_pros_id", $user->id)
            ->orderBy('appointments.created_at', 'desc')
            ->first();
        $cart = Cart::where("appointment_id", $appointments->id)->first();
        if (!$cart)
            $card_id = null;
        else
            $card_id =  $cart->id;
        return [
            'id' => $user->id,
            'name' => $user->name,
            'type' => $user instanceof Patient ? "patient" : "agent",
            'time' => time(),
            'appointments' => $appointments,
            'order_id' =>   $card_id
        ];
    }
});
/* return Auth::guard('agent')->check(); */
Broadcast::channel('patient-{id}', function ($user, $id) {
    return !!$user;
});
Broadcast::channel('patient-end-call-{id}', function ($user, $id) {
    return !!$user;
});
