<?php

namespace KupShop\GTMOldBundle\Ecommerce;

use KupShop\GTMOldBundle\Utils\PriceComputer;
use KupShop\KupShopBundle\Context\CurrencyContext;
use KupShop\OrderingBundle\Util\Order\DeliveryInfo;
use KupShop\OrderingBundle\Util\Order\OrderInfo;

class Purchase extends AbstractEcommerce
{
    protected $currencyContext;

    /**
     * @var DeliveryInfo
     */
    private $deliveryInfo;
    /**
     * @var OrderInfo
     */
    private $orderInfo;
    /**
     * @var PriceComputer
     */
    protected $priceComputer;

    public function __construct(CurrencyContext $currencyContext, DeliveryInfo $deliveryInfo, OrderInfo $orderInfo, PriceComputer $priceComputer)
    {
        $this->currencyContext = $currencyContext;
        $this->deliveryInfo = $deliveryInfo;
        $this->orderInfo = $orderInfo;
        $this->priceComputer = $priceComputer;
    }

    /**
     * Specific PageData.
     *
     * @throws \Exception
     */
    public function getData(&$dataContainer)
    {
        $dbcfg = \Settings::getDefault();
        $ec = new \stdClass();

        $order = $this->pageData['body']['order'];

        if (!empty($order) && $order instanceof \Order && !$order->getData('conversion_sent')) {
            $shipping = $this->deliveryInfo->getDeliveryPrice($order);
            $shipping = $this->priceComputer->processPrice($shipping);

            $orderPrice = $this->priceComputer->getOrderPrice($order->total_price_array);

            $orderVAT = $this->priceComputer->processPrice($order->total_price_array['value_vat']);

            $deliveryType = $order->getDeliveryType();

            $delivery = $deliveryType->getDelivery()->getName();
            $payment = $deliveryType->getPayment()->class;
            $affiliation = join(' - ', [$delivery, $payment]);

            $discounts = [];
            foreach ($order->getPurchaseState(true)->getDiscounts() as $discount) {
                $discounts[] = [
                    'name' => $discount->getName(),
                ];
            }

            $coupons = join('|', array_map(function ($item) {
                return $item['name'];
            }, $discounts));

            $ec->purchase = [
                'actionField' => [
                    'id' => $order->order_no,
                    'affiliation' => $affiliation,
                    'revenue' => $orderPrice,
                    'tax' => $orderVAT,
                    'shipping' => $shipping,
                    'coupon' => $coupons,
                ],
                'products' => [],
            ];

            $currency = $this->currencyContext->getActive();

            $deliveryItemId = $this->deliveryInfo->getDeliveryItem($order);
            $orderPriceWithoutVat = $order->total_price_array['value_without_vat'];
            if ($deliveryItemId) {
                $orderPriceWithoutVat = $orderPriceWithoutVat->sub($order->fetchItems()[$deliveryItemId]['total_price']['value_without_vat']);
            }

            $orderPriceWithoutVat = $this->priceComputer->processPrice($orderPriceWithoutVat);

            $dataContainer->transactionPriceWithoutVatAndDelivery = $orderPriceWithoutVat;

            $dataContainer->discounts = $discounts;

            $dataContainer->transactionId = $order->order_no;
            $dataContainer->transactionAffiliation = $dbcfg->shop_title;
            $dataContainer->transactionCurrency = $currency->getId();
            $dataContainer->transactionTotal = $orderPrice;
            $dataContainer->transactionTax = $orderVAT;
            $dataContainer->transactionShipping = $shipping;
            $dataContainer->transactionFlags = array_filter(array_keys($order->getFlags()));
            $products = [];
            foreach ($order->fetchItems() as $item) {
                if ($item['id_product']) {
                    $id = !empty($item['id_variation']) ? ($item['id_product'].'_'.$item['id_variation']) : $item['id_product'];

                    $ec_product = [
                        'name' => $item['product']['title'],
                        'id' => $id,
                        'price' => $this->priceComputer->getPrice($item['piece_price']),
                        'brand' => $item['producer'],
                        'category' => $item['section_name'],
                        'variant' => $item['product']['variationTitle'] ?? '',
                        'quantity' => $item['pieces'],
                        'id_variation' => $item['id_variation'] ?? '',
                        'id_product' => $item['id_product'],
                        'ean' => $item['ean'] ?? '',
                        // 'coupon': ''                            // Optional fields may be omitted or set to empty string.
                    ];

                    $this->modifyProductData($ec_product, $item);
                    $ec->purchase['products'][] = $ec_product;

                    $this->addProductField($products, $item);
                }
            }

            $this->addAdditionalFields($dataContainer, $order);

            $dataContainer->transactionProducts = $products;

            $dataContainer->event = 'order_success';
            $dataContainer->ecommerce = $ec;

            if (!empty($order->invoice_name)) {
                $dataContainer->user = $dataContainer->user ?? new \stdClass();
                $dataContainer->user->name = $order->invoice_name;
                $dataContainer->user->surname = $order->invoice_surname;
                $dataContainer->user->email = $order->invoice_email;
            }
        }
    }

    // Na upravu dat ktere jdou do transactionProducts
    protected function addProductField(&$products, $item)
    {
        $products[] = [
            'name' => $item['product']['title'],
            'sku' => !empty($item['id_variation']) ? ($item['id_product'].'_'.$item['id_variation']) : $item['id_product'],
            'category' => $item['section_name'],
            'categoryid' => $item['section_id'],
            'price' => $this->priceComputer->getPrice($item['piece_price']),
            'quantity' => $item['pieces'],
        ];
    }

    // Na upravu dat ktere jdou do ecommerce->products
    protected function modifyProductData(&$ec_product, $order_item)
    {
    }
}
