<?php

/*
 * Smarty plugin
 * -------------------------------------------------------------
 * Type:     function
 * Name:     eval
 * Purpose:  evaluate a template variable as a template
 * -------------------------------------------------------------
 */

use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\MarketingBundle\TrustedShop\TrustedShopProvider;

function smarty_function_send_trusted_shop($params, &$smarty)
{
    if (empty($params['order']) || empty($params['apikey'])) {
        return;
    }

    $order = $params['order'];

    if ($order->invoice_country == 'RO') {
        $url = 'https://www.compari.ro/';
    } elseif ($order->invoice_country == 'HU') {
        $url = 'https://www.arukereso.hu/';
    } else {
        $url = 'https://api.etrusted.com';
    }

    $Client = ServiceContainer::getService(TrustedShopProvider::class);

    $Client->setWebApiKey($params['apikey']);
    $Client->setServiceUrlSend($url);
    $Client->SetEmail($order->invoice_email);

    foreach ($order->items as $item) {
        if ($item['id_product']) {
            $identifier = empty($item['id_variation']) ? $item['id_product'] : $item['id_product'].'_'.$item['id_variation'];

            $Client->AddProduct($item['descr'], $identifier);
        }
    }

    try {
        echo $Client->Prepare();
    } catch (Exception $e) {
        $raven = getRaven();
        $raven->captureException($e);
    }
}
