<?php

namespace App\Repositories\Core\Menu;

use Illuminate\Support\Facades\Auth;
use Lavary\Menu\Builder as LavaryMenuBuilder;

class Builder extends LavaryMenuBuilder
{
    private $root = [];

    public function add($title, $options = '')
    {
        $title = sprintf('<span>%s</span>', $title);

        $id = $options['id'] ?? $this->id();

        $item = new Item($this, $id, $title, $options);

        if (isset($options['icon'])) {
            $item->icon($options['icon']);
        }

        if (isset($options['role']) || isset($options['permission'])) {
            $ability = ['admin'];
            if (isset($options['role'])) {
                $ability += explode(',', $options['role']);
            }

            $permission = null;
            if (isset($options['permission'])) {
                $permission = explode(',', $options['permission']);
            }

            $currentUser = Auth::user();

            if ($currentUser && $currentUser->ability($ability, $permission)) {
                $this->items->push($item);
            }
        } else {
            $this->items->push($item);
        }

        return $item;
    }

    public function addTo($id, $title, $options = '')
    {
        $parent = $this->whereId($id)->first();

        if (isset($parent)) {
            if (! isset($this->root[$parent->id])) {
                $parent->attr(['url' => '#', 'class' => 'treeview']);
                $this->root[$parent->id] = true;
            }

            $item = $parent->add($title, $options);
        } else {
            $item = $this->add($title, $options);
        }

        $item->icon('circle-o');

        return $item;
    }
}
