<?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 getDateTimeAttribute()
    {
        $date = date('d ',strtotime($this->date));
        $date .= date('F ',strtotime($this->date));
        $date .= date('Y',strtotime($this->date));
        return $date;
    }


    public function getUrlImageAttribute()
    {
        return asset($this->image);
    }

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

    public static function withDescription($article_id = null)
    {
        $query = self::orderByDesc('articles.date')->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.id',
            'articles.image',
            'articles.date',
            'articles.created_at',
            'ad.name',
            'ad.description',
        ]);
        return $query;
    }
}
