<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class RolesController extends Controller
{
    public function index() {
        $roles = Role::query()->paginate();

        return view('dashboard.administrator.roles.index', ['roles' => $roles]);
    }

    public function create() {
        $permissions = Permission::query()->get()->groupBy('group_name');
        return view('dashboard.administrator.roles.create', ['permissions' => $permissions]);
    }

    public function store(Request $request) {
        $role = Role::query()->create([
            'name'      =>  $request->input('name'),
            'ar_name'   =>  $request->input('ar_name'),
            'guard_name'   =>  'admins',
        ]);
        $role->syncPermissions($request->input('permissions'));
        return redirect()->route('roles.index')->with('success', trans('global.created_success'));
    }

    public function edit($id) {
        $role = Role::query()->findOrFail($id);
        $permissions = Permission::query()->get()->groupBy('group_name');
        $rolePermissions = $role->permissions->pluck('name')->toArray();
        return view('dashboard.administrator.roles.edit', [
            'role' => $role,
            'permissions' => $permissions,
            'rolePermissions' => $rolePermissions
        ]);
    }

    public function update(Request $request, Role $role) {
        $role->update([
            'name'      =>  $request->input('name'),
            'ar_name'   =>  $request->input('ar_name'),
            'guard_name'   =>  'admins',
        ]);
        $role->syncPermissions($request->input('permissions'));
        return redirect()->route('roles.index')->with('success', trans('global.updated_success'));
    }

    public function destroy(Role $role) {
        if($role->users()->count() >= 1) {
            return redirect()->route('roles.index')->with('error', trans('global.cant_delete_has_users'));
        }
        $role->delete();
        return redirect()->route('roles.index')->with('success', trans('global.deleted_successful'));
    }
}
