<?php

namespace App\Models;

use App\Traits\Auditable;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Exceptions\GlobalException;
use App\Models\User;
use App\Models\Role;


class RoleUser extends Model
{
    use Auditable;
    use HasFactory;

    /**
     * The table associated with the model.
     * 
     * @var string
     */
    protected $table = 'role_user';
    protected $fillable = ['role_id', 'user_id', 'user_type', 'created_at', 'updated_at'];

    /**
     * 
     */
    public static function getRolname(User $user)
    {
        if(isset($user)){
            try {
                $name = "";
                $roleUser = RoleUser::where("user_id", $user->id)->first();
                
                if (!$roleUser) {
                    return __('common.no-role-assigned'); // "Sin rol asignado"
                }
                
                $role = Role::find($roleUser->role_id);
                if (!$role) {
                    return __('common.invalid-role'); // "Rol inválido"
                }
                
                return $role->display_name;
            } catch (Throwable $th) {
                throw new GlobalException($th->getMessage());
            }
        }
        return __('common.no-user'); // "Sin usuario"
    }

    /**
     * 
     */
    public static function getRolShortname(User $user)
    {
        if(isset($user)){
            try {
                $roleUser = RoleUser::where("user_id", $user->id)->first();
                
                if (!$roleUser) {
                    return __('common.no-role-assigned'); // "Sin rol asignado"
                }
                
                $role = Role::find($roleUser->role_id);
                if (!$role) {
                    return __('common.invalid-role'); // "Rol inválido"
                }
                
                return $role->name;
            } catch (Throwable $th) {
                throw new GlobalException($th->getMessage());
            }
        }
        return __('common.no-user'); // "Sin usuario"
    }
}
