<?php

namespace App\Models\Definition;

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

class DefinitionValue extends Model
{
    use HasFactory;

    protected $fillable = [
        'definition_id',
        'definition_attribute_id',
        'value',
    ];

    public function definition()
    {
        return $this->belongsTo(Definition::class);
    }

    public function definitionAttribute()
    {
        return $this->belongsTo(DefinitionAttribute::class);
    }

    public function getFormattedValueAttribute()
    {
        $attribute = $this->definitionAttribute;

        if (!$attribute) {
            return $this->value;
        }

        switch ($attribute->field_type) {
            case 'boolean':
                return $this->value ? 'Evet' : 'Hayır';
            case 'date':
                return $this->value ? \Carbon\Carbon::parse($this->value)->format('d.m.Y') : null;
            case 'number':
                return is_numeric($this->value) ? number_format($this->value, 2) : $this->value;
            case 'select':
                $options = $attribute->options ?? [];
                return $options[$this->value] ?? $this->value;
            default:
                return $this->value;
        }
    }

    public function scopeByDefinition($query, $definitionId)
    {
        return $query->where('definition_id', $definitionId);
    }

    public function scopeByAttribute($query, $attributeId)
    {
        return $query->where('definition_attribute_id', $attributeId);
    }

    public function scopeByAttributeName($query, $attributeName)
    {
        return $query->whereHas('definitionAttribute', function ($q) use ($attributeName) {
            $q->where('name', $attributeName);
        });
    }

    public function scopeWithValue($query, $value)
    {
        return $query->where('value', $value);
    }
}
