<?php 

namespace App\Http\ViewComposers;

use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Contracts\View\View;
use Auth;
use Route;
use Session;
use App\Models\Func;
use App\Models\GroupPermission;

class AdminComposer {

    /**
     * The user repository implementation.
     *
     * @var UserRepository
     */

    public function __construct(Request $request)
    {
        $this->request = $request;
        $this->editable = false;
    }
    /**
     * Bind data to the view.
     *
     * @param  View  $view
     * @return void
     */


    public function compose(View $view)
    {
        if(null==Auth::user()) return;
        $func = [];
        if(Session::has("permission")) {
            $permission = Session::get("permission");
        } else {
            if(Auth::user()->group_id==1) {
                $permission = $this->getPermissions(Func::orderBy('sort')->get());
            } else {
                $permission = $this->getPermissions(Auth::user()->group->permissions);
            }
            Session::put("permission",$permission);
        }

        foreach(Func::whereNull("parent_id")->orderBy('sort')->get() as $v) {
            if( Auth::user()->id==1 || ( Auth::user()->id>1 && in_array($v->slug, $permission) ) ) 
                $func[] = $v;
        }

        if(Auth::user()->group_id==1) {
            $editable = true;
        } else {
            $editable = false;
            foreach (GroupPermission::whereGroupId(Auth::user()->group_id)->get() as $k => $v) {
                if( null!=$this->request->segment(2) && $v->func->slug==$this->request->segment(2) )
                    $editable = $v->permission==2?true:false;
            }
        }

        $view->with([
            'navs' => $func,
            'editable' => $editable
        ]);
    }

    public function getPermissions($permissions)
    {
        $permission = array();

        foreach($permissions as $p) {
            if( $p->permission>=1) {
                $permission[] = $p->func->slug;
            }
            
        }

        return $permission;
    }
}
