<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * @property mixed id
 */
class Attribute extends Model
{
    //use soft delete
    use SoftDeletes;

    protected $fillable = [
       'id'
    ];

    public function choices()
    {
        return $this->hasMany(AttributeChoice::class);
    }

    public function subattributes()
    {
        return $this->hasMany(Attribute::class,'attribute_id');
    }

    public function details()
    {
        return $this->hasOne(AttributeDescription::class)->where('language_id', currentLanguage()['id']);
    }
    /**
     * Return descriptions for city
     * @return HasMany
     */
    public function descriptions($language_id= null)
    {
        if ($language_id) {
            $data = $this->hasMany(AttributeDescription::class)->where('language_id', $language_id)->first();
            if(!$data){
                $data = $this->hasMany(AttributeDescription::class)->first();
            }
            return $data;
        }
        $data = $this->hasMany(AttributeDescription::class)->where('language_id', currentLanguage()['id'])->first();
        return $data;
    }
    public static function withDescription($attribute_id = null)
    {
        $query = self::orderByDesc('attributes.id')->join('attribute_descriptions as ad', 'ad.attribute_id', 'attributes.id')
            ->where('ad.language_id', currentLanguage()->id)
            ->select(['attributes.created_at', 'ad.*']);

        if ($attribute_id)
        {
            if (is_array($attribute_id))
            {
                $query->whereIn('attributes.id', $attribute_id);
            }
            else
            {
                $query->where('attributes.id', $attribute_id);
            }
        }
        $query->select([
            'attributes.*',
            'ad.name',
        ]);
        return $query;
    }

}
