<?php

namespace App\Models;

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

/**
 * @property mixed id
 */
class Facility extends Model
{
    //use soft delete
    use SoftDeletes;

    protected $fillable = [
        'image'
    ];

    public function descriptions($language_id= null)
    {
        if ($language_id) {
            $data = $this->hasMany(FacilityDescription::class)->where('language_id', $language_id)->first();
            if(!$data){
                $data = $this->hasMany(FacilityDescription::class)->first();
            }
            return $data;
        }
        $data = $this->hasMany(FacilityDescription::class)->where('language_id', currentLanguage()['id'])->first();
        return $data;
    }

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

        if ($facility_id)
        {
            if (is_array($facility_id))
            {
                $query->whereIn('facilities.id', $facility_id);
            }
            else
            {
                $query->where('facilities.id', $facility_id);
            }
        }
        $query->select([
            'facilities.*',
            'cd.name',
        ]);
        return $query;
    }

}
