<?php

namespace App\Models;

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

class Country extends Model
{
    //
    use SoftDeletes;
    protected $fillable = [
        'image','currency','abbr','iso'
    ];
    public function descriptions($language_id= null)
    {

        if ($language_id) {
            $data = $this->hasMany(CountryDescription::class)->where('language_id', $language_id)->first();
            if(!$data){
                $data = $this->hasMany(CountryDescription::class)->first();
            }

            return $data;
        }
        $data = $this->hasMany(CountryDescription::class)->where('language_id', currentLanguage()['id'])->first();
        return $data;
    }


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

        if ($country_id)
        {
            if (is_array($country_id))
            {
                $query->whereIn('countries.id', $country_id);
            }
            else
            {
                $query->where('countries.id', $country_id);
            }
        }

        $query->select([
            'countries.*',
            'cd.name',
        ]);
        return $query;
    }

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