<?php

class core_start_menu extends module {

    public $templBlade = 'core_start_menu';

    public function _on_() {
        global $blade, $auth;

        $blade2 = clone $blade;

        $data = [];

        $obj = new cobject(__REAL_CAT_OBJ_);
        $db2 = $obj->getDB()->q($obj->getSelect(' AND _sys_unvisible = 0  ORDER BY `_sys_order` ASC '));
        $menuItems = $db2->fetchAll();
        $tree = $this->buildTree($menuItems);

        $tree = $tree[0]['children'];
        $data['html'] = $this->renderTree($tree);

        if ($auth->is_login()) {
            $favIds = (array)json_decode($auth->user_obj->get('favorite_menu'), true);
            if (!$favIds) {
                $favIds = [];
            }
        } else {
            $favIds = [];
        }
        if (is_array($favIds) && !empty($favIds)) {
            $db2 = $obj->getDB()->q($obj->getSelect(' AND `cat_id` in ("' . implode('", "', $favIds) . '") ORDER BY field(`cat_id`, "' . implode('", "', $favIds) . '") '));
            $favLinks = $db2->fetchAll();
        } else {
            $favLinks = [];
        }
        $data['favLinks'] = $favLinks;




        return $blade2->runChild($this->getBladeTempl('line_menu'), $data);
    }

    // Функции для построения дерева и рендеринга в HTML
    function buildTree(&$elements, $parentCat = '') {
        $branch = array();

        foreach ($elements as &$element) {
            if ($element['parent_cat'] == $parentCat) {
                $children = $this->buildTree($elements, $element['cat_id']);
                if ($children) {
                    $element['children'] = $children;
                }
                $branch[] = $element;
                unset($element);  // Удаляем элемент после добавления в дерево для оптимизации
            }
        }
        return $branch;
    }

    function renderTree($tree) {
        global $cat, $auth;

        $curFavorites = json_decode($auth->user_obj->get('favorite_menu'), true);

        $html = '<ul>';
        foreach ($tree as $branch) {
            $html .= '<li>';
            $html .="<a href=\"?cat={$branch['cat_id']}\" title=\"{$branch['cat_name']}\" class=''>
                            <img src=\"{$branch['img']}\" class=\"coreMenuIcon\"/>{$branch['cat_name']} <span class=\"badge badge-primary badge-{$branch['cat_id']}\"></span>
                            ";
            if (in_array($branch['cat_id'], $curFavorites)) {
                $html .= "<i title='Добавить / убрать из избранного' class=\"favind-{$branch['cat_id']} text-muted small fas fa-star\" onClick='toggleCoreFav(\"{$branch['cat_id']}\"); return false;'></i>";
            } else {
                $html .= "<i title='Добавить / убрать из избранного' class=\"favind-{$branch['cat_id']} text-muted small far fa-star\" onClick='toggleCoreFav(\"{$branch['cat_id']}\"); return false;'></i>";
            }
            $html .= "</a>";
            if (!empty($branch['children'])) {
                $html .= $this->renderTree($branch['children']);
            }
            $html .= '</li>
';
        }
        $html .= '</ul>';
        return $html;
    }

}

?>