<?php

namespace App\Notifications;

use App\Models\Booking;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Log;
use NotificationChannels\Fcm\FcmChannel;
use NotificationChannels\Fcm\FcmMessage;
use NotificationChannels\Fcm\Resources\Notification as FcmNotification;

class BookingCreatedNotification extends Notification implements ShouldQueue
{
    use Queueable;

    public function __construct(protected Booking $booking) {}

    public function via($notifiable)
    {
        $channels = ['database'];

        if ($notifiable->firebase_token) {
            $channels[] = FcmChannel::class;
        }

        Log::info('Notification channels for BookingCreatedNotification', [
            'user_id' => $notifiable->id,
            'channels' => $channels
        ]);

        return $channels;
    }

    public function toFcm($notifiable): FcmMessage
    {
        $locale = $notifiable->pref_lang ?? app()->getLocale();
        $title = __('messages.booking_created_title', ['booking_id' => $this->booking->id], $locale);
        $body = __('messages.booking_created_body', ['booking_id' => $this->booking->id, 'total_amount' => $this->booking->total_amount], $locale);
        Log::info('Sending BookingCreatedNotification to user ID: ' . $notifiable->id, [
            'title' => $title,
            'body' => $body,
            'booking_id' => $this->booking->id,
            'url' => route('user.bookings.show', $this->booking->id),
            "locale" => $locale,
            "pref_lang" => $notifiable->pref_lang,
            "user" => $notifiable
        ]);

        return FcmMessage::create()
            ->data([
                'booking_id' => (string) $this->booking->id,
                'url' => route('user.bookings.show', $this->booking->id),
            ])
            ->notification(
                notification: FcmNotification::create()
                    ->title($title)
                    ->body($body)
            );
    }

    public function toArray($notifiable)
    {
        $locale = $notifiable->pref_lang ?? app()->getLocale();

        return [
            'title_en' => __('messages.booking_created_title', ['booking_id' => $this->booking->id], 'en'),
            'body_en' => __('messages.booking_created_body', ['booking_id' => $this->booking->id, 'total_amount' => $this->booking->total_amount], 'en'),
            'title_ar' => __('messages.booking_created_title', ['booking_id' => $this->booking->id], 'ar'),
            'body_ar' => __('messages.booking_created_body', ['booking_id' => $this->booking->id, 'total_amount' => $this->booking->total_amount], 'ar'),
            'url' => route('user.bookings.show', $this->booking->id),
            'booking_id' => $this->booking->id
        ];
    }
}
