<?php

namespace Modules\Feature\Models;

use App\Services\Upload\UploadService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;

class Feature extends Model
{
    public $timestamps = false;
    protected $fillable =
    [
        'image','featureable_id','featureable_type'
    ];


    public function descriptions($language_id= null)
    {
        if ($language_id) {
            $data = $this->hasMany(FeatureDescription::class)->where('language_id', $language_id)->first();
            if(!$data){
                $data = $this->hasMany(FeatureDescription::class)->first();
            }

            return $data;
        }
        $data = $this->hasMany(FeatureDescription::class)->where('language_id', currentLanguage()['id'])->first();
        return $data;
    }

    /**
     * Get current description of the the Room
     * @return HasOne
     */
    public function currentDescription() :HasOne
    {
        return $this->hasOne(FeatureDescription::class)->where('language_id', config('current_language_id'));
    }

    public function setImageAttribute($value): void
    {
        if ($value) {
            if (is_string($value)) {
                $this->attributes['image'] = $value;
            } else {
                $oldImage = request('old_image') ?? $this->image ?? null;
                $image = UploadService::upload($value, $oldImage, 'features');
                $this->attributes['image'] = $image;
            }
        } elseif ($this->image ?? false) {
            $this->attributes['image'] = $this->image;
        }
    }

    public function getImageUrlAttribute(): ?string
    {
        return UploadService::url($this->image);
    }
}
