<?php

/*
 * Smarty plugin
 * -------------------------------------------------------------
 * Type:     function
 * Name:     get_campaigns_in_sections
 * Purpose:  get count of campaign products in a section
 * -------------------------------------------------------------
 */

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

function smarty_function_get_campaigns_in_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()
            ->joinProducersOnProducts()
            ->andWhere(Query\Operator::inIntArray(getDescendantCategories($section['id']), 'ps.id_section'))
            ->andWhere(Query\Operator::findInSet([$params['campaign']], 'p.campaign'))
            ->andWhere("p.figure = 'Y' AND p.in_store > 0 AND (p.id_model IS NOT NULL) ")
            ->groupBy('p.id_model')->execute()->rowCount();

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

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