<?php

namespace Modules\ContactList\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\Company\Models\Company;
use Modules\Country\Models\Country;
use Modules\Region\Models\Region;
use Modules\Sector\Models\Sector;
use Modules\User\Models\User;

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

    protected $fillable =
    [
        'role','image','email','phone','country_id','company_id','gender','status','added_by','is_top_customer','company_website','avg_stand_annual','avg_events_annual','budget','decision_maker_status','note','lock','employee_id'
    ];

    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(ContactListDescription::class)->where('language_id', currentLanguage()->id);
    }

    public function company()
    {
        return $this->belongsTo(Company::class)->withTrashed();
    }
    public function country()
    {
        return $this->belongsTo(Country::class)->withTrashed();
    }
    public function employee()
    {
        return $this->belongsTo(User::class,'employee_id')->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;
        }
    }
}
