<?php

namespace App\Models\Objects\Values;

use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Support\Arr;

class RelationValue extends Value {
    protected $table = 'field_relation_values';

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

    public function relatable(): MorphTo {
        return $this->morphTo();
    }

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

    public function set($value): bool {
        if (!is_object($value) && ($class = $this->field->params['related'] ?? null) && class_exists($class)) {
            if (!is_array($value)) $value = $class::query()->where(['uuid' => $value])->first();
            elseif (Arr::isAssoc($value)) {
                if ($id = $value['id'] ?? $value['uuid'] ?? null) {
                    $value = $class::query()->where(is_numeric($id) ? ['id' => $id] : ['uuid' => $id])->first();
                } else $value = $class::query()->where($value)->first();
            }
        }
        return is_object($value) ? boolval($value->relationValues()->save($this)) : !$this->delete();
    }

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