<?php

namespace App\Models\Deal;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Modules\User\Models\User;
use Modules\User\Models\UserRole;
use Modules\User\Models\Role;
use Modules\Contracts\Models\Contract;
use Modules\Main\Models\Complex;
use Modules\Main\Models\Agent\Agent;
use Modules\Bitrix\Traits\Bitrixable;
class Deal extends Model
{
    use HasFactory, Notifiable, Bitrixable;
    protected $fillable = [
        'client_id',
        'complex_id',
        'agent_id',
        'bitrix_id',
        'is_unique',
        'confirm_token'
    ];
    public function complex()
    {
        return $this->belongsTo(Complex::class);
    }
    public function agent()
    {
        return $this->belongsTo(Agent::class, 'agent_id');
    }

    public function contract()
    {
        return $this->hasOne(Contract::class, 'deal_id');
    }

    protected static function booted(): void
    {
        static::creating(function (Deal $deal)
        {
            $deal->confirm_token = hash('sha256', json_encode($deal->all()));
        });

        static::created(function (Deal $deal)
        {
            UserRole::create([
                'user_id' => $deal->client_id,
                'role_id' => Role::CLIENT
            ]);
        });

        static::deleted(function (Deal $deal)
        {
            $deal->bitrixy()->delete();

        });

    }


}
