<?php

namespace KupShop\GTMOldBundle\Ecommerce;

use KupShop\GTMOldBundle\Utils\PriceComputer;

class Checkout extends AbstractEcommerce
{
    /**
     * @var PriceComputer
     */
    private $priceComputer;

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

    /**
     * Specific PageData.
     */
    public function getData(&$dataContainer)
    {
        /** @var \Cart $cart */
        $cart = $this->pageData['body'];

        if (empty($cart->products)) {
            return;
        }

        $dataContainer->event = 'checkout';
        $dataContainer->cart = new \stdClass();

        $step = '';
        $counter = 1;
        foreach ($cart->steps as $step) {
            if (!empty($step['selected'])) {
                $step = $counter;
                break;
            }
            $counter++;
        }

        $products = [];
        foreach ($cart->products as $cart_product) {
            $id = !empty($cart_product['id_variation']) ? ($cart_product['id'].'_'.$cart_product['id_variation']) : $cart_product['id'];

            $cart_product['product']->fetchSections();

            $ec_product = [
                'name' => $cart_product['product']['title'],
                'id' => $id,
                'price' => $this->priceComputer->getPrice($cart_product['product']->getProductPrice()),
                'brand' => $cart_product['producer'],
                'category' => $cart_product['product']->sections[0]['name'] ?? '',
                'variant' => $cart_product['product']['variationTitle'] ?? '',
                'quantity' => $cart_product['pieces'],
                // 'coupon': ''
                'dimension14' => join('|', array_keys($cart_product['product']->campaign_codes)),
            ];

            $this->modifyProductData($ec_product, $cart_product);

            $products[] = $ec_product;
        }

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

        $dataContainer->discounts = $discounts ?? [];

        foreach ($cart->orders_charges ?: [] as $charge) {
            $dataContainer->cart->charges[] = [
                'id' => $charge['id'],
                'title' => $charge['title'],
                'price' => $charge['price']->getPriceWithVat(),
            ];
        }

        $dataContainer->ecommerce = [
            'checkout' => [
                'actionField' => [
                    'step' => $step,
                ],
                'products' => $products,
            ],
        ];
    }

    protected function modifyProductData(&$ec_product, $cart_product)
    {
    }
}
