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

    protected $fillable = [
        'country_id'
    ];

    /**
     * Return descriptions for city
     * @return HasMany
     */
    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 function country()
    {
        return $this->belongsTo(Country::class)->withTrashed();
    }
    public static function withDescription($city_id = null)
    {
        $query = self::orderByDesc('cities.id')->join('city_descriptions as ad', 'ad.city_id', 'cities.id')
            ->where('ad.language_id', currentLanguage()->id)
            ->select(['cities.created_at', 'ad.*']);

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

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