<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class ServiceItem extends Model
{
    use HasFactory, SoftDeletes;

    /**
     * Indicates if the IDs are auto-incrementing.
     *
     * @var bool
     */
    public $incrementing = false;

    /**
     * The data type of the auto-incrementing ID.
     *
     * @var string
     */
    protected $keyType = 'string';

    protected $fillable = [
        'service_category_id',
        'name',
        'slug',
        'description',
        'image',
        'base_price',
        'unit',
        'is_active',
        'sort_order',
    ];

    protected $casts = [
        'base_price' => 'decimal:2',
        'is_active' => 'boolean',
        'sort_order' => 'integer',
    ];

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($item) {
            if (empty($item->id)) {
                $item->id = Str::uuid();
            }
        });
    }

    public function serviceCategory()
    {
        return $this->belongsTo(ServiceCategory::class);
    }

    public function serviceItemFeatures()
    {
        return $this->hasMany(ServiceItemFeature::class);
    }

    public function serviceItemFeatureOptions()
    {
        return $this->hasMany(ServiceItemFeatureOption::class);
    }

    public function vendorServices()
    {
        return $this->hasMany(VendorService::class);
    }

    public function orderItems()
    {
        return $this->hasMany(OrderItem::class);
    }

    public function featureTypes()
    {
        return $this->belongsToMany(FeatureType::class, 'service_item_features')
            ->withPivot(['is_required', 'sort_order'])
            ->withTimestamps();
    }

    public function featureOptions()
    {
        return $this->belongsToMany(FeatureOption::class, 'service_item_feature_options')
            ->withPivot(['is_available', 'price_adjustment', 'price_adjustment_type', 'sort_order'])
            ->withTimestamps();
    }

    public function availableFeatureOptions()
    {
        return $this->belongsToMany(FeatureOption::class, 'service_item_feature_options')
            ->wherePivot('is_available', true)
            ->withPivot(['price_adjustment', 'price_adjustment_type', 'sort_order'])
            ->withTimestamps();
    }
}
