<?php

namespace App\Models;

use App\Enums\PaymentStatus;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;

class BookingItem extends Model
{
    use HasFactory, LogsActivity;


    protected $fillable = [
        'booking_id',
        'product_id',
        'price',
        'service_date',
        "service_provider_id",
        "user_id",
        "commission",
        "net_price",
        "notes",
        "status",
        "is_transfered",
    ];

    protected $casts = [
        // 'service_date' => 'date:Y-m-d',
        'price' => 'float',
        'commission' => 'float',
        'net_price' => 'float',
        "status" => \App\Enums\BookingItemStatus::class,
        "is_transfered" => "bool"
    ];

    public function booking()
    {
        return $this->belongsTo(Booking::class);
    }
    public function user()
    {
        return $this->belongsTo(User::class)->withTrashed();
    }
    public function product()
    {
        return $this->belongsTo(Product::class)->withTrashed();
    }
    public function serviceProvider()
    {
        return $this->belongsTo(ServiceProvider::class)->withTrashed();
    }

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logFillable()
            ->logOnlyDirty()
            ->setDescriptionForEvent(fn(string $eventName) => "This model has been {$eventName}");
    }

    protected static function booted()
    {
        static::updated(function (BookingItem $bookingItem) {
            if ($bookingItem->isDirty('status')) {
                $bookingItem->user->notify(new \App\Notifications\ItemStatusChangedNotification($bookingItem, $bookingItem->status, $bookingItem->user));
                if ($bookingItem->status == \App\Enums\BookingItemStatus::CANCELED && $bookingItem->booking->payment_status === PaymentStatus::PAID) {
                    $bookingItem->serviceProvider->notify(new \App\Notifications\ItemCancelledNotification($bookingItem, $bookingItem->user));
                }
            }
        });
    }
}
