<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

/**
 * @mixin IdeHelperListingFeatureValue
 */
class ListingFeatureValue extends Model
{
    use HasFactory;

    protected $fillable = [
        'listing_id',
        'feature_id',
        'value_text',
        'value_number',
        'value_boolean',
        'value_json',
    ];

    protected $casts = [
        'value_number' => 'decimal:2',
        'value_boolean' => 'boolean',
        'value_json' => 'array',
    ];

    public function listing()
    {
        return $this->belongsTo(Listing::class);
    }

    public function feature()
    {
        return $this->belongsTo(ListingFeature::class, 'feature_id');
    }

    public function getValueAttribute()
    {
        if (!is_null($this->value_boolean)) {
            return $this->value_boolean;
        }

        if (!is_null($this->value_number)) {
            return $this->value_number;
        }

        if (!is_null($this->value_json)) {
            return $this->value_json;
        }

        return $this->value_text;
    }
}