<?php

namespace App\Models\Objects;

use App\Support\RelationValuesTrait;
use App\Support\UuidScopeTrait;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class ObjectType extends Model {
    use UuidScopeTrait, SoftDeletes, RelationValuesTrait;

    protected $dates = [
    ];

    protected $fillable = [
        'uuid',
        'parent_id',
        'name',
        'title'
    ];

    protected $hidden = [
        'id'
    ];

    public function parent(): BelongsTo {
        return $this->belongsTo(ObjectType::class, 'parent_id');
    }

    public function children(): HasMany {
        return $this->hasMany(ObjectType::class, 'parent_id');
    }

    public function objects(): HasMany {
        return $this->hasMany(NirObject::class, 'type_id');
    }

    public function groups(): HasMany {
        return $this->hasMany(FieldsGroup::class)->orderBy('ord');
    }

    public function fields(): Builder {
        return Field::query()->whereHas('groups', function($query) {
            $query->where(['object_type_id' => $this->id]);
        });
    }

    public function getField($name) {
        return $this->fields()->where(['name' => $name])->first();
    }
}