<?php

use KupShop\OrderingBundle\Entity\Purchase\PurchaseItemInterface;
use Symfony\Component\Routing\Router;

function smarty_function_get_oc_cart_share_qr_code($params, &$smarty)
{
    /** @var $purchaseState \KupShop\OrderingBundle\Entity\Purchase\PurchaseState */
    if (!($purchaseState = ($params['purchaseState'] ?? false))) {
        throw new \InvalidArgumentException('Purchase state is required');
    }

    $data = [
        'coupons' => $purchaseState->getActiveCoupons(),
        'items' => array_map(fn (PurchaseItemInterface $item) => ($item->getProduct()->variationCode ?? $item->getProduct()->code).' '.$item->getPieces(), $purchaseState->getProducts()),
    ];

    $url = path(
        'kupshop_content_cart_cart_1',
        ['share' => base64_encode(json_encode($data))],
        Router::ABSOLUTE_URL
    );

    $options = new \chillerlan\QRCode\QROptions(['outputBase64' => false]);
    $qr = (new \chillerlan\QRCode\QRCode($options))->render($url);

    $result = ['qr' => $qr, 'url' => $url];

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