<?php

namespace KupShop\HeurekaCartBundle\EventListener;

use KupShop\HeurekaCartBundle\Util\HeurekaUtil;
use KupShop\HeurekaCartBundle\Util\Settings;
use KupShop\KupShopBundle\Util\Database\QueryHint;
use KupShop\OrderingBundle\Event\OrderEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class HeurekaOrderEventListener implements EventSubscriberInterface
{
    private HeurekaUtil $heurekaUtil;

    /**
     * HeurekaOrderEventListener constructor.
     */
    public function __construct(HeurekaUtil $heurekaUtil)
    {
        $this->heurekaUtil = $heurekaUtil;
    }

    public static function getSubscribedEvents(): array
    {
        return [
            OrderEvent::ORDER_STATUS_CHANGED => [
                ['updateOrderStatus', 200],
            ],
            OrderEvent::ORDER_STORNO => [
                ['updateOrderStatus', 200],
            ],
        ];
    }

    public function updateOrderStatus(OrderEvent $event, $eventName = null): bool
    {
        $order = $event->getOrder();

        if ($order->isNewOrder()) {
            return false;
        }

        if (!$this->isHeurekaOrder($order)) {
            return false;
        }

        // heureka order status codes:
        // https://sluzby.heureka.cz/napoveda/marketplace-api/#codes-order
        if ($eventName == OrderEvent::ORDER_STORNO) {
            $status = 4; // storno z pohledu obchodu (obchod stornoval objednávku)
        } else {
            $status = Settings::getOrderStatus($order);
        }

        $data = [
            'order_id' => intval($order->id),
            'status' => $status,
        ];

        if ($order->package_id) {
            $data['transport']['tracking_url'] = $order->replacePlaceholders('{ODKAZ_SLEDOVANI_BALIKU}');
        }

        $heurekaAPI = QueryHint::withRouteToMaster(fn () => $this->heurekaUtil->getHeurekaAPIUtil($order));
        $response = $heurekaAPI->putOrderStatus($data, $order->getCurrency());
        $response_status = $response['status'] ?? null;

        getLogger()->notice('HeurekaOrderEventListener updateOrderStatus ['.$order->id.'] -> status '.$status, [
            'orderID' => $order->id,
            'orderNumber' => $order->order_no,
            'orderStatus' => $order->status,
            'orderStatusStorno' => $order->status_storno,
            'heurekaNewStatus' => $status,
            'responseStatus' => $response_status,
            'response' => $response,
            'requestData' => $data,
            'requestUrl' => $heurekaAPI->getRequestUrl($order->getCurrency()).'order/status',
            'requestMethod' => 'PUT',
        ]);

        if ($heurekaAPI->error || !$response_status) { // log history only in case of error
            $message = 'Nastavení stavu objednávky na Heurece - '.$status;
            $this->logHistory($order, $response, $message);
        }

        return true;
    }

    public function isHeurekaOrder(\Order $order): bool
    {
        if (!$order->getData('heureka_id')) {
            // neni Heureka objednavka
            return false;
        }

        return true;
    }

    public function logHistory(\Order $order, $response, $message = ''): void
    {
        if ($this->heurekaUtil->getHeurekaAPIUtil($order)->error) {
            $message .= ' - '.$this->heurekaUtil->getHeurekaAPIUtil($order)->error;
        } else {
            $status = $response['status'] ?? null;
            if (is_null($status)) {
                $msg = print_r($response, true);
                $message .= ' - chyba!<br>'.$msg;
            } else {
                $message .= ' - '.($status ? 'OK' : 'neúspěšně');
            }
        }
        $order->logHistory($message, false);
    }
}
