<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Permission;

class PermissionsController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:permission_index|permission_create|permission_edit|permission_destroy', ['only' => ['index', 'show']]);
        $this->middleware('permission:permission_create', ['only' => ['create', 'store']]);
        $this->middleware('permission:permission_edit', ['only' => ['edit', 'update']]);
        $this->middleware('permission:permission_destroy', ['only' => ['destroy']]);
    }

    public function index()
    {
        return view('role.permissionList',[
            'list' => Permission::all()
        ]);
    }

    public function create()
    {
        return view('role.createPermission',[
            'page_title' => 'Create New Permission'
        ]);
    }


    public function store(Request $request)
    {
        $request->validate([
            'status' => 'required'
        ]);


        Permission::create([
            'name'      => $request->name,
            'status'    => $request->status
            ]);

        // DB::table('permissions')->insert(['status' => $request->status ]);

        return redirect()->back()->with('success_message','Permission Created successfully');
    }


    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        return view('role.editPermission',[
            'page_title' => 'Edit Permission',
            'permission' => Permission::find($id)
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        Permission::whereId($id)->update([
            'name' => $request->name,
            'status' => $request->status
        ]);

        return redirect()->back()->with('success_message','Permission updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
