<?php
/**
 * Created by PhpStorm.
 * User: Cristian
 * Date: 13/07/17
 * Time: 18:33
 */

namespace Sartoric\ModularCms\ViewComposers;

use Sartoric\ModularCms\Models\Menuitem;
use Illuminate\Support\Facades\Route;
//use Illuminate\Contracts\Routing\Registrar as Route;
use Illuminate\View\View;
use Sartoric\ModularCms\Models\User;

class MenuComposer
{
    protected $bcpath;

    public function compose(View $view)
    {
        // DONE Filtrare in base al ruolo utente (va creata tabella e relazione)
        // Retrieve menu items based on User's role
        // If the user is Admin get all the active menu items (even if not assigned to a role)
        if (auth()->user()->isSuperAdmin()) {
            $menuitems = Menuitem::where('active', 1)->get();
        } else {
            $menuitems = auth()->user()->menuitems->where('active', 1);
//            $menuitems=collect([]);
//            foreach (auth()->user()->roles as $role) {
//                foreach ($role->menuitems->where('active', 1) as $item) {
//                    $menuitems->push($item);
//                }
//            }
        }
        // extract the last part of the uri
//        if ($slashpos = strrpos(Route::getcurrentRoute()->uri(), '/')) {
//            $lasturi = substr(Route::getcurrentRoute()->uri(), $slashpos+1);
//        } else {
//            $lasturi = Route::getcurrentRoute()->uri();
//        }

        if ($dotpos = strpos(Route::currentRouteName(), '.')) {
            $lastlevel = substr(Route::currentRouteName(), 0, $dotpos);
        } else {
            $lastlevel = Route::currentRouteName();
        }

        // looks for the lowest level menu item
        $lastcrumb = $menuitems->where('link', $lastlevel)->first();

        $this->bcpath=collect([]);
        $this->buildbcpath($lastcrumb, $menuitems);

        $view->with('menuitems', $menuitems->where('menu', 1));
        $view->with('bcpath', $this->bcpath);
    }

    protected function buildbcpath($lastcrumb, $menuitems)
    {
        if ($lastcrumb) {
            if ($lastcrumb->parent >0) {
                $this->buildbcpath($menuitems->where('id', $lastcrumb->parent)->first(), $menuitems);
            }
            $this->bcpath->push($lastcrumb);
        }
    }
}


