<?php

function smarty_function_get_order_coupons($params, &$smarty)
{
    if (empty($params['order'])) {
        throw new InvalidArgumentException("Missing parameter 'order' in smarty function 'get_order_coupons'!");
    }

    $order = $params['order'];
    if (!$order->isActive() || !$order->isPaid()) {
        return;
    }

    $order_coupons = [];

    $coupons = sqlQueryBuilder()->select('*')
        ->from('discounts_coupons', 'dc')
        ->andWhere(\Query\Operator::equals(['dc.id_order_purchased' => $order->id]))
        ->sendToMaster()
        ->execute()->fetchAll();
    foreach ($coupons as $coupon) {
        $order_coupons[$coupon['id_order_item']][] = $coupon;
    }

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