<?php

namespace App\Listeners;

use App\Events\ReservationReceived;
use App\Http\Controllers\DashboardController;
use App\Models\User;
use App\Notifications\NewReservationForRestaurant;
use App\Queue\UsesDatabaseQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Notification;

class SendReservationListener implements ShouldQueue
{
    use InteractsWithQueue, UsesDatabaseQueue;

    /**
     * Create the event listener.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle(ReservationReceived $event): void
    {
        $users = User::role('Admin_'.$event->reservation->branch->restaurant_id)->where('restaurant_id', $event->reservation->branch->restaurant->id)->get();

        try {
            Notification::send($users, new NewReservationForRestaurant($event->reservation));
        } catch (\Exception $e) {
            \Log::error('Error sending new reservation notification: ' . $e->getMessage());
        }

        $pushNotification = new DashboardController();
        $pushUsersIds = [$users->pluck('id')->toArray()];
        $restaurant = $event->reservation->branch->restaurant;
        $dateFormat = $restaurant->date_format ?? dateFormat();
        $timeFormat = $restaurant->time_format ?? timeFormat();
        $formattedDateTime = $event->reservation->reservation_date_time->translatedFormat($dateFormat . ', ' . $timeFormat);
        $pushNotification->sendPushNotifications($pushUsersIds, __('email.reservation.subject'), $formattedDateTime, route('reservations.index'));

    }
}
