<?php

function smarty_function_get_product_gifts($params, &$smarty)
{
    $product = $params['product'] ?? false;
    if (!$product) {
        return null;
    }

    $gifts = [];
    if (findModule(Modules::ORDERS, Modules::SUB_ORDERS_FROM_PURCHASE_STATE)) {
        // Gifts loaded from PurchaseItem from additionalItems
        foreach ($product->getAdditionalItems() as $item) {
            if ($item->note['item_type'] === 'gift') {
                $gifts[] = $item->getProduct();
            }
        }
    } else {
        if (is_array($product)) {
            $gifts = $product['product']['gifts'] ?? [];
        } else {
            $gifts = $product->getProduct()['gifts'] ?? [];
        }
    }

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