<?php

namespace KupShop\GTMOldBundle\Ecommerce;

use KupShop\GTMOldBundle\Utils\PriceComputer;
use KupShop\KupShopBundle\Context\CurrencyContext;

class AddToCart extends AbstractEcommerce
{
    protected $currencyContext;
    /**
     * @var PriceComputer
     */
    protected $priceComputer;

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

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

        $ec->currencyCode = $this->currencyContext->getActive()->getId();

        $ec->add = new \stdClass();
        $ec->add->products = [];

        if (is_array($this->pageData['addedToCart'])) {
            $addedProducts = $this->pageData['addedToCart'];
        } else {
            $addedProducts = [$this->pageData['addedToCart']];
        }

        /** @var \CartItem $added */
        foreach ($addedProducts as $added) {
            $product = [
                'name' => $added->fetchTitle(),
            ];

            $productObj = $added->fetchProduct();
            $productObj->fetchVariations();
            $productObj->fetchSections();

            if ($added->id_variation) {
                $product['id'] = $added->id_product.'_'.$added->id_variation;
                $product['price'] = $this->priceComputer->getPrice($productObj->variations['variations'][$added->id_variation]['productPrice']);
            } else {
                $product['id'] = $added->id_product;
                $product['price'] = $this->priceComputer->getPrice($productObj->getProductPrice());
            }

            $product['id_variation'] = $added->id_variation ?? '';
            $product['id_product'] = $added->id_product ?? '';

            if (findModule(\Modules::PRODUCERS)) {
                $product['brand'] = $added['producer'];
            }

            $section = !empty($productObj->sections[0]) ? $productObj->sections[0]->getName() : 'undefined';
            $product['category'] = $section;
            $product['variant'] = $productObj->variations['variations'][$added->id_variation]['title'] ?? '';
            $product['quantity'] = $added->pieces_added;

            $this->addProductField($product, $productObj);

            $ec->add->products[] = $product;
        }

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

        $dataContainer->ecommerce = $ec;
        $dataContainer->event = 'addToCart';
    }

    protected function addProductField(&$product, $data)
    {
    }
}
