<?php

namespace App\Http\Controllers\Spatie;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class RoleController extends Controller
{
    public function __construct()
    {
        $this->middleware(['permission:roles.index'])->only('index');
        $this->middleware(['permission:roles.create'])->only('save');
        $this->middleware(['permission:roles.edit'])->only('update');
        $this->middleware(['permission:roles.delete'])->only('delete');
    }

    public function index()
    {
        $title = "role";
        $roles = Role::orderBy('id', 'desc')->get();
        $permissions = Permission::latest()->get();

        return view('spatie.role', compact('title','roles','permissions'));
    }

    public function save(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|unique:roles'
        ]);

        $role = Role::create([
            'name' => $request->input('name')
        ]);

        //assign permission to role
        $role->syncPermissions($request->input('permissions'));

        if($role){
            //redirect dengan pesan sukses
            return redirect()->route('role')->with(['success' => 'Data Berhasil Disimpan!']);
        }else{
            //redirect dengan pesan error
            return redirect()->route('role')->with(['error' => 'Data Gagal Disimpan!']);
        }
    }

    public function update(Request $request, Role $role)
    {
        $this->validate($request, [
            'name' => 'required|unique:roles,name,'.$role->id
        ]);

        $role = Role::findOrFail($role->id);
        $role->update([
            'name' => $request->input('name')
        ]);

        //assign permission to role
        $role->syncPermissions($request->input('permissions'));

        if($role){
            //redirect dengan pesan sukses
            return redirect()->route('role')->with(['success' => 'Data Berhasil Disimpan!']);
        }else{
            //redirect dengan pesan error
            return redirect()->route('role')->with(['error' => 'Data Gagal Disimpan!']);
        }
    }

    public function delete(Role $role)
    {
        $role->delete();

        return redirect()->route('role')->with('success', 'Data Berhasil Dihapus');
    }
}
