<?php

namespace Modules\Company\Models;

use App\Services\Upload\FileService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;
use Modules\Country\Models\Country;
use Modules\Region\Models\Region;
use Modules\Sector\Models\Sector;
use Modules\User\Models\User;

class Company extends Model
{
    //use soft delete
    use SoftDeletes;

    protected $fillable =
    [
        'domain','image','latitude','longitude','sector_id','added_by','region_id','country_id','lock'
    ];

    protected static function booted()
    {
        static::creating(function ($model) {
            if (Auth::check() && empty($model->added_by)) {
                $model->added_by = Auth::id();
            }
        });
    }

    public function added()
    {
        return $this->belongsTo(User::class,'added_by')->withTrashed();
    }
    /**
     * Get current description of the the Room
     * @return HasOne
     */
    public function currentDescription() :HasOne
    {
        return $this->hasOne(CompanyDescription::class)->where('language_id', currentLanguage()->id);
    }

    public function sector()
    {
        return $this->belongsTo(Sector::class)->withTrashed();
    }

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

    public function region()
    {
        return $this->belongsTo(Region::class)->withTrashed();
    }
    public function setImageAttribute($value)
    {
        if($value)
        {
            if(is_string($value))
            {
                $this->attributes['image'] = $value;
            }
            else
            {
                $photo = FileService::uploadImage($value);
                $this->attributes['image'] = $photo;
            }
        }
        else
        {
            $this->attributes['image'] = request()->method() == 'post'  ? 'logo.png' : $this->image;
        }
    }

    public function getDateAttribute()
    {
        return date('Y-m-d',strtotime($this->created_at));
    }
}
