<?php

namespace Modules\CityManager\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Modules\User\Models\User;
use Modules\User\Models\UserRole;
use Modules\User\Models\Role;
use Modules\Main\Models\City;
class CityManager extends Model
{
    use HasFactory;
    protected $fillable = [
        'city_id',
        'user_id'
    ];
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }
    public function city()
    {
        return $this->belongsTo(City::class, 'city_id');
    }
    protected static function booted()
    {
        static::created(function (CityManager $cityManager)
        {
            UserRole::create([
                'user_id' => $cityManager->user_id,
                'role_id' => Role::CITY_MANAGER
            ]);
        });

        static::deleted(function (CityManager $cityManager)
        {
            if (CityManager::where('user_id', $cityManager->user->id)->count() == 0) {
                UserRole::where([
                    'user_id' => $cityManager->user_id,
                    'role_id' => Role::CITY_MANAGER
                ])->delete();
            }
        });
    }
}
