<?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 Region extends Model
{
    // Fields that mass assignment
    protected $fillable = ['country_id'];

    // Use soft delete
    use SoftDeletes;

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

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

    public function country()
    {
        return $this->belongsTo(Country::class);
    }

    public static function withDescription($country_id = null, $region_id = null)
    {
        $regions = self::join('region_descriptions as rd', 'rd.region_id', 'regions.id')
            ->where('rd.language_id', currentLanguage()->id);

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

        if ($region_id){
            $regions->where('regions.id', $region_id);
        }

        $regions->select([
            'regions.*',
            'rd.name',
        ]);
        return $region_id ? $regions->first() : $regions->cursor() ?? [];
    }

}
