<?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 Area extends Model
{
    //use soft delete
    use SoftDeletes;

    protected $fillable = [
        'city_id'
    ];

    /**
     * Return descriptions for Area
     * @return HasMany
     */
    public function descriptions($language_id= null)
    {
        if ($language_id) {
            $data = $this->hasMany(AreaDescription::class)->where('language_id', $language_id)->first();
            if(!$data){
                $data = $this->hasMany(AreaDescription::class)->first();
            }
            return $data;
        }
        $data = $this->hasMany(AreaDescription::class)->where('language_id', currentLanguage()['id'])->first();
        return $data;
    }
    public function city()
    {
        return $this->belongsTo(City::class)->withTrashed();
    }
    public static function withDescription($area_id = null)
    {
        $query = self::orderByDesc('areas.id')->join('area_descriptions as ad', 'ad.area_id', 'areas.id')
            ->where('ad.language_id', currentLanguage()->id)
            ->select(['areas.created_at', 'ad.*']);

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

    public function currentDescription()
    {
        return $this->hasOne(AreaDescription::class)->where('language_id',currentLanguage()['id']);
    }
}
