<?php

namespace App\Http\Controllers\Admin;

use App\Models\Menu;
use App\Http\Requests\MenuRequest;

class MenuController extends AdminController
{
    protected $seperator = '&nbsp;&nbsp;&nbsp;';

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = Menu::get()->toHierarchy();

        return view('admin.menu.menu_index', compact('data'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $menuNests = Menu::getNestedList('name', 'id', $this->seperator);

        return view('admin.menu.menu_add', compact('menuNests'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param MenuRequest $request
     * @return \Illuminate\Http\Response
     */
    public function store(MenuRequest $request)
    {
        $node = Menu::create($request->all());
        $request->input('parent_id') && $node->makeChildOf($request->input('parent_id'));

        if ($node) {
           return redirect('admin/menu')->with('success', '菜单添加成功');
        }

        return back()->withInput()->with('error', '菜单添加失败');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $menu = Menu::find($id);
        $nests = Menu::getNestedList('name', 'id', $this->seperator);

        return view('admin.menu.menu_edit', compact('menu', 'nests'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param MenuRequest $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(MenuRequest $request, $id)
    {
        $menu = Menu::find($id);
        $result = $menu->fill($request->all())->save();

        if ($result) {
            if ($request->input('parent_id')) {
                // 待优化@可以判断是否改变
                $menu->makeChildOf($request->input('parent_id'));
            } else {
                // 根节点
                $menu->makeRoot();
            }
            return redirect('admin/menu')->with('success', '菜单修改成功');
        }

        return back()->withInput()->with('error', '菜单修改失败');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $ids    = array_str($id);
        $result = Menu::whereIn('id', $ids)->delete();

        if($result) {
            flash('success', '菜单删除成功！');
            return response()->json(['code' => 200]);
        }

        return response()->json(['code' => 500]);
    }
}
