<?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 State 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(StateDescription::class);
    }

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

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

    public static function withDescription($country_id = null, $state_id = null, $languageId = null)
    {
        $states = self::join('state_descriptions as sd', 'sd.state_id', 'states.id')
            ->where('sd.language_id', $languageId ?? currentLanguage()->id);

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

        if ($state_id){
            $states->where('states.id', $state_id);
        }

        $states->select([
            'states.*',
            'sd.name',
        ]);
        return $state_id ? $states->first() : $states->get() ?? [];
    }

}
