<?php

namespace App;

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


class Country extends Model
{
    // Use soft delete
    use SoftDeletes;

    /**
     * Get description for pages
     * @return HasMany
     */
    public function descriptions() :HasMany
    {
        return $this->hasMany(CountryDescription::class);
    }

    /**
     * Get description of current language for pages
     * @return HasOne
     */
    public function currentDescription() :HasOne
    {
        return $this->hasOne(CountryDescription::class)->where('language_id', currentLanguage()->id);
    }


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

        if (count($ids) == 1){
            $countries->where('countries.id', $ids);
        }

        if (count($ids) > 1){
            $countries->whereIn('countries.id', $ids);
        }

        $countries->select([
            'countries.*',
            'cd.name',
        ]);
        return count($ids) == 1 ? $countries->first() : $countries->cursor() ?? [];
    }

}
