<?php

namespace Modules\Deal\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\ContactList\Models\ContactList;
use Modules\DealStatus\Models\DealStatus;
use Modules\Product\Models\Product;
use Modules\Region\Models\Region;
use Modules\Sector\Models\Sector;
use Modules\User\Models\User;

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

    protected $fillable =
    [
        'status','start_date','end_date','closed_at','file','file_url','product_id','company_id','employee_id','deal_id','contact_list_id','amount','payment_status','sector_id','month','added_by','lock'
    ];

    protected static function booted()
    {
        static::creating(function ($model) {
            if (Auth::check() && empty($model->added_by)) {
                $model->added_by = Auth::id();
            }
        });
    }
    /**
     * Get current description of the the Room
     * @return HasOne
     */
    public function currentDescription() :HasOne
    {
        return $this->hasOne(DealDescription::class)->where('language_id', currentLanguage()->id);
    }

    public function added()
    {
        return $this->belongsTo(User::class,'added_by')->withTrashed();
    }

    public function sub()
    {
        return $this->hasMany(self::class,'deal_id');
    }
    public function subTrashed()
    {
        return $this->hasMany(self::class,'deal_id')->onlyTrashed();
    }
    public function company()
    {
        return $this->belongsTo(Company::class,'company_id')->withTrashed();
    }
    public function sector()
    {
        return $this->belongsTo(Sector::class,'sector_id')->withTrashed();
    }
    public function contactList()
    {
        return $this->belongsTo(ContactList::class,'contact_list_id')->withTrashed();
    }
    public function deal()
    {
        return $this->belongsTo(self::class,'deal_id')->withTrashed();
    }
    public function employee()
    {
        return $this->belongsTo(User::class,'employee_id')->withTrashed();
    }
    public function product()
    {
        return $this->belongsTo(Product::class,'product_id')->withTrashed();
    }
    public function setFileAttribute($value)
    {
        if($value)
        {
            if(is_string($value))
            {
                $this->attributes['file'] = $value;
            }
            else
            {
                $file = FileService::uploadFile($value);
                $this->attributes['file'] = $file;
            }
        }
        else
        {
            $this->attributes['file'] = request()->method() == 'post'  ? 'logo.png' : $this->file;
        }
    }
}
