<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Spatie\Permission\Guard;
use Illuminate\Support\Facades\Artisan;
use Spatie\Permission\Models\Permission;

use Illuminate\Routing\Controller;

class PermissionController extends Controller
{

    public function __construct() {
    $this->middleware('can:permission.index')->only('index','show');
    $this->middleware('can:permission.create')->only('create','store');
    $this->middleware('can:permission.edit')->only('edit','update');
    $this->middleware('can:permission.destroy')->only('destroy');
    }

    public function index()
    {
        $permissions = Permission::all();
        return view('permission.index',compact('permissions'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('permission.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        try {
            $request['guard_name'] ??= Guard::getDefaultName(static::class);

        $permission= Permission::create($request->all());

        Artisan::call('cache:clear');

        return redirect()->route('permission.edit',compact('permission'))->with('info', 'Permiso creado exitosamente.');
        } catch (\Throwable $th) {
        return redirect()->route('permission.create')->with('info', 'Falta algun dato o el permiso ya se encuentra creado.');

        }

    }

    public function show(Permission $permission)
    {
        return view('permission.show',compact('permission'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Permission $permission)
    {
        return view('permission.edit',compact('permission'));
    }

    public function update(Request $request, Permission $permission)
    {
        $permission->update($request->all());
        return redirect()->route('permission.edit',compact('permission'))->with('info','Se modificó el permiso correctamente');
    }

    public function destroy(Permission $permission)
    {
        $permission->delete();
        session()->flash('swal',[
            'icon'=>'success',
            'title'=>'Eliminado!',
            'text'=>'Se ha eliminado el registro correctamente'
        ]);
        return redirect()->route('permission.index');
    }

}
