<?php

namespace Fivable\Buildable\Controllers;

use Fivable\Buildable\Models\BuildableMenu;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Fivable\Scaffolding\Controllers\ApiController;

class BuildableMenuController extends ApiController
{
    /**
     * Display a listing of the resource.
     *
     * @return JsonResponse
     */
    public function index() : JsonResponse
    {
        $this->authorizeForUser($this->user(), 'viewIndex', BuildableMenu::class);

        $menus = BuildableMenu::query()->with('rootPage', 'metas')->get();

        return response()->json([
            'menus' => $menus,
        ]);
    }

    /**
     * Get a specific BuildableMenu
     * @param  BuildableMenu  $buildableMenu
     * @return JsonResponse
     */
    public function show(BuildableMenu $buildableMenu) : JsonResponse
    {
        $this->authorizeForUser($this->user(), 'view', $buildableMenu);

        return response()->json([
            'menu' => $buildableMenu,
        ]);
    }

    /**
     * Create multiple BuildableMenus
     * @param Request $request
     * @return JsonResponse
     */
    public function store(Request $request) : JsonResponse
    {
        $this->authorizeForUser($this->user(), 'create', BuildableMenu::class);

        $newMenus = BuildableMenu::createMenus($request->all());

        return response()->json([
            'new_menus' => $newMenus,
        ]);
    }

    /**
     * Update multiple BuildableMenus
     * @param  Request  $request
     * @return JsonResponse
     */
    public function update(Request $request) : JsonResponse
    {
        $this->authorizeForUser($this->user(), 'update', BuildableMenu::class);

        $buildableMenus = BuildableMenu::updateMenus($request->all());

        return response()->json([
            'updated_menus' => $buildableMenus->updatedMenus,
            'new_menus' => $buildableMenus->newMenus,
        ]);
    }

    /**
     * Delete a specific BuildableMenu
     * @param  BuildableMenu  $buildableMenu
     * @return JsonResponse
     * @throws \Exception
     */
    public function destroy(BuildableMenu $buildableMenu) : JsonResponse
    {
        $this->authorizeForUser($this->user(), 'delete', $buildableMenu);

        $buildableMenu->delete();

        return response()->json([
            'deleted_menu' => $buildableMenu,
        ]);
    }
}
