<?php

namespace App;

use App\Helpers\ImageHelper;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class Country extends Model
{
    // Fields that mass assignment
    protected $fillable = ['image'];

    // 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 function states()
    {
        return $this->hasMany(State::class);
    }

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

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

        $countries->select([
            'countries.*',
            'cd.name',
        ]);
        return $country_id ? $countries->first() : $countries->get() ?? [];
    }

}
