<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Spatie\Permission\Guard;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class PermissionsController extends Controller
{
    public function index()
    {
        $permissions = Permission::getPermissions();
        return response()->json([
            'message' => 'success',
            'data' => $permissions
        ], 201);
    }

    public function create()
    {
        return response()->json([
           'data' => [
               'guard_name' => [
                   'web', 'auth', 'cors:api'
               ]
           ]
        ]);

    }

    public function store(Request $request)
    {
        $validData = $request->validate([
            'name' => 'required',
            'guard_name' => 'required'
        ]);

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

        return $permission;
    }

    public function edit($id)
    {
        $perm = Permission::findById($id);
        return response()->json([
            'data' => $perm
        ]);
    }

    public function update(Request $request, $id)
    {
        $perm = Permission::findById($id);

        $validData = $request->validate([
            'name' => 'required',
        ]);

        $perm->update($validData);

        return response()->json([
            'message' => 'success',
            'data' => $perm
        ]);
    }

    public function delete(Request $request, $id)
    {
        $permission = Permission::find($id);
        $permission->delete();
//        Artisan::call('optimize:clear');
        return response()->json([
            'message' => 'permission has been deleted.',
        ]);
    }
}
