<?php

namespace App\Models;

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

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

    protected $fillable = [
        'image','gender_status','brand_status','category_id','main_id','sub_id','views'
    ];

    /**
     * Return descriptions for choice
     * @return HasMany
     */

    public function category()
    {
        return $this->belongsTo(Category::class,'category_id');
    }
    public function models()
    {
        return $this->hasMany(Category::class,'category_id');
    }
    public function sampleProduct()
    {
        return $this->hasMany(Product::class,'category_id')->take(4)->orderBy('id','DESC');
    }

    public function currentDescription()
    {
        return $this->hasOne(CategoryDescription::class)->where('language_id',currentLanguage()['id']);
    }
    
    public function attributes()
    {
        return $this->belongsToMany(Attribute::class,'category_attributes','category_id','attribute_id');
    }
    public function descriptions($language_id= null)
    {
        if ($language_id) {
            $data = $this->hasMany(CategoryDescription::class)->where('language_id', $language_id)->first();
            if(!$data){
                $data = $this->hasMany(CategoryDescription::class)->first();
            }
            return $data;
        }
        $data = $this->hasMany(CategoryDescription::class)->where('language_id', currentLanguage()['id'])->first();
        return $data;
    }

    public static function withDescription($category_id = null)
    {
        $query = self::orderByDesc('categories.id')->join('category_descriptions as cd', 'cd.category_id', 'categories.id')
            ->where('cd.language_id', currentLanguage()->id)
            ->select(['categories.created_at', 'cd.*']);

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

}
