<?php

namespace App\Models\Objects\Values;

use App\Models\Objects\Field;
use App\Models\Objects\NirObject;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

abstract class Value extends Model {
    protected $dates = [
    ];

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

    protected $hidden = [
        'id'
    ];

    public function object(): BelongsTo {
        return $this->belongsTo(NirObject::class, 'object_id');
    }

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

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

    public function set($value): bool {
        return $this->update(['value' => $value]);
    }

    public static function applyFilter($query, $value) {
        if (is_array($value)) {
            if (!empty($value['gt']) && !empty($value['lt'])) $query->whereBetween('value', $value);
            elseif (!empty($value['gt'])) $query->where('value', '>=', $value['gt']);
            elseif (!empty($value['lt'])) $query->where('value', '<=', $value['lt']);
        } else $query->where('value', '=', $value);
    }
}