<?php

namespace App\Http\Controllers;

use App\Http\Requests\StorePermissionRequest;
use App\Http\Requests\StoreRoleRequest;
use App\Http\Requests\UpdateRoleRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class RoleController extends Controller
{
    /**
     *@return view
     */
    public function index() : view
    {
        $roles = Role::all();
        return view('role.role', ['roles' => $roles]);
    }

    /**
     * @return view
     */
    public function create() : view
    {
        return view('role.roleForm');
    }

    /**
     * @param StoreRoleRequest $request
     * @return RedirectResponse
     */
    public function store(StoreRoleRequest $request)
    {
        // Store
        $validated =$request->validated();
        $role = Role::create([
            'name' => $validated['role_name'],
            'for_contract' => $validated['for_contract'] == "on"
        ]);
        // redirect the user to a different page
        return redirect()->route('role.index')->with('success', 'Role created successfully.');
    }

    /**
     * @param String $id
     * @return view
     */
    public function show(string $id) : view
    {
        //pull permissions
        $permissions = Permission::all();
        $role = Role::find($id);
        return view('role.role-permission', ['role' => $role, 'permissions'=>$permissions ]);
    }

    /**
     * @param Role $role
     * @return view
     */
    public function edit(Role $role): view
    {
        return view('role.roleEdit', ['role'=>$role]);
    }

    /**
     * @param UpdateRoleRequest $request
     * @param Role $role
     * @return RedirectResponse
     */
    public function update(UpdateRoleRequest $request, Role $role): RedirectResponse
    {
        $validated =$request->validated();
        $role->update([
            'name' => $validated['role_name'],
            'for_contract' => $validated['for_contract'] == "on"
        ]);
        // redirect the user to a roles
        return redirect()->route('role.index')->with('success', 'Role updated!');
    }

    /**
     * @param String $id
     * @return RedirectResponse
     */
    public function destroy(string $id): RedirectResponse
    {
        // Delete a specific post
        $delete= Role::find($id);
        $delete->delete();
        //redirect
        return redirect()->route('role.index')->with('Deleted', 'Role removed !');
    }

    /**
     *
     * @param Request $request
     * @param $role_id
     * @return RedirectResponse
     */
    public function addPermissionToRole(Request $request, $role_id) : RedirectResponse
    {
        $role = Role::find($role_id);
        $data =$request->validate([
            'perm' => 'required'
        ]);
        $role->syncPermissions($data);
        return redirect()->route('role.index')->with('success', 'Role Permissions updated.');
    }
}
