<?php

/*
 * Smarty plugin
 * -------------------------------------------------------------
 * Type:     function
 * Name:     eval
 * Purpose:  evaluate a template variable as a template
 * -------------------------------------------------------------
 */

use KupShop\ContentBundle\Util\MenuUtil;
use KupShop\KupShopBundle\Context\LanguageContext;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

function fetchMenuLinks($parent_id = 0, $level = 0)
{
    $menuLinks = [];

    $languageContext = ServiceContainer::getService(LanguageContext::class);

    $qb = sqlQueryBuilder()
        ->select('ml.*')
        ->from('menu_links', 'ml')
        ->andWhere(
            \Query\Translation::joinTranslatedFields(
                \KupShop\I18nBundle\Translations\MenuLinksTranslation::class,
                function ($qb, $columnName, $translatedField, $langID) use ($languageContext) {
                    if ($columnName === 'name_short' && $langID != $languageContext->getDefaultId()) {
                        $translatedField = $translatedField ?? 'ml.'.$columnName; // no translations
                        $qb->addSelect("{$translatedField} AS `{$columnName}`");

                        return false;
                    }

                    return;
                },
                ['name', 'name_short', 'link', 'url', 'figure']
            )
        )
        ->orderBy('list_order', 'ASC');

    if ($parent_id > 0) {
        $qb->andWhere(\Query\Operator::equals(['parent' => $parent_id]));
    } else {
        $qb->andWhere('ml.parent IS NULL AND ml.id=ml.id_menu');
    }

    $SQL = $qb->execute();

    foreach ($SQL as $row) {
        if ($row['figure'] == 'N') {
            continue;
        }

        $url = ($row['type'] == MenuUtil::TYPE_PAGE) ? createScriptURL(['URL' => $row['url']]) : $row['link'];

        $url = htmlspecialchars($url);

        if ($parent_id === 0 && $level === 0) {
            $item = fetchMenuLinks($row['id'], $level);
        } else {
            $item = [
                'id' => $row['id'],
                'title' => !empty($row['name_short']) ? $row['name_short'] : $row['name'],
                'url' => $url,
                'target' => $row['target'],
                'children' => fetchMenuLinks($row['id'], $level + 1),
                'level' => $level,
                'selected' => false,
                'data' => json_decode($row['data'] ?? '', true) ?? [],
            ];
        }

        $menuLinks[$row['id']] = $item;
    }
    unset($row);
    sqlFreeResult($SQL);

    return $menuLinks;
}

function updateMenuLinks(&$menu)
{
    global $ctrl;

    $selected = false;
    $currUrl = html_entity_decode($ctrl['currUrl']['Abs']);
    $currUrlRel = html_entity_decode($ctrl['currUrl']['Rel']);

    foreach ($menu as &$submenu) {
        $itemSelected = false;

        // Select if subitem selected
        if (!empty($submenu['children'])) {
            $itemSelected |= updateMenuLinks($submenu['children']);
        }

        // Select if url matches
        $decodedUrl = html_entity_decode($submenu['url']);
        $itemSelected |= $decodedUrl == $currUrl || $decodedUrl == $currUrlRel;

        $submenu['selected'] = $itemSelected;

        $selected |= $itemSelected;
    }

    return $selected;
}

function smarty_function_insert_menu($params, &$smarty)
{
    $default = [
        'level' => 0,
        'level_max' => 99,
        'template' => 'block.menu.tpl',
        'menu_id' => 1,
        'submenu' => [],
    ];

    $params = array_merge($default, $params);

    // Get Own Menu structures
    static $menuLinks = null;

    $languageContext = ServiceContainer::getService(LanguageContext::class);
    $cacheName = 'menu-'.$languageContext->getActiveId();

    if (empty($menuLinks)) {
        $menuLinks = getCache($cacheName);
    }

    if (empty($menuLinks)) {
        $menuLinks = fetchMenuLinks();
        setCache($cacheName, $menuLinks);
    }

    // discover menu_id by label
    static $menuLabels = null;
    if (is_null($menuLabels)) {
        $menuLabels = getCache('menu-groupLabels');
        if (empty($menuLabels)) {
            $menuLabels = sqlFetchAll(
                sqlQueryBuilder()->select('id, code')->from('menu_links')
                    ->where('type=:type AND code IS NOT NULL')
                    ->setParameter('type', MenuUtil::TYPE_GROUP)->execute(),
                ['code' => 'id']
            );
            setCache('menu-groupLabels', $menuLabels);
        }
    }
    if (!empty($params['label']) && isset($menuLabels[$params['label']])) {
        $params['menu_id'] = $menuLabels[$params['label']];
    } elseif (!empty($params['label'])) {
        return "Neznámý label: {$params['label']}";
    }

    if (!isset($menuLinks[$params['menu_id']])) {
        return "Neznámé menu_id: {$params['menu_id']}";
    }

    // Get correct menu
    $menu = $menuLinks[$params['menu_id']];
    $parent = null;

    updateMenuLinks($menu);

    if (!empty($params['submenu'])) {
        foreach ($params['submenu'] as $item) {
            $parent = $menu[$item];
            $menu = $parent['children'];
        }
    } elseif ($params['level'] > 0) {
        for ($i = 0; $i < $params['level']; $i++) {
            $selected = null;
            foreach ($menu as $submenu) {
                if ($submenu['selected']) {
                    $selected = $submenu;
                    break;
                }
            }

            if (empty($selected)) {
                return;
            }

            $parent = $selected;
            $menu = $selected['children'];
        }
    }

    $params['file'] = $params['template'];
    $params['menu'] = $menu;
    $params['parent'] = $parent;

    $_smarty_tpl_vars = $smarty->tpl_vars;

    echo $smarty->_subTemplateRender(
        $params['file'],
        $smarty->cache_id,
        $smarty->compile_id,
        0,
        null,
        $params,
        0,
        false
    );

    $smarty->tpl_vars = $_smarty_tpl_vars;
}

/* vim: set expandtab: */
