<?php

namespace App\Models\api\v1;

use App\Models\User;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Model;

/**
 * @property integer $id
 * @property integer $user_id
 * @property integer $role_id
 * @property string $creation_date
 * @property string $last_update_date
 * @property boolean $is_active
 * @property string $created_at
 * @property integer $created_by
 * @property integer $last_updated_by
 * @property string $updated_at
 * @property boolean $is_deleted
 * @property string $deleted_at
 * @property integer $deleted_by
 * @property Role $role
 * @property User $user
 */
class UserRole extends Model
{
    /**
     * The table associated with the model.
     * 
     * @var string
     */
    protected $table = 'users_roles';

    /**
     * The "type" of the auto-incrementing ID.
     * 
     * @var string
     */
    protected $keyType = 'integer';

    /**
     * @var array
     */
    protected $fillable = ['user_id', 'role_id', 'creation_date', 'is_active', 'created_at', 'created_by', 'updated_by', 'updated_at', 'is_deleted', 'deleted_at', 'deleted_by'];
    protected $hidden = [ 'created_at', 'created_by', 'updated_by', 'updated_at', 'is_deleted', 'deleted_at', 'deleted_by'];


    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function role()
    {
        return $this->belongsTo('App\Models\api\v1\Role');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo('App\Models\api\v1\User');
    }


    public static function GetRolesDetailsByUserId(int $user_id): array
    {
        $user_roles = UserRole::Where([['user_id', $user_id], ['is_deleted', 0]])->get();
        $result     = [];
        foreach ($user_roles as $user_role)
        {
            $role = Role::find($user_role->role_id);
            $result[] = [
                'user_role_id'          => $user_role->id,
                'role_id'               => $role->id,
                'name'                  => $role->name,
                'user_role_is_active'   => $user_role->is_active == 1,
                'role_is_active'        => $user_role->is_active == 1
            ];
        }
       return $result;
    }

    public static function boot()
    {
        parent::boot();

        static::creating(function ($model)
        {
            $model->uuid        = Str::uuid();
            $model->created_by  = auth()->user()->id ??  null;
            $model->is_active   = 1;
            // $model->reference = Str::random(12);
        });

    }
}
