<?php

namespace KupShop\ElninoBundle\GTMv1\Ecommerce;

use KupShop\KupShopBundle\Util\System\UrlFinder;
use Query\Operator;

class Purchase extends \KupShop\GTMOldBundle\Ecommerce\Purchase
{
    /**
     * @var UrlFinder
     */
    protected $urlFinder;

    /**
     * @required
     */
    public function setUrlFinder(UrlFinder $urlFinder): void
    {
        $this->urlFinder = $urlFinder;
    }

    /**
     * Specific PageData.
     *
     * @throws \Exception
     */
    public function getData(&$dataContainer)
    {
        parent::getData($dataContainer);
        $order = $this->pageData['body']['order'];

        $deliveryType = $order->getDeliveryType();

        $dataContainer->transactionTotalWithPriceAndDelivery = $dataContainer->transactionTotal;
        $dataContainer->transactionTotal = $dataContainer->transactionPriceWithoutVatAndDelivery;
        $dataContainer->paymentName = $deliveryType->payment;
        $dataContainer->orderEmail = $order->invoice_email;
        $dataContainer->orderName = $order->invoice_name;
        $dataContainer->orderSurname = $order->invoice_surname;

        if (!empty($order->note_admin)) {
            $note = json_decode($order->note_admin, true);
            $dataContainer->orderGender = $note['gender'] ?? '';
        }

        $dataContainer->sessionId = md5(session_id());
        $dataContainer->timeStamp = time();

        $dataContainer->customer_type = $this->getReturningVisitor($order);
    }

    protected function getReturningVisitor($order)
    {
        $ordersCount = sqlQueryBuilder()->select('COUNT(*)')->from('orders')
            ->where(Operator::andX(
                Operator::equals(['invoice_email' => $order->invoice_email]),
                Operator::not(Operator::equals(['id' => $order->id])),
                'DATE_ADD(date_created, INTERVAL 1 YEAR) > NOW()'
            ))
            ->execute()->fetchColumn();

        return $ordersCount ? 'returning' : 'new';
    }

    protected function modifyProductData(&$ec_product, $order_item)
    {
        $ec_product['url'] = $this->urlFinder->shopUrlAbsolute(createScriptURL([
            's' => 'product',
            'IDproduct' => $order_item['id_product'],
            'TITLE' => $order_item['product']['title'],
        ]));
    }
}
