<?php

namespace App\Models;

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

class Booking extends Model
{
    use HasFactory, SoftDeletes, LogsActivity;

    protected $fillable = [
        'user_id',
        'total_amount',
        'commission_amount',
        'net_amount',
        'payment_method',
        'payment_status',
        'status',
        'notes',
    ];

    protected $casts = [
        'total_amount' => 'float',
        'commission_amount' => 'float',
        'net_amount' => 'float',
        'payment_status' => PaymentStatus::class,
        'status' => BookingStatus::class,
        "payment_response" => "json"

    ];

    public function user()
    {
        return $this->belongsTo(User::class)->withTrashed();
    }

    public function items()
    {
        return $this->hasMany(BookingItem::class);
    }

    public function serviceProviders()
    {
        return $this->hasManyThrough(ServiceProvider::class, BookingItem::class);
    }

    public function serviceProvider()
    {
        return $this->hasOneThrough(ServiceProvider::class, BookingItem::class, 'booking_id', 'id', 'id', 'service_provider_id');
    }

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

    protected static function booted()
    {
        static::created(function (Booking $booking) {
            $booking->user->notify(new \App\Notifications\BookingCreatedNotification($booking));
        });

        static::updated(function (Booking $booking) {
            if ($booking->isDirty('status')) {
                $booking->user->notify(new BookingStatusUpdatedNotification($booking));
            }
        });
    }
}
