<?php

namespace KupShop\AdminBundle\Admin\Tabs;

use KupShop\AdminBundle\Admin\WindowTab;
use KupShop\I18nBundle\Util\PriceConverter;
use KupShop\KupShopBundle\Context\ContextManager;
use KupShop\KupShopBundle\Context\CurrencyContext;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\KupShopBundle\Util\Contexts;

class ProductMarginsTab extends WindowTab
{
    protected $title = 'flapMargins';

    protected $template = 'window/tabs/orderMarginsTab.tpl';

    public static function getTypes()
    {
        return [
            'orders' => 1,
        ];
    }

    public static function isAllowed()
    {
        return findModule(\Modules::PRODUCTS, \Modules::SUB_PRICE_BUY);
    }

    public function isVisible(): bool
    {
        return parent::isVisible() && $this->getAction() !== 'add' && findRight('PROD_PRICEBUY');
    }

    public function getLabel()
    {
        return 'Marže';
    }

    public function getVars($smarty_tpl_vars)
    {
        $order = $smarty_tpl_vars['order']->value;

        $contextManager = ServiceContainer::getService(ContextManager::class);

        return $contextManager->activateOrder($order,
            function () use ($order, $smarty_tpl_vars) {
                $items = [];
                $priceBuyTotal = \DecimalConstants::zero();
                $priceSellTotal = \DecimalConstants::zero();
                $piecesTotal = 0;

                $priceConverter = ServiceContainer::getService(PriceConverter::class);

                $currency = $order->getCurrency();
                $currencyContext = Contexts::get(CurrencyContext::class);

                foreach ($smarty_tpl_vars['body']->value['oop'] as $item) {
                    if (isset($item['price_buy'])) {
                        $item['price_buy'] = $priceConverter->convert($currency, $currencyContext->getDefault(), $item['price_buy'])->asFloat();
                    } else {
                        // get price_buy form product if there is no price_buy on order item
                        $product = $order->items[$item['id']]['product'] ?? null;
                        if (!$product || !isset($product->price_buy)) {
                            continue;
                        }

                        if (is_array($product->price_buy)) {
                            $item['price_buy'] = $priceConverter->convert(
                                $product->price_buy['currency_object'],
                                $currencyContext->getDefault(),
                                $product->price_buy['value_without_vat']
                            )->asFloat();
                        } else {
                            $item['price_buy'] = $priceConverter->convert(
                                $product->price_buy->getCurrency(),
                                $currencyContext->getDefault(),
                                $product->price_buy->value_without_vat
                            )->asFloat();
                        }
                    }

                    $item['total_price'] = $priceConverter->convert($currency, $currencyContext->getDefault(), $item['total_price'])->asFloat();

                    $itemBuyTotal = $item['price_buy'] * $item['pieces'];
                    $priceBuyTotal = $priceBuyTotal->add(toDecimal($itemBuyTotal));
                    $priceSellTotal = $priceSellTotal->add(toDecimal($item['total_price']));
                    $piecesTotal += $item['pieces'];

                    if ($item['total_price'] > 0) {
                        $item['margin'] = round(($item['total_price'] - $itemBuyTotal) / $item['total_price'] * 100, 2);
                    } else {
                        $item['margin'] = -100;
                    }

                    foreach ($this->getMarginColors() as $key => $color) {
                        if ($item['margin'] < $key) {
                            $item['bg_color'] = $color;
                            break;
                        }
                    }

                    $items[] = $item;
                }

                return [
                    'items' => $items,
                    'priceBuyTotal' => $priceBuyTotal->asFloat(),
                    'priceSellTotal' => $priceSellTotal->asFloat(),
                    'piecesTotal' => $piecesTotal,
                ];
            });
    }

    private function getMarginColors(): array
    {
        return [
            0 => '#ffd5db', // pink
            2 => '#fceecd', // orange
            10 => '#fafcb5', // yellow
            50 => '#e5fccd', // green
            9999 => '#daddfc', // purple / blue
        ];
    }
}
