<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Awobaz\Compoships\Compoships;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class ItemVariant extends Model
{
    use HasFactory;
    
    use Compoships;

    protected $table = 'item_variants';
    protected $primaryKey = 'id';

    protected $fillable = [
        'id',
        'code',
        'description',
        'item_id',
        'display_name',
        'is_publish',
        'barcode',
        'variant_name',
    ];

    public function reference()
    {
        return $this->belongsTo(ItemReference::class, ["item_id", "id"], ["item_id", "item_variant_id"]);
    }


    public function variables()
    {
        return $this->belongsToMany(Variant::class, "variant_value")->select("id", "name", "value");
    }

    public function image()
    {
        return $this->hasOne(ItemImage::class)->where('item_id', $this->item_id);
    }

    public function images()
    {
        return $this->hasMany(ItemImage::class)->where('item_id', $this->item_id);
    }
     public function variantValue()
    {
        return $this->hasMany(\App\Models\VariantValue::class, 'item_variant_id');
    }

       public function getImageUrlAttribute()
    {
        $image = $this->images->first()->filename ?? null;



        if (str_contains($image,"http")) {
            return $image;
        }

        return $image ? Storage::disk('wms')->url($image) : null;
    }

    public function item()
    {
        return $this->belongsTo(Items::class, 'item_id');
    }




}
