<?php

namespace App\Http\Controllers;

use App\Models\UserRole;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class UserRoleController extends Controller
{

    const ROLES_BLADE = 'src/user_roles';
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $userroles = UserRole::all();

        return view(UserRoleController::ROLES_BLADE, ['userroles' => $userroles,
            'selectedUserRole' => null]);
    }


    /**
     * Search for selected user roles.
     *
     * @return \Illuminate\Http\Response
     */
    public function search(Request $request){

        $keyword = $request->keyword;
        $userroles = DB::select(Db::raw("select * from user_role where 
        role like '%".$keyword."%'"));

        return json_encode($userroles);
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function save(Request $request)
    {
        $data = $request->validate([
            'role' => 'required|max:255'
        ]);
    
        $data['created_by'] = Auth::user()->user_id;
        
        $selected = $request->selected_userrole;
    
        if($selected){
            $userRole = tap(UserRole::where('user_role_id',
             $selected)->update($data));
        }else {
            $userRole = tap(new UserRole($data))->save();
        }
        return redirect('/userroles');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\UserRole  $userRole
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $userRoleId = $id;
        $selectedUserRole = UserRole::find($userRoleId);
        $userroles = UserRole::all();

        return view(UserRoleController::ROLES_BLADE, 
            ['userroles' => $userroles,
            'selectedUserRole' => $selectedUserRole]);
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\UserRole  $userRole
     * @return \Illuminate\Http\Response
     */
    public function del(Request $request)
    {
        $userRoleId = $request->deleteuserrole;
        $userRole = UserRole::find($userRoleId);
        $userRole->delete();
        $userroles = UserRole::all();

        return view(UserRoleController::ROLES_BLADE, 
            ['userroles' => $userroles, 'selectedUserRole' => null]);
    }
}