<?php

namespace App\Models;

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

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

    protected $fillable = [
        'image','date'
    ];

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

    public function descriptions($language_id= null)
    {
        if ($language_id) {
            $data = $this->hasMany(ArticleDescription::class)->where('language_id', $language_id)->first();
            if(!$data){
                $data = $this->hasMany(ArticleDescription::class)->first();
            }
            return $data;
        }
        $data = $this->hasMany(ArticleDescription::class)->where('language_id', currentLanguage()['id'])->first();
        return $data;
    }

    public static function withDescription($article_id = null)
    {
        $query = self::join('article_descriptions as ad', 'ad.article_id', 'articles.id')
            ->where('ad.language_id', currentLanguage()->id)
            ->select(['articles.created_at', 'ad.*']);

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