<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class RoleController extends Controller
{
    public function index(Request $request)
    {
        $role = $request->get('role', 'user');
        $size = $request->get('size', 20);

        $users = DB::table('users')->whereRaw('LOWER(role) = LOWER(?)', [$role])->paginate($size)->withQueryString();
        $roleStats = DB::table('users')->selectRaw('role, count(*) as cnt')->groupBy('role')->pluck('cnt', 'role');
        $statusStats = DB::table('users')->selectRaw('status, count(*) as cnt')->groupBy('status')->pluck('cnt', 'status');
        $user = auth()->user();

        return view('role.index', compact('users', 'role', 'roleStats', 'statusStats', 'user', 'size'));
    }

    public function permit(Request $request)
    {
        $userId = $request->get('user_id');
        $role = $request->get('role');
        if ($userId && $role) {
            DB::table('users')->where('id', $userId)->update(['role' => $role]);
        }
        return redirect()->back();
    }
}
