<?php

namespace Sartoric\ModularCms\Controllers\Layouts;

use Sartoric\ModularCms\Models\Role;
use Sartoric\ModularCms\Models\Menuitem;
use Sartoric\ModularCms\Models\Permission;
use Sartoric\ModularCms\Controllers\Controller;
use Illuminate\Http\Request;
use DB;
use Validator;
use Session;

class RoleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $roles = Role::all();
        return view('sartoric/modularcms::layouts.roles.index', compact('roles'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $role = new Role;
        $rolemenus = collect([]);
        $menuitems = Menuitem::where('active', 1)->get();
        $rolepermissions = collect([]);
        $permitems = Permission::all();
        return view('sartoric/modularcms::layouts.roles.create', compact(['role', 'menuitems', 'rolemenus',
                                                           'permitems', 'rolepermissions']));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $this->validator($request->all())->validate();

        $role = null;

        try {
            DB::transaction(function () use (&$role, $request) {

                $role = Role::create([
                    'name' => request('name'),
                    'description' => request('description'),
                ]);

                $role->menuitems()->sync(request('menulist'));

                $role->permissions()->sync(request('permlist'));

                $role->save();

                //TODO : Eliminare exception di test
                //throw new \Exception('Errore durante il salvataggio');
            });
        } catch (\Exception $err) {
            return back()->with('notify', $this->notifArray('DB', 'error', $err->getMessage(), true));
        }
        return redirect()->route('roles.edit', $role)
            ->with('notify', $this->notifArray('DB', 'success', __('Ruolo creato con successo')));
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Role  $role
     * @return \Illuminate\Http\Response
     */
    public function show(Role $role)
    {
        $rolemenus = $role->menuitems->pluck('id');
        $menuitems = Menuitem::where('active', 1)->get();
//        $rolepermissions = $role->permissions->pluck('id');
//        $permitems = Permission::all();
        return view('sartoric/modularcms::layouts.roles.edit', compact(['role', 'menuitems', 'rolemenus']));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Role  $role
     * @return \Illuminate\Http\Response
     */
    public function edit(Role $role)
    {
        $rolemenus = $role->menuitems->pluck('id');
        $menuitems = Menuitem::where('active', 1)->get();
        $rolepermissions = $role->permissions->pluck('id');
        $permitems = Permission::all();
        return view('sartoric/modularcms::layouts.roles.edit', compact(['role', 'menuitems', 'rolemenus',
                                                          'permitems', 'rolepermissions']));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Role  $role
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Role $role)
    {

        if (!$request->user()->can('update', $role)) {
            //return back()->with('notify',$this->notifArray('DB', 'info', __('Operazione non consentita'), true));
            abort(401);
        }

        $this->validator($request->all())->validate();

        try {
            DB::transaction(function () use ($role, $request) {

                $role->fill([
                    'name' => request('name'),
                    'description' => request('description'),
                ]);

                $role->menuitems()->sync(request('menulist'));

                $role->permissions()->sync(request('permlist'));

                $role->save();

                //TODO : Eliminare exception di test
                //throw new \Exception('Errore durante il salvataggio');
            });
        } catch (\Exception $err) {
            return back()->with('notify', $this->notifArray('DB', 'error', $err->getMessage(), true));
        }
        return redirect()->route('roles.edit', $role)
               ->with('notify', $this->notifArray('DB', 'success', __('Ruolo aggiornato con successo')));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Role  $role
     * @return \Illuminate\Http\Response
     */
    public function destroy(Role $role)
    {
        if (!auth()->user()->can('delete', $role)) {
            abort(401);
        }
// TODO : Gestire detach
        try {
            $role->delete();
        } catch (\Exception $err) {
            return back()->with('notify', $this->notifArray('DB', 'error', $err->getMessage(), true));
        }
        return redirect()->route('roles.index', $role)
            ->with('notify', $this->notifArray('DB', 'success', __('Ruolo eliminato con successo')));
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    public function validator(array $data)
    {
        return Validator::make($data, [
            'name'         => 'required|string|max:255',
            'description'  => 'nullable|string|max:255',
            'menulist'     => 'required|array',
            'permlist'     => 'array',
        ]);
    }
}
