<?php

namespace App\Http\Controllers\Admin;

use App\Models\Menu;
use App\Models\Permission;
use App\Http\Requests\PermissionRequest as Request;

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

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data     = Permission::with('menus')->latest('id')->paginate(20);
  
        return view('admin.permission.permission', compact('data'));
    }

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

        return view('admin.permission.permission_create', compact('menus'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request\PermissionRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $result  = Permission::create($request->all());

        if ($result) {
           return redirect('admin/permission')->with('success', '添加权限成功');
        }

        return back()->withInput($request->all())->with('error', '添加权限失败');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

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

        $menus = Menu::getNestedList('name', 'id', $this->seperator);

        return view('admin.permission.permission_edit', compact('permission', 'menus'));
    }

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

        if ($result) {
           return redirect('admin/permission')->with('success', '修改成功');
        }

        return back()->withInput($request->all())->with('error', '修改失败');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $ids    = array_str($id);

        $result = Permission::whereIn('id', $ids)->delete();

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

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