<?php

namespace App\Models\Objects\Values;

use App\Models\Asset;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ImageValue extends Value {
    protected $table = 'field_image_values';

    protected $fillable = [
        'object_id',
        'field_id',
        'asset_id',
        'ord'
    ];

    public function asset(): BelongsTo {
        return $this->belongsTo(Asset::class);
    }

    public function get() {
        return $this->asset;
    }

    public function set($value): bool {
        if (!is_object($value)) $value = Asset::byUuid($value)->first();
        return is_object($value) ? $this->update(['asset_id' => $value->id]) : !$this->delete();
    }

    public static function applyFilter($query, $value) {
        $value = is_array($value) ? $value : [$value];
        $query->whereHas('asset', function($query) use($value) {
            $query->where(function($query) use($value) {
                $query->whereIn('uuid', $value)->orWhereIn('name', $value);
            });
        });
    }
}