<?php

namespace KupShop\OrderingBundle\Util\Order;

use KupShop\KupShopBundle\Context\ContextManager;
use KupShop\KupShopBundle\Context\CurrencyContext;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

class OrderCurrencyConverter
{
    /**
     * @param string $id_currency
     *
     * @return bool
     */
    public function changeOrderCurrency(\Order $order, $id_currency)
    {
        $currencyContext = ServiceContainer::getService(CurrencyContext::class);
        if (!array_key_exists($id_currency, $currencyContext->getSupported())) {
            return false;
        }

        $currency = $currencyContext->getSupported()[$id_currency];
        $contextManager = ServiceContainer::getService(ContextManager::class);

        $result = $contextManager->activateContexts(
            [CurrencyContext::class => $id_currency],
            function () use ($order, $currency) {
                sqlGetConnection()->transactional(function () use ($order, $currency) {
                    $id_currency = $currency->getId();
                    $cur_rate = toDecimal($order->currency_rate);
                    $new_rate = $currency->getRate();
                    $conv_rate = $cur_rate->div($new_rate);

                    $SQL = sqlQuery('SELECT oi.* FROM '.$order->items_table.' AS oi WHERE oi.id_order='.$order->id.' FOR UPDATE');
                    foreach ($SQL as $row) {
                        $price = toDecimal($row['piece_price'])->mul($conv_rate);
                        $price = calcPrice(roundPrice(calcPrice($price, $row['tax'])), -$row['tax']);
                        $total = $price->mul(toDecimal($row['pieces']));
                        $update_prices = ['piece_price' => $price, 'total_price' => $total];
                        if (findModule(\Modules::PRODUCTS, \Modules::SUB_PRICE_BUY) && !empty($row['price_buy'])) {
                            $update_prices['price_buy'] = toDecimal($row['price_buy'])->mul($conv_rate);
                        }
                        $order->updateSQL($order->items_table, $update_prices, ['id' => $row['id']]);
                    }
                    sqlFreeResult($SQL);

                    $order->updateSQL('orders', ['currency' => $id_currency, 'currency_rate' => $new_rate], ['id' => $order->id]);
                    $log_message = sprintf(translate('orderCurrencyChanged'), $order->currency, $id_currency);
                    $order->currency = $id_currency;
                    $order->currency_rate = $new_rate;
                    $order->recalculate();

                    if (findModule('order_payment')) {
                        $payments = $order->getPaymentsArray();
                        foreach ($payments as $payment) {
                            $price = roundPrice(toDecimal($payment['price'])->mul($conv_rate));
                            $order->updateSQL('order_payments', ['price' => $price], ['id' => $payment['id']]);
                        }
                        $order->updatePayments();
                    }

                    $order->logHistory($log_message);
                });

                return true;
            }
        );

        return $result;
    }
}
