<?php

namespace App\Http\Controllers;

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

class PermissionController extends Controller
{

    /**
     * Returns a view showing all permissions
     *
     *@return view
     */
    public function index() : view
    {
        $permissions = Permission::all();
        //fetch service group
        $serviceGroups =IprsNewServiceGroup::select('id', 'service_name')->get();
        return view('permission.permission', ['permissions'=> $permissions, 'serviceGroups' => $serviceGroups]);
    }

    /**
     * Display view form create permissions
     *
     * @return view
     */
    public function create() : view
    {
        // Show the form to create a new post
    }

    /**
     * Store form inputs
     *
     * @param StorePermissionRequest $request
     * @return RedirectResponse
     */
    public function store(StorePermissionRequest $request): RedirectResponse
    {
        $validated =$request->validated();
        $permission = Permission::create([
            'name' => $validated['permission_name'],
            'permission_type'=>$validated['permission_type'],
            'description'=>$validated['description'],
            'service_group_id'=>$validated['service_group_id']
        ]);
        // redirect the user to a different page
        return redirect()->route('permission.index')->with('success', 'Permission created successfully.');
    }

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