<?php

namespace Modules\Main\Models\Agent;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

use Modules\Main\Models\Company\Company;
use Modules\User\Models\User;
use Modules\User\Models\UserRole;
use Modules\User\Models\Role;
use App\Models\Deal\Deal;
use App\Notifications\AgentCreated;
use Modules\Payment\Traits\Paymentable;
use Modules\Bitrix\Traits\Bitrixable;
class Agent extends Model
{
    use HasFactory;
    use SoftDeletes;
    use Paymentable;
    use Bitrixable;

    public const STATUS_ACTIVE    = "ACTIVE";
    public const STATUS_DISMISSED = "DISMISSED";
    protected $fillable = [
        'user_id',
        'company_id'
    ];
    public function company()
    {
        return $this->belongsTo(Company::class);
    }
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function deals()
    {
        return $this->hasMany(Deal::class);
    }

    protected static function booted(): void
    {
        static::created(function (Agent $agent)
        {
            UserRole::insertOrIgnore([
                'user_id' => $agent->user_id,
                'role_id' => Role::AGENT
            ]);
            $agent->notify();
        });

        static::restored(function (Agent $agent)
        {
            UserRole::insertOrIgnore([
                'user_id' => $agent->user_id,
                'role_id' => Role::AGENT
            ]);
            $agent->notify();
        });

        static::updated(function (Agent $agent)
        {
            if ($agent->trashed())
            {
                UserRole::where([
                    'user_id' => $agent->user_id,
                    'role_id' => Role::AGENT
                ])->delete();
            }
            else
            {
                UserRole::create([
                    'user_id' => $agent->user_id,
                    'role_id' => Role::AGENT
                ]);
            }
        });

        static::deleted(function (Agent $agent)
        {
            UserRole::where([
                'user_id' => $agent->user_id,
                'role_id' => Role::AGENT
            ])->delete();
        });
    }
    private function notify()
    {
        //$this->user->notify(new AgentCreated($this));
        return true;
    }
}
