<?php

namespace Modules\Main\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;

use App\Notifications\Deal\DealCreated;
use App\Notifications\Deal\DealUnique;
use App\Notifications\Deal\DealNotUnique;
class Deal extends Model
{
    use HasFactory, Notifiable, Bitrixable;
    protected $fillable = [
        'complex_id',
        'agent_id',
        'bitrix_id',
        'is_unique',
        'confirm_token',
        'plan7_data',
        'unique_until'
    ];

    protected $dates =[
        'unique_until','deleted_at'
    ];

    public function complex()
    {
        return $this->belongsTo(Complex::class, 'complex_id');
    }
    public function clients()
    {
        return $this->hasManyThrough(
            Client::class
            ,
            DealClients::class
            ,
            'deal_id'
            ,
            'id'
            ,
            'id'
            ,
            'client_id'

        );
        //return $this->hasMany(DealClients::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) {
            $deal->notify(new DealCreated());
        });
        static::updated(function (Deal $deal) {
            if ($deal->wasChanged('status')) {
                switch ($deal->status) {
                    case DealStatus::UNIQUE:
                        $deal->notify(new DealUnique());
                        break;
                    case DealStatus::NOT_UNIQUE:
                        $deal->notify(new DealNotUnique());
                        break;
                }
            }
        });
    }


}
