<?php

/*
 * Smarty plugin
 * -------------------------------------------------------------
 * Type:     function
 * Name:     get_slider
 * Purpose:  get a slider of known name or id
 * -------------------------------------------------------------
 */

use KupShop\KupShopBundle\Context\LanguageContext;
use KupShop\KupShopBundle\Util\Contexts;

/**
 * @param array  $params
 * @param Smarty $smarty
 *
 * @return array
 */
function smarty_function_get_ratings($params, &$smarty)
{
    $activeLanguage = null;
    $rating = false;
    $tmpSum = 0;
    $ratingCount = 0;

    if (findModule(Modules::TRANSLATIONS)) {
        $languagesContext = Contexts::get(LanguageContext::class);
        $activeLanguage = $languagesContext->getActiveId();
    }

    $review = \KupShop\KupShopBundle\Util\Compat\ServiceContainer::getService(\KupShop\CatalogBundle\Util\ReviewsUtil::class);
    $reviews = $review->getForProduct($params['id_product'], $activeLanguage);

    foreach ($reviews as $index => $item) {
        if (isset($item['rating'])) {
            $tmpSum += $item['rating'];
            $ratingCount++;
        }

        if (!empty($params['skip_empty']) && empty($item['user_name']) && empty($item['name'])) {
            unset($reviews[$index]);
        }

        if (!$review->hasComment($item)) {
            unset($reviews[$index]);
        }

        if (findModule(Modules::TRANSLATIONS) && $activeLanguage != $item['id_language']) {
            if (empty($params['languages'][$activeLanguage]) || !in_array($item['id_language'], $params['languages'][$activeLanguage])) {
                if (!$review->hasTranslatedComment($item)) {
                    unset($reviews[$index]);
                }
            }
        }
    }

    if ($ratingCount > 0) {
        $rating = $tmpSum / $ratingCount;
    }

    $ret = [
        'rating' => $rating,
        'rating_count' => $ratingCount,
        'reviews' => $reviews,
        'user_already_rated' => $review->hasUserAlreadyRated($params['id_product']),
    ];

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