<?php

declare(strict_types=1);

namespace External\PompoBundle\Controller;

use External\PompoBundle\DataGo\Synchronizer\OrderSynchronizer;
use External\PompoBundle\Util\PompoUtil;
use KupShop\AdminBundle\AdminRequiredControllerInterface;
use LSS\Array2XML;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route("/_datago")
 */
class DataGoController extends AbstractController implements AdminRequiredControllerInterface
{
    /**
     * @Route("/sync/{type}/")
     */
    public function synchronize(PompoUtil $pompoUtil, string $type): Response
    {
        ini_set('max_execution_time', (string) (60 * 60 * 4));
        ini_set('memory_limit', '2048M');

        $pompoUtil->synchronizeDataGo([$type]);

        return new JsonResponse(['success' => true]);
    }

    /**
     * @Route("/dump_order/{id}/")
     */
    public function dumpOrder(Request $request, OrderSynchronizer $orderSynchronizer, PompoUtil $pompoUtil, int $id): Response
    {
        try {
            $order = \Order::get($id);
        } catch (\InvalidArgumentException $e) {
            throw new NotFoundHttpException('Order not found');
        }

        $orderData = $orderSynchronizer->getOrderData($order);

        if ($request->get('xml')) {
            // get credentials from pompoUtil  - getDataGoCredentialsByOrder
            $credentials = $pompoUtil->getDataGoCredentialsByOrder($order);
            $data = [
                'connection' => [
                    'username' => $credentials[0],
                    'password' => $credentials[1],
                ],
                'order' => $orderData,
            ];

            // create XML from array
            $xml = Array2XML::createXML('dataline', $data)->saveXML();

            $response = new Response($xml);
            $response->headers->set('Content-Type', 'text/xml');

            return $response;
        }

        return new JsonResponse($orderData);
    }
}
