<?php

namespace App\Notifications;

use App\Models\BookingItem;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;
use NotificationChannels\Fcm\FcmChannel;
use NotificationChannels\Fcm\FcmMessage;
use NotificationChannels\Fcm\Resources\Notification as FcmNotification;

class ItemUpdatedNotification extends Notification implements ShouldQueue
{
    use Queueable;

    protected $item;
    protected $user;

    public function __construct(BookingItem $item, User $user)
    {
        $this->item = $item;
        $this->user = $user;
    }

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

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

        return $channels;
    }

    public function toFcm($notifiable): FcmMessage
    {
        $locale = $notifiable->pref_lang ?? app()->getLocale();
        $title = __('messages.item_updated_title', ['user' => $this->user->name], $locale);
        $body = __('messages.item_updated_body', ['item_id' => $this->item->id, 'date' => $this->item->service_date, 'notes' => $this->item->notes ?? 'No notes'], $locale);

        return FcmMessage::create()
            ->data([
                'item_id' => (string) $this->item->id,
                "booking_id" => $this->item->booking_id,
                'url' => route('provider.booking-items.show', $this->item->id),
                'type' => 'item_updated',
            ])
            ->notification(
                notification: FcmNotification::create()
                    ->title($title)
                    ->body($body)
            );
    }

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

        return [
            'title_en' => __('messages.item_updated_title', ['user' => $this->user->name], 'en'),
            'body_en' => __('messages.item_updated_body', ['item_id' => $this->item->id, 'date' => $this->item->service_date, 'notes' => $this->item->notes ?? 'No notes'], 'en'),
            'title_ar' => __('messages.item_updated_title', ['user' => $this->user->name], 'ar'),
            'body_ar' => __('messages.item_updated_body', ['item_id' => $this->item->id, 'date' => $this->item->service_date, 'notes' => $this->item->notes ?? 'No notes'], 'ar'),
            'url' => route('provider.booking-items.show', $this->item->id),
            "booking_id" => $this->item->booking_id,
        ];
    }
}
