<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Spatie\Permission\Models\Permission;

class PermissionController extends Controller
{
    public function __construct()
    {
        $this->middleware(["auth"]);
        $this->middleware(["lang"]);
    }

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        $permission = Permission::query()->paginate($request->input("limit", 20));

        return Response::detect("permission.index", [ "permission" => $permission ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        return Response::detect("permission.create");
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param Request $request
     * @return Response
     */
    public function store(Request $request)
    {
        $requestBody = $request->validate([
            "name" => "required|max:255",
            "link" => "required|max:255"
        ]);

        $permission = new Permission($requestBody);
        $permission->save();

        return Response::detect("permission.store");
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        return Response::detect("permission.show", [ "permission" => $id]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        $permission = Permission::find($id);

        return Response::detect("permissions.edit", [
            "permission" => $permission
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param Request $request
     * @param int $id
     * @return void
     */
    public function update(Request $request, $id)
    {
        $data = $request->validate([
            "time" => "required"
        ]);

        $permission = Permission::find($id);

        $permission->update($data);

        $permission->save();

        return Response::detect("permissions.edit", [
            "permission" => $permission
        ]);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return void
     */
    public function destroy($id)
    {
        $permission = Permission::find($id);
        $permission->delete();

        return Response::detect("permissions.destroy");
    }
}
