<?php

namespace App\Repositories\Core\Auth;

use App\Models\Core\Auth\Role;
use App\Models\Core\Auth\RoleUser;
use App\Traits\Model\Basic;
use Illuminate\Support\Facades\Auth;
use Laratrust\Traits\LaratrustUserTrait;

class Roles
{
    use Basic, LaratrustUserTrait;

    public static function getListByRights()
    {
        $data = ! Auth::user()->hasRole('admin') ? Role::whereNotIn('name', ['admin'])->get() : Role::all();

        return $data->pluck('name', 'id')->toArray();
    }

    public static function create($data)
    {
        $permissions = array_keys($data['permissions']);
        unset($data['permissions']);
        $data['active'] = true;
        $role = Role::create($data);
        $role->attachPermissions($permissions);

        return $role;
    }

    public static function update($input, $id = false)
    {
        $id = $id ? $id : $input['id'];
        $permissions = array_keys($input['permissions']);
        $role = self::get($id);
        $role->update(['name' => $input['name']]);
        $role->syncPermissions($permissions);

        return $role;
    }

    public static function toggleActive($id, $active)
    {
        return Role::find($id)->update(['active' => $active]);
    }

    public static function getWithPermissions($id)
    {
        $role = self::get($id)->toArray();
        $role['permissions'] = self::get($id)->permissions->pluck('id')->toArray();

        return $role;
    }

    public static function getByName($name)
    {
        return Role::where('name', $name)->first();
    }

    public static function getRolesByUser($user_id = false)
    {
        $user_id = $user_id ? $user_id : Users::getId();

        return RoleUser::byUser($user_id);
    }

    public static function getUsersByRole($id)
    {
        return RoleUser::byTeam($id)->get();
    }

    public static function getUsersIdByRole($id)
    {
        return self::getUsersByRole($id)->pluck('user_id');
    }

    public static function getModel()
    {
        return RoleUser::query();
    }
}
