<?php

namespace KupShop\GTMBundle\Resources\script;

use KupShop\AdminBundle\Util\Script\Script;
use KupShop\GTMBundle\ServerSideGTMEvent\OrderComplete;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\OrderingBundle\Event\OrderEvent;

class SendServerSideGTMOrderScript extends Script
{
    protected static $defaultParameters = [
        'orderNo' => '12345',
        'debugHash' => '',
        'display' => false,
    ];
    protected $orderGTM;
    protected $order;

    protected static $name = 'Odeslat server-side GTM purchase eventu';

    public function __construct()
    {
        $this->orderGTM = ServiceContainer::getService(OrderComplete::class);
        $this->order = new \Order();
    }

    protected function run(array $arguments)
    {
        if ($arguments['orderNo'] ?? false) {
            $orderNo = $arguments['orderNo'];
            $debugHash = $arguments['debugHash'];
            $order = $this->order->createFromDbOrderNo($orderNo);
            $event = new OrderEvent($order);
            $this->orderGTM->setDebugHash($debugHash);

            if ($arguments['display']) {
                $payload = $this->orderGTM->getPayload($event);
                $this->log(json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_LINE_TERMINATORS));

                return;
            }

            $this->orderGTM->start($event);
        }
    }
}

return SendServerSideGTMOrderScript::class;
