<?php

namespace App\Repositories\Auth;

use App\Models\Permission;
use App\Models\Role;
use DB;
use Hash;

class RoleRepository
{
    public function getList(array $params = [])
    {
        $limit = @$params["limit"] ? (int) @$params["limit"] : 10;
        $sortColumn = @$params["sort"]["column"] ? $params["sort"]["column"] : "id";
        $sortDir = @$params["sort"]["dir"] ? $params["sort"]["dir"] : "desc";

        return Role::when(@$params['search'], function($query) use ($params) {
            return $query->where('name', 'iLIKE', '%' . $params['search'] . '%');
        })
        ->orderBy($sortColumn, $sortDir)
        ->paginate($limit);
    }

    public function getPermission(array $params = [])
    {
        return Permission::orderBy("code")->paginate(1000);
    }

    public function create(array $data)
    {
        $item = Role::create($data);
        $item->permissions()->sync($data["permissions"]);
        $item->save();
        return $item;
    }

    public function update(Role $item, array $data)
    {
        $item->update($data);
        $item->permissions()->sync($data["permissions"]);
        $item->save();
        return $item;
    }

    public function delete(Role $item)
    {
        $item->delete();
    }

    public function findBy($column, $value)
    {
        $item = Role::where($column, $value)->firstOrFail();
        return $item;
    }

    public function findUserByPermission($code)
    {
        $roles = Role::whereHas("permissions", function($query) use ($code){
            $query->where("code", $code);
        })->get();
        return $roles->flatMap(function($role){
            return $role->users;
        });
    }
}
