<?php

namespace KupShop\PohodaBundle\Utils\Exporters;

use KupShop\KupShopBundle\Context\LanguageContext;
use KupShop\OrderingBundle\Util\Discount\DiscountGenerator;
use KupShop\OrderingBundle\Util\Order\OrderItemInfo;
use KupShop\PohodaBundle\Utils\PohodaBase;
use KupShop\PohodaBundle\Utils\Tools\PohodaProductExporter;
use Query\Operator;
use Symfony\Contracts\Service\Attribute\Required;

class CouponExporter
{
    use \DatabaseCommunication;
    use PohodaBase;

    private $IDs;

    /**
     * @var PohodaProductExporter
     */
    private $productExporter;

    /**
     * @var LanguageContext
     */
    private $languageContext;

    #[Required]
    public DiscountGenerator $discountGenerator;

    #[Required]
    public OrderItemInfo $orderItemInfo;

    #[Required]
    public \KupShop\OrderingBundle\Util\Discount\CouponExporter $couponExporter;

    public function getData()
    {
        $coupons = [];
        foreach ($this->IDs as $orderId) {
            $order = new \Order($orderId);
            foreach ($order->fetchItems() as $item) {
                $coupons = array_merge($coupons, array_values($this->orderItemInfo->getCustomDataItem($item, 'created_coupons', [])));
            }
        }

        if ($coupons) {
            return $this->couponExporter->getXML($coupons);
        }

        return false;
    }

    public function processData($xml = null)
    {
        // Nastavuje se kvůli volání z adminu jiný mutace
        $this->languageContext->activate($this->languageContext->getDefaultId());

        $this->pohodaConnector->prepareSyncTime();
        $xml = $xml ?: $this->getData();

        if ($xml) {
            $couponsRequest = $this->transformToRequest($xml);
            $request = $this->replace($couponsRequest);
            $this->addRequestLog('Coupon Export', $request);
            $response = $this->pohodaConnector->sendRequest($request);
            if ($response) {
                $this->processResponse($response);
            }

            $this->pohodaConnector->setLastSyncTime('couponsCreatorOut');
        }

        $this->setIDs(null);
    }

    protected function processResponse($xmlStringResponse)
    {
        $xml = simplexml_load_string($xmlStringResponse);
        $this->pohodaConnector->checkValidResponse($xml);
        foreach ($xml->xpath('rsp:responsePackItem') as $responsePackItem) {
            try {
                $this->addResponseLog('Coupon export', $responsePackItem->asXML());
            } catch (\Throwable $exception) {
            }

            if (!$responsePackItem->xpath('ord:orderResponse/rdc:importDetails/rdc:detail/rdc:errno[text() = 109]')) {
                $attr = $responsePackItem->attributes();
                if ($attr['id'] && $attr['state'] == 'ok') {
                    $IDs = explode('_', $attr['id']);

                    $data = sqlQueryBuilder()->select('data')->from('discounts_coupons')->where(Operator::equals(['code' => $attr['id']]))->execute()->fetchOne();

                    $data = json_decode($data ?? '', true);
                    $data['pohoda_id'] = strval($responsePackItem->xpath('stk:stockItemResponse/rdc:producedDetails/rdc:id/text()')[0]);

                    sqlQueryBuilder()
                        ->update('discounts_coupons')
                        ->directValues(['data' => json_encode($data)])
                        ->where(Operator::equals(['code' => $attr['id']]))
                        ->execute();
                }
            }
        }
    }

    public function setIDs($IDs)
    {
        $this->IDs = $IDs;
    }

    /**
     * @required
     */
    public function setProductExporter(PohodaProductExporter $productExporter)
    {
        $this->productExporter = $productExporter;
    }

    /**
     * @required
     */
    public function setLanguageContext(LanguageContext $languageContext): void
    {
        $this->languageContext = $languageContext;
    }

    /**
     * @return \DOMDocument|false
     *
     * @throws \KupShop\PohodaBundle\Exceptions\PohodaException
     */
    public function transformToRequest(mixed $xml)
    {
        $couponsRequest = $this->transformHelper->baseTransform($xml, $this->transformHelper->loadXslt('couponExport.xsl'));

        return $couponsRequest->saveXML();
    }
}
