<?php

/*
 * Smarty plugin
 * -------------------------------------------------------------
 * Type:     function
 * Name:     get_action_sections
 * Purpose:  get root sections with products in action
 * -------------------------------------------------------------
 */

use KupShop\CatalogBundle\Section\SectionTree;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

function smarty_function_get_action_sections($params, &$smarty)
{
    $action_sections = [];

    $sections = ServiceContainer::getService(SectionTree::class)->getTree();
    foreach ($sections as $section) {
        if (isset($params['id_section']) && $section['id'] != $params['id_section']) {
            continue;
        }

        $actions = sqlQueryBuilder()->select('COUNT(*) cnt')
         ->fromProducts()->joinSectionsOnProducts()
         ->where(Query\Operator::inIntArray(getDescendantCategories($section['id']), 'ps.id_section'))
         ->andWhere(Query\Operator::findInSet(['A'], 'p.campaign'))
         ->execute()->fetch();

        $action_sections[$section['id']] = $actions['cnt'];
    }

    if (!empty($params['assign'])) {
        $smarty->assign($params['assign'], $action_sections);
    } else {
        return $action_sections;
    }
}
