<?php

namespace App\Views;

class MenuGenerator
{
    private string $common_class = 'common_mnu';
    private string $dropdown_class = 'dropdown';
    private array $menu;

    public function __construct(?string $common_class, ?string $dropdown_class)
    {
        $this->common_class = $common_class ?? $this->common_class;
        $this->dropdown_class = $dropdown_class ?? $this->dropdown_class;
        $this->menu = config("menu");
    }

    public function getRawMenu(): array
    {
        return $this->menu;
    }

    public function getMenu(): string
    {
        $uls = $this->createMenu($this->menu);
        return "<ul class='nav navbar-nav'>$uls</ul>";
    }

    private function getCommonBlock(string $class, string $name, ?string $link): string
    {
        return "<li class='$class'><a href='$link'>$name</a></li>";
    }

    private function getDropdownBlock(string $class, string $name, array $children): string
    {
        $submenu = '';
        foreach($children as $child) {
            if($child['visible'] === 1) {
                $submenu .= $this->getCommonBlock($this->common_class, $child['name'], $child['url']);
            }
        }

        return "<li class='$class'>
					<a href='#' class='dropdown-toggle' data-toggle='dropdown'
					role='button' aria-haspopup='true' aria-expanded='false'>$name
						<span class='caret'></span>
					</a><ul class='dropdown-menu'>$submenu</ul>
				</li>";
    }

    private function createMenu(array $menu): string
    {
        $result = '';

        foreach($menu as $arr) {
            $arr['link'] = isset($arr['url']) ? sprintf("/%s", $arr['url']) : null;

            if ($arr['visible'] === 1) {
                if (isset($arr['children']) && (count($arr['children']) > 0)) {
                    $result .= $this->getDropdownBlock($this->dropdown_class, $arr['name'], $arr['children']);
                } else {
                    $result .= $this->getCommonBlock($this->common_class, $arr['name'], $arr['link']);
                }
            }
        }

        return $result;
    }
}
