<?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 Address extends Model
{
    // Fields that mass assignment
    protected $fillable = ['map_url', 'email', 'phone'];

    // Use soft delete
    use SoftDeletes;


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

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


    public static function withDescription($id = null)
    {
        $query = self::orderBy('addresses.id')->join('address_descriptions as aDesc', 'aDesc.address_id', 'addresses.id')
            ->where('aDesc.language_id', currentLanguage()->id);
        if ($id) {
            $query->where('addresses.id', $id);
        }

        $query->select([
            'addresses.*',
            'aDesc.name'
        ]);

        return $id ? $query->first() : $query->get();
    }


}
