<?php

namespace Sargilla\FlatLab\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Sargilla\FlatLab\FlatLabMenu as Menu;
use Yajra\Datatables\Facades\Datatables;

class MenuController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }
    
    public function index()
    {
        return view('flatlab::menus.index');
    }

    public function store(Request $request)
    {
         $this->validate(request(),[
            'nombre'=> 'required',
            'tipo' => 'required',
            'destino'=> 'required'
        ]);
        request()->request->add(['alias'=> str_slug(request()->nombre)]);

        Menu::create(request()->all());
        
        return ['mensaje'=> 'Menu Creado correctamente!'];
    }

    public function show(Menu $menu)
    {
       return $menu;
    }

    public function update(Request $request, Menu $menu)
    {
        $this->validate(request(),[
            'nombre'=> 'required',
            'tipo' => 'required',
            'menu' => 'required',
            'destino'=> 'required'
        ]);
        request()->request->add(['alias'=> str_slug(request()->nombre)]);

        $menu->update(request()->all());
        
        return ['mensaje'=> 'Menu Actualizado correctamente!'];
    }

    public function destroy(Menu $menu)
    {
        $menu->delete();
        return ['mensaje'=> 'Menu Borrado correctamente!'];
    }
    /**
     *  getMenus
     */
    public function getMenus()
    {
        if (!request()->ajax()) {
             return redirect()->route('menus.index');
        }
        return Datatables::of(Menu::all())
        	->editColumn('padre_id', function($query){
                if($query->padre_id == 0)
                    return null;
                else
                    return $query->padre->nombre;
            })
            ->editColumn('icono', function($query){
            	return '<i class="fa '.$query->icono.'"></i>';
            })
            ->addColumn('acciones', function($query){
                return "<div class='acciones' data-id='$query->id' >
                    <button class='btn btn-xs btn-primary' 
                        data-toggle='modal' data-target='#menu-modal' data-action='editar' title='Editar Menu' ><i class='fa fa-pencil'></i></button>
                    <button class='btn btn-xs btn-danger btn-xs'
                       data-toggle='modal' data-target='#menu-modal' data-action='borrar' title='Borrar Menu'><i class='fa fa-times'></i></button>
                </div>";
            })
            ->rawColumns(['acciones','icono'])
            ->make(true);    
    }
}
