src/AtechNet/CoreBundle/Controller/CheckoutController.php line 147

Open in your IDE?
  1. <?php
  2. namespace App\AtechNet\CoreBundle\Controller;
  3. use App\AtechNet\CoreBundle\Entity\Attribute;
  4. use App\AtechNet\CoreBundle\Entity\AttributeOption;
  5. use App\AtechNet\CoreBundle\Entity\Basket;
  6. use App\AtechNet\CoreBundle\Entity\BasketItem;
  7. use App\AtechNet\CoreBundle\Entity\BasketItemAttributeOption;
  8. use App\AtechNet\CoreBundle\Entity\BillingoPayment;
  9. use App\AtechNet\CoreBundle\Entity\Coupon;
  10. use App\AtechNet\CoreBundle\Entity\Customer;
  11. use App\AtechNet\CoreBundle\Entity\CustomerAddress;
  12. use App\AtechNet\CoreBundle\Entity\CustomerEmail;
  13. use App\AtechNet\CoreBundle\Entity\DocumentPayment;
  14. use App\AtechNet\CoreBundle\Entity\Domain;
  15. use App\AtechNet\CoreBundle\Entity\DomainPaymentType;
  16. use App\AtechNet\CoreBundle\Entity\DomainShippingType;
  17. use App\AtechNet\CoreBundle\Entity\Order;
  18. use App\AtechNet\CoreBundle\Entity\Statistics\OrderChangelog;
  19. use App\AtechNet\CoreBundle\Entity\OrderComment;
  20. use App\AtechNet\CoreBundle\Entity\OrderItem;
  21. use App\AtechNet\CoreBundle\Entity\OrderItemAttributeOption;
  22. use App\AtechNet\CoreBundle\Entity\OrderSetting;
  23. use App\AtechNet\CoreBundle\Entity\PickupPoint;
  24. use App\AtechNet\CoreBundle\Entity\Product;
  25. use App\AtechNet\CoreBundle\Entity\ProductType;
  26. use App\AtechNet\CoreBundle\Entity\StockItem;
  27. use App\AtechNet\CoreBundle\Entity\StockMovement;
  28. use App\AtechNet\CoreBundle\Entity\StockMovementItem;
  29. use App\AtechNet\CoreBundle\Entity\Survey;
  30. use App\AtechNet\CoreBundle\Entity\SurveyQuestion;
  31. use App\AtechNet\CoreBundle\Entity\SurveyQuestionOption;
  32. use App\AtechNet\CoreBundle\Entity\User;
  33. use App\AtechNet\CoreBundle\Enum\PaymentType;
  34. use App\AtechNet\CoreBundle\Form\CheckoutType;
  35. use App\AtechNet\CoreBundle\Helper\DeliveryUtil;
  36. use App\AtechNet\CoreBundle\Helper\Furbify\CartHelper;
  37. use App\AtechNet\CoreBundle\Helper\Furbify\Heureka;
  38. use App\AtechNet\CoreBundle\Helper\Furbify\Image;
  39. use App\AtechNet\CoreBundle\Helper\Furbify\MultiStore;
  40. use App\AtechNet\CoreBundle\Helper\Furbify\OrderHelper;
  41. use App\AtechNet\CoreBundle\Helper\Furbify\PayPal;
  42. use App\AtechNet\CoreBundle\Helper\Furbify\Registration;
  43. use App\AtechNet\CoreBundle\Helper\Instacash;
  44. use App\AtechNet\CoreBundle\Helper\Klarna;
  45. use App\AtechNet\CoreBundle\Helper\KlaviyoConnect;
  46. use App\AtechNet\CoreBundle\Helper\Milpay;
  47. use App\AtechNet\CoreBundle\Helper\OrderStatistics;
  48. use App\AtechNet\CoreBundle\Helper\Packeta;
  49. use App\AtechNet\CoreBundle\Helper\Security as SecurityHelper;
  50. use App\AtechNet\CoreBundle\Repository\StockMovementRepository;
  51. use Doctrine\ORM\Exception\NotSupported;
  52. use Doctrine\ORM\Exception\ORMException;
  53. use Doctrine\ORM\OptimisticLockException;
  54. use Exception;
  55. use Firebase\JWT\JWT;
  56. use Psr\Container\ContainerExceptionInterface;
  57. use Psr\Container\NotFoundExceptionInterface;
  58. use Psr\SimpleCache\InvalidArgumentException;
  59. use Symfony\Component\Form\FormError;
  60. use Symfony\Component\HttpFoundation\JsonResponse;
  61. use Symfony\Component\HttpFoundation\RedirectResponse;
  62. use Symfony\Component\HttpFoundation\Request;
  63. use Symfony\Component\HttpFoundation\Response;
  64. use Symfony\Component\Intl\Countries;
  65. use Symfony\Component\Mime\Email;
  66. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  67. use Symfony\Component\Routing\Annotation\Route;
  68. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  69. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  70. class CheckoutController extends AbstractController
  71. {
  72.     public const TIMEOUT = 2; // hours
  73.     public const SHIPPING_TYPES_WITH_IMMEDIATE_SHIPPING = [
  74.         DomainShippingType::SHIPPING_TYPE_CARRIER_EXPRESS_ID,
  75.         DomainShippingType::ShippingType_PICKUP_POINT_Id,
  76.     ];
  77.     private $unWantedAttributes = [
  78.         237, 239, 247, 241, 387, 388, 405, 409, 415, 419, 529, 854, 940,
  79.     ];
  80.     private $extenalCheckPaymentTypes = [
  81.         PaymentType::DebitCard->value,
  82.         PaymentType::Quatro->value,
  83.         PaymentType::Cetelem->value,
  84.         PaymentType::DebitCard3Percent->value,
  85.         PaymentType::Instacash->value,
  86.         PaymentType::PastPay->value,
  87.         PaymentType::Klarna->value,
  88.         PaymentType::PayPal->value,
  89.         PaymentType::Milpay->value,
  90.     ];
  91.     /**
  92.      * Pick-up Point Select
  93.      */
  94.     private $enablePickupPointSelector = [
  95.         DomainShippingType::ShippingType_PICKUP_POINT_Id,
  96.     ];
  97.     /**
  98.      * Hide Payment Methods by Selected Shipping Method if necessary
  99.      */
  100.     private $paymentMethodRestriction = [
  101.         DomainShippingType::ShippingType_PICKUP_POINT_Id => [PaymentType::CashOnDelivery->value],
  102.     ];
  103.     private function isYear2025(): bool
  104.     {
  105.         $currentDate = (int) (new \DateTime('NOW'))->format('Y');
  106.         return $currentDate == 2025;
  107.     }
  108.     /**
  109.      * @Route("/checkout/customer", name="checkout_customer", defaults={"_locale":""})
  110.      * @Route("/{_locale<%supported_locales%>?}/checkout/customer", name="checkout_customer_locale", defaults={"_locale":""})
  111.      * @param Request $request
  112.      * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
  113.      * @throws \Exception
  114.      */
  115.     public function customerAction(Request $request)
  116.     {
  117.         $customer = $this->getLoginHelper($request)->getLoggedInCustomer();
  118.         // Multi-Store
  119.         $multiStore = $this->getMultiStoreHelper($request);
  120.         // Checkout DATA
  121.         if ($request->getSession()->has('checkout')) {
  122.             $checkout = $request->getSession()->get('checkout');
  123.         } else {
  124.             $checkout = [];
  125.         }
  126.         if ($customer || $request->getSession()->get('abandonedCart') != null) {
  127.             $abandonedCartData = $request->getSession()->get('abandonedCart');
  128.             $checkout['updated'] = new \DateTime();
  129.             $checkout['email'] = $abandonedCartData ? $abandonedCartData->email : $customer->getEmail();
  130.             $data['name'] = $abandonedCartData ? '' : $customer->getFullName();
  131.             $request->getSession()->set('checkout', $checkout);
  132.             return $this->redirectToRoute('checkout_address');
  133.         }
  134.         $data = [];
  135.         $data['hideChat'] = true;
  136.         /**
  137.          * @var Basket $cart
  138.          */
  139.         $cart = $this->getCart($request->getSession()->get('cartId'));
  140.         if (!$cart) {
  141.             return $this->redirectToRoute('cart_show');
  142.         }
  143.         $entityManager = $this->getEntityManager();
  144.         // Basket expires
  145.         $cartUpdated = clone $cart->getUpdated();
  146.         // if ($cartUpdated->add(new \DateInterval("PT" . self::TIMEOUT . "H")) <= (new \DateTime('NOW'))) {
  147.         //     $entityManager->remove($cart);
  148.         //     $entityManager->flush();
  149.         //     return $this->redirectToRoute('cart_show');
  150.         // }
  151.         $orderSummary = $this->orderSummary($cart, $request);
  152.         // Validate cart has products and has stock.
  153.         if (!$orderSummary['valid'] && $orderSummary['countItems'] > 0) {
  154.             return $this->redirectToRoute('cart_show');
  155.         }
  156.         // Logged in Customer
  157.         if ($customer) {
  158.             $data['loggedIn'] = true;
  159.             $data['name'] = $customer->getFullName();
  160.             if (empty($checkout['email'])) {
  161.                 $checkout['email'] = $customer->getEmail();
  162.             }
  163.         } else {
  164.             $data['loggedIn'] = false;
  165.         }
  166.         $checkout['step'] = 2;
  167.         $form = $this->createForm(CheckoutType::class, $checkout, [
  168.             'locale' => $request->getLocale(),
  169.             'defaultLocale' => $multiStore->getDefaultLocale(),
  170.         ]);
  171.         $form->handleRequest($request);
  172.         if ($form->isSubmitted()) {
  173.             $cart->setUpdated((new \DateTime('NOW')));
  174.             $entityManager->flush();
  175.         }
  176.         if ($form->isSubmitted() && $form->isValid()) {
  177.             $checkout['updated'] = new \DateTime();
  178.             $checkout['email'] = $form->get('email')->getData();
  179.             $request->getSession()->set('checkout', $checkout);
  180.             $customer = $entityManager->getRepository(Customer::class)->findOneBy([
  181.                 'email' => $checkout['email'],
  182.                 'domain' => $this->getMultiStoreHelper($request)->getDomain(),
  183.             ]);
  184.             if ($customer) {
  185.                 $cart->setCustomer($customer);
  186.             }
  187.             $cart->setAbandonedEmail($checkout['email']);
  188.             $entityManager->flush();
  189.             return $this->redirectToRoute('checkout_address');
  190.         }
  191.         $data['form'] = $form->createView();
  192.         // Order Summary
  193.         $data['orderSummary'] = $orderSummary;
  194.         $data['header'] = $this->getHeader($request);
  195.         $data['footer'] = $this->getFooter($request);
  196.         $data['contentBottom'] = $this->getContentBottom($request);
  197.         $data['stepsOptions'] = $this->checkoutSteps(2);
  198.         return $this->render('AtechNetCoreBundle/Checkout/customer.html.twig', $data);
  199.     }
  200.     /**
  201.      * @Route("/checkout/shipping-and-payment", name="checkout_shipping_and_payment", defaults={"_locale":""})
  202.      * @Route("/{_locale<%supported_locales%>?}/checkout/shipping-and-payment", name="checkout_shipping_and_payment_locale", defaults={"_locale":""})
  203.      * @param Request $request
  204.      * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
  205.      * @throws \Exception
  206.      */
  207.     public function shippingPaymentAction(Request $request)
  208.     {
  209.         $multiStore = $this->getMultiStoreHelper($request);
  210.         $domain = $multiStore->getDomain();
  211.         $domainId = $domain->getId();
  212.         $customer = $this->getLoginHelper($request)->getLoggedInCustomer();
  213.         $data = [];
  214.         $data['hideChat'] = true;
  215.         $data['shippingCountry'] = $domain->getLanguage()->getCode();
  216.         $data['packetaApiKey'] = $this->getParameter('packeta')['api_key'];
  217.         // Checkout DATA
  218.         if ($request->getSession()->has('checkout')) {
  219.             $checkout = $request->getSession()->get('checkout');
  220.         } else {
  221.             $checkout = [];
  222.         }
  223.         // Get Cart Items
  224.         $cart = $this->getCart($request->getSession()->get('cartId'));
  225.         if ($cart) {
  226.             $entityManager = $this->getEntityManager();
  227.             $translator = $this->getTranslator();
  228.             $data['isBasketIncludesGamerProduct'] = $this->getEntityManager()->getRepository(Product::class)->isBasketIncludesGamerProduct($cart);
  229.             // Basket expires
  230.             $cartUpdated = clone $cart->getUpdated();
  231.             // if ($cartUpdated->add(new \DateInterval("PT" . self::TIMEOUT . "H")) <= (new \DateTime('NOW'))) {
  232.             //     $entityManager->remove($cart);
  233.             //     $entityManager->flush();
  234.             //     return $this->redirectToRoute('cart_show');
  235.             // }
  236.             $orderSummary = $this->orderSummary($cart, $request);
  237.             // Validate cart has products and has stock.
  238.             if (!$orderSummary['valid'] && $orderSummary['countItems'] > 0) {
  239.                 return $this->redirectToRoute('cart_show');
  240.             }
  241.             // Coupon Free Shipping
  242.             $isCouponApplicableForFreeShipping = false;
  243.             if (isset($checkout['coupon']['code']) && $checkout['coupon']['code'] != '') {
  244.                 $coupon = $entityManager->getRepository(Coupon::class)->findOneBy([
  245.                     'code' => $checkout['coupon']['code'],
  246.                     'domain' => $domain,
  247.                 ]);
  248.                 if ($coupon) {
  249.                     // Set Email
  250.                     if (!empty($checkout['email'])) {
  251.                         $cart->setEmail($checkout['email']);
  252.                     } else {
  253.                         $cart->setEmail(null);
  254.                     }
  255.                     $isCouponApplicableForFreeShipping = CartHelper::isCouponApplicableForFreeShipping($coupon, $cart, $entityManager);
  256.                 }
  257.             }
  258.             // Shipping Methods
  259.             $data['shippingMethods'] = [];
  260.             $shippingMethods = $entityManager->getRepository(DomainShippingType::class)->findBy([
  261.                 'domain' => $domainId,
  262.                 'activeOnWeb' => true,
  263.             ], [
  264.                 'sortIndex' => 'ASC',
  265.             ]);
  266.             $getPickupPoints = false;
  267.             $hasMainProductTypes = CartHelper::hasMainProductType($cart);
  268.             /**
  269.              * @var DomainShippingType $shippingMethod
  270.              */
  271.             foreach ($shippingMethods as $shippingMethod) {
  272.                 $methodIsDisabled = false;
  273.                 if ($shippingMethod->getType() == DomainShippingType::ShippingType_Carrier_Id && $domainId == Domain::DOMAIN_ID_WS_HU) {
  274.                     $translationKey = 'shipping.method.type.' . $shippingMethod->getType() . '.achu';
  275.                 } else {
  276.                     $translationKey = 'shipping.method.type.' . $shippingMethod->getType();
  277.                 }
  278.                 if (($title = $translator->trans($translationKey)) == $translationKey) {
  279.                     $title = false;
  280.                 }
  281.                 if (($description = $translator->trans($translationKey . '.description')) == $translationKey . '.description') {
  282.                     $description = false;
  283.                 }
  284.                 if (($icon = $translator->trans($translationKey . '.icon')) == $translationKey . '.icon') {
  285.                     $icon = false;
  286.                 }
  287.                 // Validate Pickup Point availability
  288.                 if (in_array(
  289.                     $shippingMethod->getType(),
  290.                     [
  291.                         DomainShippingType::ShippingType_PICKUP_POINT_Id,
  292.                         DomainShippingType::SHIPPING_TYPE_PACKETA_PICKUP_POINT_ID,
  293.                     ]
  294.                 )) {
  295.                     if (!$cart->isPickupPointAvailable()) {
  296.                         $methodIsDisabled = true;
  297.                     }
  298.                 }
  299.                 if ($shippingMethod->getType() == DomainShippingType::SHIPPING_TYPE_PACKETA_PICKUP_POINT_ID
  300.                     && $orderSummary['subTotal'] >= Packeta::getCodLimitByDomainMarketCode(strtoupper($domain->getLanguage()->getCode()))) {
  301.                     $methodIsDisabled = true;
  302.                 }
  303.                 // Shipping Cost
  304.                 $shippingPrice = in_array($shippingMethod->getType(), $orderSummary['enableFreeShipping']) ? 0 : $shippingMethod->getPrice();
  305.                 // Free Shipping
  306.                 if ((float)$shippingMethod->getFreeShipLimit() > 0 && (float)$shippingMethod->getFreeShipLimit() < $orderSummary['subTotal']) {
  307.                     $shippingPrice = 0;
  308.                 }
  309.                 // Coupon Free Shipping
  310.                 if ($isCouponApplicableForFreeShipping) {
  311.                     $shippingPrice = 0;
  312.                 }
  313.                 // Round Shipping Cost
  314.                 if (in_array($domainId, [Domain::DOMAIN_ID_RT_HU, Domain::DOMAIN_ID_WS_HU])) {
  315.                     $shippingPrice = number_format($shippingPrice, 0, '.', '');
  316.                 }
  317.                 if ($title) {
  318.                     $shiftBy = ((int)explode('-', $shippingMethod->getShippingDays())[0]) - 1;
  319.                     $data['shippingMethods'][$shippingMethod->getId()] = [
  320.                         'id' => $shippingMethod->getId(),
  321.                         'type' => $shippingMethod->getType(),
  322.                         'title' => $title,
  323.                         'description' => $description,
  324.                         'price' => $shippingPrice,
  325.                         'icon' => $icon,
  326.                         'collapse' => in_array($shippingMethod->getType(), $this->enablePickupPointSelector) ? 1 : 0,
  327.                         'estimatedDeliveryDate' => (new DeliveryUtil())->getEstimatedDeliveryDate($shippingMethod->getDomain()->getId(), $data['isBasketIncludesGamerProduct'], false, $shiftBy),
  328.                         'restriction' => isset($this->paymentMethodRestriction[$shippingMethod->getType()]) ? $this->paymentMethodRestriction[$shippingMethod->getType()] : [],
  329.                         'disabled' => $methodIsDisabled,
  330.                     ];
  331.                 }
  332.                 if (in_array($shippingMethod->getType(), $this->enablePickupPointSelector)) {
  333.                     $getPickupPoints = true;
  334.                 }
  335.             }
  336.             if (isset($checkout['packetaPickupPointId']) && (is_numeric($checkout['packetaPickupPointId']) || ($checkout['packetaPickupPointCarrierId'] == Packeta::FOXPOST_CARRIER_ID)) ) {
  337.                 $data['packetaPickupPointId'] = $checkout['packetaPickupPointId'];
  338.             }
  339.             if (isset($checkout['packetaPickupPointTitle']) && $checkout['packetaPickupPointTitle'] != '') {
  340.                 $data['packetaPickupPointTitle'] = (string)$checkout['packetaPickupPointTitle'];
  341.             }
  342.             if (isset($checkout['packetaPickupPointCarrierId']) && is_numeric($checkout['packetaPickupPointCarrierId'])) {
  343.                 $data['packetaPickupPointCarrierId'] = (int)$checkout['packetaPickupPointCarrierId'];
  344.             }
  345.             if (!isset($checkout['shippingMethodId'])) {
  346.                 $checkout['shippingMethodId'] = $cart->getShippingMethod();
  347.             }
  348.             // Pick-up Points
  349.             $data['pickupPoints'] = [];
  350.             if ($getPickupPoints) {
  351.                 $pickupPoints = $entityManager->getRepository(PickupPoint::class)->findBy([
  352.                     'active' => true,
  353.                     'country' => $multiStore->getDefaultCountry(),
  354.                 ], [
  355.                     'city' => 'ASC',
  356.                 ]);
  357.                 foreach ($pickupPoints as $pickupPoint) {
  358.                     $data['pickupPoints'][$pickupPoint->getId()] = [
  359.                         'id' => $pickupPoint->getId(),
  360.                         'title' => $pickupPoint->getTitle(),
  361.                         'address' => $pickupPoint->getCity() . ', ' . $pickupPoint->getStreet(),
  362.                         'street' => $pickupPoint->getStreet(),
  363.                         'city' => $pickupPoint->getCity(),
  364.                         'zip' => $pickupPoint->getZip(),
  365.                         'sortOrder' => $pickupPoint->getCity(),
  366.                     ];
  367.                 }
  368.             }
  369.             // Payment Methods
  370.             $instacash = null;
  371.             if (in_array($domain->getLanguage()->getCode(), ['sk', 'hu'])) {
  372.                 $instacash = $this->getInstacash($domain->getLanguage()->getCode());
  373.             }
  374.             $milpay = null;
  375.             if (in_array($domain->getId(), [Domain::DOMAIN_ID_RT_HU, Domain::DOMAIN_ID_RT_SK, Domain::DOMAIN_ID_RT_CZ])) {
  376.                 $milpay = $this->getMilpay($domain->getLanguage()->getCode());
  377.             }
  378.             $isCompany = $checkout['isCompany'] && (!is_null($checkout['billingTaxId']) || !is_null($checkout['billingVatNumber']));
  379.             $paymentData = $this->getOrderHelper($request)->getPaymentMethodData($domainId, $customer, $cart, $instacash, $milpay, $isCompany, $entityManager->getRepository(Order::class));
  380.             $data['paymentMethods'] = $paymentData['paymentList'];
  381.             $data['showCetelemCalculator'] = $paymentData['showCetelemCalculator'];
  382.             $data['cetelemDescLink'] = $paymentData['cetelemDescLink'];
  383.             $data['cetelemDesc'] = $paymentData['cetelemDesc'];
  384.             $data['pastPay'] = [
  385.                 'available' => $paymentData['pastPayAvailable'] && $checkout['isCompany'] && $checkout['billingTaxId'] != null,
  386.                 'debtorTaxNumber' => $checkout['billingTaxId'],
  387.             ];
  388.             if (!isset($checkout['paymentMethodId'])) {
  389.                 $checkout['paymentMethodId'] = $cart->getPaymentMethod();
  390.             }
  391.             $priceLimits = DomainPaymentType::CASH_ON_DELIVERY_LIMITS;
  392.             //REMOVE SELECTED CASH ON DELIVERY WHEN IT IS DISABLED
  393.             if ($priceLimits[$orderSummary['currency']]
  394.                 && $orderSummary['total'] > $priceLimits[$orderSummary['currency']]
  395.                 && isset($checkout['paymentMethodTypeId'])
  396.                 && $checkout['paymentMethodTypeId'] == PaymentType::CashOnDelivery->value) {
  397.                 $checkout['paymentMethodId'] = null;
  398.             }
  399.             //
  400.             if ( isset($checkout['shippingMethodTypeId']) && $checkout['shippingMethodTypeId'] == DomainShippingType::ShippingType_Personally_Id) {
  401.                 $checkout['shippingMethodId'] = null;
  402.                 $checkout['paymentMethodId'] = null;
  403.             }
  404.             // Abandoned cart
  405.             if (!$request->getSession()->has('abandonedCart')) {
  406.                 $customer = $entityManager->getRepository(Customer::class)->findOneBy([
  407.                     'email' => $checkout['email'],
  408.                     'domain' => $this->getMultiStoreHelper($request)->getDomain(),
  409.                 ]);
  410.                 if ($customer) {
  411.                     $cart->setCustomer($customer);
  412.                 }
  413.                 $cart->setUpdated((new \DateTime('NOW')));
  414.                 $cart->setAbandonedEmail($checkout['email']);
  415.                 $entityManager->flush();
  416.             }
  417.             $checkout['step'] = 4;
  418.             $form = $this->createForm(CheckoutType::class, $checkout, [
  419.                 'locale' => $request->getLocale(),
  420.                 'defaultLocale' => $multiStore->getDefaultLocale(),
  421.                 'action' => $this->generateUrl('checkout_shipping_and_payment'),
  422.             ]);
  423.             $form->handleRequest($request);
  424.             if ($form->isSubmitted()) {
  425.                 $cart->setUpdated((new \DateTime('NOW')));
  426.                 $entityManager->flush();
  427.             }
  428.             if ($form->isSubmitted() && $form->isValid()) {
  429.                 $checkout['updated'] = new \DateTime();
  430.                 $checkout['shippingMethodId'] = (int)$form->get('shippingMethodId')->getData();
  431.                 $checkout['paymentMethodId'] = (int)$form->get('paymentMethodId')->getData();
  432.                 if ($request->request->get('packeta-pickup-point-id') != "") {
  433.                     $checkout['packetaPickupPointId'] = $request->request->get('packeta-pickup-point-id');
  434.                 }
  435.                 $checkout['packetaPickupPointTitle'] = (string)$request->request->get('packeta-pickup-point-title');
  436.                 $checkout['packetaPickupPointCarrierId'] = (string)$request->request->get('packeta-pickup-point-carrier-id');
  437.                 $checkout['shippingMethodPickupPointId'] = (int)$form->get('shippingMethodPickupPointId')->getData();
  438.                 $checkout['shippingMethodTypeId'] = (int)$form->get('shippingMethodTypeId')->getData();
  439.                 $checkout['paymentMethodTypeId'] = (int)$form->get('paymentMethodTypeId')->getData();
  440.                 $checkout['estimatedDeliveryDate'] = $form->get('estimatedDeliveryDate')->getData();
  441.                 $checkout['3_percent_discount'] = in_array($checkout['paymentMethodTypeId'], [6, 7, 8, 15]); // 3 Percent payments
  442.                 $request->getSession()->set('checkout', $checkout);
  443.                 return $this->redirectToRoute('checkout_review');
  444.             } elseif ($form->isSubmitted()) {
  445.                 $checkout['shippingMethodId'] = (int)$form->get('shippingMethodId')->getData();
  446.                 $checkout['paymentMethodId'] = (int)$form->get('paymentMethodId')->getData();
  447.                 $checkout['shippingMethodPickupPointId'] = (int)$form->get('shippingMethodPickupPointId')->getData();
  448.                 $checkout['shippingMethodTypeId'] = (int)$form->get('shippingMethodTypeId')->getData();
  449.                 $checkout['paymentMethodTypeId'] = (int)$form->get('paymentMethodTypeId')->getData();
  450.                 $checkout['estimatedDeliveryDate'] = $form->get('estimatedDeliveryDate')->getData();
  451.                 $data['error'] = true;
  452.             }
  453.             $data['form'] = $form->createView();
  454.             // Order Summary
  455.             $data['orderSummary'] = $orderSummary;
  456.             // Defaults
  457.             if (isset($checkout['shippingMethodId'])) {
  458.                 $data['shippingMethodId'] = (int)$checkout['shippingMethodId'];
  459.             } else {
  460.                 $data['shippingMethodId'] = 0;
  461.             }
  462.             if (isset($checkout['paymentMethodId'])) {
  463.                 $data['paymentMethodId'] = (int)$checkout['paymentMethodId'];
  464.             } else {
  465.                 $data['paymentMethodId'] = 0;
  466.             }
  467.             if (isset($checkout['paymentMethodTypeId'])) {
  468.                 $data['paymentMethodTypeId'] = (int)$checkout['paymentMethodTypeId'];
  469.             } else {
  470.                 $data['paymentMethodTypeId'] = 0;
  471.             }
  472.             if (isset($checkout['shippingMethodPickupPointId'])) {
  473.                 $data['shippingMethodPickupPointId'] = (int)$checkout['shippingMethodPickupPointId'];
  474.             } else {
  475.                 $data['shippingMethodPickupPointId'] = 0;
  476.             }
  477.             if (isset($data['shippingMethods'][$data['shippingMethodId']])) {
  478.                 $data['shippingMethod'] = $data['shippingMethods'][$data['shippingMethodId']];
  479.             } else {
  480.                 $data['shippingMethod'] = [];
  481.             }
  482.             if (isset($data['paymentMethods'][$data['paymentMethodId']])) {
  483.                 $data['paymentMethod'] = $data['paymentMethods'][$data['paymentMethodId']];
  484.             } else {
  485.                 $data['paymentMethod'] = [];
  486.             }
  487.             if (isset($data['pickupPoints'][$data['shippingMethodPickupPointId']])) {
  488.                 $data['pickupPoint'] = $data['pickupPoints'][$data['shippingMethodPickupPointId']];
  489.             } else {
  490.                 $data['pickupPoint'] = [];
  491.             }
  492.             //klarna
  493.             $shippingCountry = $checkout['shippingCountry'] ?? $domain->getLanguage()->getCode();
  494.             $klarna = $this->getKlarna($domainId, $request, $shippingCountry, $checkout['coupon'] ?? []);
  495.             if (!is_null($klarna)) {
  496.                 $klarnaSession = $klarna->createKlarnaSession($orderSummary, $checkout, $cart->getBasketItems());
  497.                 if ($klarna->isValidKlarnaSession($klarnaSession, $shippingCountry)) {
  498.                     $data['klarna_client_token'] = $klarnaSession['client_token'];
  499.                     $request->getSession()->set(
  500.                         'klarnaClientToken',
  501.                         $klarnaSession['client_token']
  502.                     );
  503.                     $request->getSession()->set(
  504.                         'klarnaSessionId',
  505.                         $klarnaSession['session_id']
  506.                     );
  507.                 }
  508.             }
  509.             $data['quatro_calculator'] = $this->getParameter('quatro_calculator_url');
  510.             $domain = $multiStore->getDomain();
  511.             $data['currency'] = $domain->getCurrency();
  512.             $data['precision'] = $domain->getPricePrecision();
  513.             $data['header'] = $this->getHeader($request);
  514.             $data['footer'] = $this->getFooter($request);
  515.             $data['contentBottom'] = $this->getContentBottom($request);
  516.             $data['stepsOptions'] = $this->checkoutSteps(4);
  517.             $data['domain'] = $domain;
  518.             $data['cashOnDeliveryLimits'] = DomainShippingType::getCashOnDeliveryPriceLimits($domain->getId());
  519.             $data['basketItemListIncludesMobileProduct'] = $this->getEntityManager()->getRepository(Order::class)->isBasketItemListIncludesMobileProduct($cart);
  520.             $data['paymentType'] = PaymentType::toArray();
  521.             $data['currentCustomer'] = $this->getLoginHelper($request)->getLoggedInCustomer();
  522.             return $this->render('AtechNetCoreBundle/Checkout/shippingPayment.html.twig', $data);
  523.         }
  524.         return $this->redirectToRoute('cart_show');
  525.     }
  526.     /**
  527.      * @Route("/checkout/address", name="checkout_address", defaults={"_locale":""})
  528.      * @Route("/{_locale<%supported_locales%>?}/checkout/address", name="checkout_address_locale", defaults={"_locale":""})
  529.      * @param Request $request
  530.      * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
  531.      * @throws \Exception
  532.      */
  533.     public function addressAction(Request $request)
  534.     {
  535.         $data = [];
  536.         $data['hideChat'] = true;
  537.         // Multi-Store
  538.         $multiStore = $this->getMultiStoreHelper($request);
  539.         // Checkout DATA
  540.         if ($request->getSession()->has('checkout')) {
  541.             $checkout = $request->getSession()->get('checkout');
  542.         } else {
  543.             $checkout = [];
  544.         }
  545.         $customerTypeId = $request->getSession()->get('customerTypeId');
  546.         $checkout['customerTypeId'] = $customerTypeId;
  547.         // Get Cart Items
  548.         $cart = $this->getCart($request->getSession()->get('cartId'));
  549.         if ($cart) {
  550.             $data['abandonedCartLink'] = $this->getKlaviyoConnect($request)->createPublicUrlForAbandonedCart($cart);
  551.             $entityManager = $this->getEntityManager();
  552.             $translator = $this->getTranslator();
  553.             // Basket expires
  554.             $cartUpdated = clone $cart->getUpdated();
  555.             // if ($cartUpdated->add(new \DateInterval("PT" . self::TIMEOUT . "H")) <= (new \DateTime('NOW'))) {
  556.             //     $entityManager->remove($cart);
  557.             //     $entityManager->flush();
  558.             //     return $this->redirectToRoute('cart_show');
  559.             // }
  560.             $orderSummary = $this->orderSummary($cart, $request);
  561.             // Validate cart has products and has stock.
  562.             if (!$orderSummary['valid'] && $orderSummary['countItems'] > 0) {
  563.                 return $this->redirectToRoute('cart_show');
  564.             }
  565.             $checkout['step'] = 3;
  566.             if (!isset($checkout['isCompany'])) {
  567.                 $checkout['isCompany'] = false;
  568.             }
  569.             if (!isset($checkout['billingAddressIsShippingAddress'])) {
  570.                 $checkout['billingAddressIsShippingAddress'] = true;
  571.             }
  572.             if ($customerTypeId == MultiStore::CUSTOMER_TYPE_WHOLESALE) {
  573.                 $checkout['isCompany'] = true;
  574.                 $checkout['billingAddressIsShippingAddress'] = false;
  575.             }
  576.             if (!isset($checkout['register'])) {
  577.                 $checkout['register'] = false;
  578.             }
  579.             $data['domainLanguageCode'] = $multiStore->getDefaultLanguage()->getCode();
  580.             $data['loggedIn'] = false;
  581.             $loggedInCustomer = $this->getLoginHelper($request)->getLoggedInCustomer();
  582.             if ($loggedInCustomer) {
  583.                 $checkout['billingFirstName'] = $loggedInCustomer->getFirstName();
  584.                 $checkout['billingLastName'] = $loggedInCustomer->getLastName();
  585.                 $checkout['billingBusinessName'] = $loggedInCustomer->getBusinessName();
  586.                 $checkout['billingCity'] = '';
  587.                 $checkout['billingPostalCode'] = '';
  588.                 $checkout['billingAddress'] = '';
  589.                 $checkout['isCompany'] = $loggedInCustomer->isCompany();
  590.                 $billingAddress = null;
  591.                 $shippingAddresses = [];
  592.                 foreach ($loggedInCustomer->getAddresses() as $address) {
  593.                     if ($address->getType() == CustomerAddress::AddressType_Billing_Id) {
  594.                         $billingAddress = $address;
  595.                     } else {
  596.                         $shippingAddresses[] = $address;
  597.                     }
  598.                 }
  599.                 if ($billingAddress) {
  600.                     $checkout['billingFirstName'] = $billingAddress->getFirstName();
  601.                     $checkout['billingLastName'] = $billingAddress->getLastName();
  602.                     $checkout['billingBusinessName'] = $billingAddress->getBusinessName() ?? $loggedInCustomer->getBusinessName();
  603.                     $checkout['billingCity'] = $billingAddress->getCity();
  604.                     $checkout['billingPostalCode'] = $billingAddress->getZip();
  605.                     $checkout['billingAddress'] = $billingAddress->getStreet();
  606.                 }
  607.                 if (empty($shippingAddresses)) {
  608.                     $checkout['shippingFirstName'] = $checkout['billingFirstName'];
  609.                     $checkout['shippingLastName'] = $checkout['billingLastName'];
  610.                     $checkout['shippingBusinessName'] = $checkout['billingBusinessName'];
  611.                     $checkout['shippingCity'] = $checkout['billingCity'];
  612.                     $checkout['shippingPostalCode'] = $checkout['billingPostalCode'];
  613.                     $checkout['shippingAddress'] = $checkout['billingAddress'];
  614.                 } else {
  615.                     $shippingAddress = end($shippingAddresses);
  616.                     $checkout['shippingFirstName'] = $shippingAddress->getFirstName();
  617.                     $checkout['shippingLastName'] = $shippingAddress->getLastName();
  618.                     $checkout['shippingBusinessName'] = $shippingAddress->getBusinessName();
  619.                     $checkout['shippingCity'] = $shippingAddress->getCity();
  620.                     $checkout['shippingPostalCode'] = $shippingAddress->getZip();
  621.                     $checkout['shippingAddress'] = $shippingAddress->getStreet();
  622.                 }
  623.                 // Phone Number
  624.                 $phoneNumber = $loggedInCustomer->getPhone();
  625.                 // Remove non-numeric characters
  626.                 $_phoneNumber = preg_replace('/[^0-9]/', '', $phoneNumber);
  627.                 // Add plus sign if was removed
  628.                 if (substr($phoneNumber, 0, 1) == '+') {
  629.                     $_phoneNumber = '+' . $_phoneNumber;
  630.                 }
  631.                 // Remove calling codes to prevent duplication
  632.                 if ($data['domainLanguageCode'] == 'cz') {
  633.                     $checkout['shippingPhoneNumber'] = preg_replace('/^(\+420|00420)/', '', $_phoneNumber);
  634.                 } elseif ($data['domainLanguageCode'] == 'hu') {
  635.                     $checkout['shippingPhoneNumber'] = preg_replace('/^(\+36|0036|06)/', '', $_phoneNumber);
  636.                 } else {
  637.                     $checkout['shippingPhoneNumber'] = preg_replace('/^(\+421|00421|0)/', '', $_phoneNumber);
  638.                 }
  639.                 $checkout['billingBusinessId'] = $loggedInCustomer->getBusinessId();
  640.                 $checkout['billingTaxId'] = $loggedInCustomer->getTaxId();
  641.                 $checkout['billingVatNumber'] = $loggedInCustomer->getVatId();
  642.                 if (($checkout['billingFirstName'] . $checkout['billingLastName'] . $checkout['billingCity'] . $checkout['billingPostalCode'] . $checkout['billingAddress']) !== ($checkout['shippingFirstName'] . $checkout['shippingLastName'] . $checkout['shippingCity'] . $checkout['shippingPostalCode'] . $checkout['shippingAddress'])) {
  643.                     $checkout['billingAddressIsShippingAddress'] = false;
  644.                 }
  645.                 $data['loggedIn'] = true;
  646.             } elseif (!empty($checkout['shippingPhoneNumber'])) {
  647.                 // Phone Number
  648.                 $phoneNumber = $checkout['shippingPhoneNumber'];
  649.                 // Remove non-numeric characters
  650.                 $_phoneNumber = preg_replace('/[^0-9]/', '', $phoneNumber);
  651.                 // Add plus sign if was removed
  652.                 if (substr($phoneNumber, 0, 1) == '+') {
  653.                     $_phoneNumber = '+' . $_phoneNumber;
  654.                 }
  655.                 // Remove calling codes to prevent duplication
  656.                 if ($data['domainLanguageCode'] == 'cz') {
  657.                     $checkout['shippingPhoneNumber'] = preg_replace('/^(\+420|00420)/', '', $_phoneNumber);
  658.                 } elseif ($data['domainLanguageCode'] == 'hu') {
  659.                     $checkout['shippingPhoneNumber'] = preg_replace('/^(\+36|0036|06)/', '', $_phoneNumber);
  660.                 } else {
  661.                     $checkout['shippingPhoneNumber'] = preg_replace('/^(\+421|00421|0)/', '', $_phoneNumber);
  662.                 }
  663.             }
  664.             $form = $this->createForm(CheckoutType::class, $checkout, [
  665.                 'locale' => $request->getLocale(),
  666.                 'defaultLocale' => $multiStore->getDefaultLocale(),
  667.                 'action' => $this->generateUrl('checkout_address'),
  668.             ]);
  669.             $form->handleRequest($request);
  670.             if ($form->isSubmitted()) {
  671.                 $checkout['updated'] = new \DateTime();
  672.                 $checkout['register'] = $form->get('register')->getData();
  673.                 $checkout['shippingFirstName'] = $form->get('shippingFirstName')->getData();
  674.                 $checkout['shippingLastName'] = $form->get('shippingLastName')->getData();
  675.                 $checkout['shippingBusinessName'] = $form->get('shippingBusinessName')->getData();
  676.                 
  677.                 if ($multiStore->getDomain()->getId() == Domain::DOMAIN_ID_RT_EU) {
  678.                     $checkout['shippingCountry'] = $form->get('shippingCountry')->getData();
  679.                 }
  680.                 $checkout['shippingCity'] = $form->get('shippingCity')->getData();
  681.                 $checkout['shippingPostalCode'] = preg_replace('/\D/', ' ', $form->get('shippingPostalCode')->getData());
  682.                 $checkout['shippingAddress'] = $form->get('shippingAddress')->getData();
  683.                 // Phone Number
  684.                 $phoneNumber = $form->get('shippingPhoneNumber')->getData();
  685.                 // Remove non-numeric characters
  686.                 $_phoneNumber = preg_replace('/[^0-9]/', '', $phoneNumber);
  687.                 // Add plus sign if was removed
  688.                 if (substr($phoneNumber, 0, 1) == '+') {
  689.                     $_phoneNumber = '+' . $_phoneNumber;
  690.                 }
  691.                 // Remove calling codes to prevent duplication
  692.                 if ($data['domainLanguageCode'] == 'cz') {
  693.                     $checkout['shippingPhoneNumber'] = '+420' . preg_replace('/^(\+420|00420)/', '', $_phoneNumber);
  694.                 } elseif ($data['domainLanguageCode'] == 'hu') {
  695.                     $checkout['shippingPhoneNumber'] = '+36' . preg_replace('/^(\+36|0036|06)/', '', $_phoneNumber);
  696.                 } elseif ($data['domainLanguageCode'] == 'sk') {
  697.                     $checkout['shippingPhoneNumber'] = '+421' . preg_replace('/^(\+421|00421|0)/', '', $_phoneNumber);
  698.                 } else {
  699.                     $checkout['shippingPhoneNumber'] = $_phoneNumber;
  700.                 }
  701.                 $checkout['isCompany'] = $form->get('isCompany')->getData();
  702.                 $checkout['billingBusinessName'] = $form->get('billingBusinessName')->getData();
  703.                 $checkout['billingBusinessId'] = $form->get('billingBusinessId')->getData();
  704.                 $checkout['billingTaxId'] = $form->get('billingTaxId')->getData();
  705.                 $checkout['billingVatNumber'] = $form->get('billingVatNumber')->getData();
  706.                 if ((is_null($checkout['billingVatNumber']) || $checkout['billingVatNumber'] == '') && $multiStore->getDefaultLocale() == 'cz') {
  707.                     $checkout['billingVatNumber'] = $checkout['billingTaxId'];
  708.                 }
  709.                 $checkout['billingAddressIsShippingAddress'] = $form->get('billingAddressIsShippingAddress')->getData();
  710.                 $checkout['billingFirstName'] = $form->get('billingFirstName')->getData();
  711.                 $checkout['billingLastName'] = $form->get('billingLastName')->getData();
  712.                 if ($multiStore->getDomain()->getId() == Domain::DOMAIN_ID_RT_EU) {
  713.                     $checkout['billingCountry'] = $checkout['billingAddressIsShippingAddress'] ? $form->get('shippingCountry')->getData() : $form->get('billingCountry')->getData();
  714.                 }
  715.                 $checkout['billingCity'] = $form->get('billingCity')->getData();
  716.                 $checkout['billingPostalCode'] = preg_replace('/\D/', ' ', $form->get('billingPostalCode')->getData());
  717.                 $checkout['billingAddress'] = $form->get('billingAddress')->getData();
  718.                 if ($loggedInCustomer && !in_array($loggedInCustomer->getId(), $this->getGuestAccountIds())) {
  719.                     $billingAddress = false;
  720.                     $shippingAddress = false;
  721.                     foreach ($loggedInCustomer->getAddresses() as $address) {
  722.                         if ($address->getType() == CustomerAddress::AddressType_Billing_Id) {
  723.                             $billingAddress = $address;
  724.                         } else {
  725.                             $shippingAddress = $address;
  726.                         }
  727.                     }
  728.                     if (isset($checkout['billingBusinessName']) && $checkout['billingBusinessName'] != '') {
  729.                         $loggedInCustomer->setBusinessName($checkout['billingBusinessName']);
  730.                     }
  731.                     if (isset($checkout['billingBusinessId']) && $checkout['billingBusinessId'] != '') {
  732.                         $loggedInCustomer->setBusinessId(str_replace([' ', '-'], '', $checkout['billingBusinessId']));
  733.                     }
  734.                     if (isset($checkout['billingTaxId']) && $checkout['billingTaxId'] != '') {
  735.                         $loggedInCustomer->setTaxId($checkout['billingTaxId']);
  736.                     }
  737.                     if (isset($checkout['billingVatNumber']) && $checkout['billingVatNumber'] != '') {
  738.                         $loggedInCustomer->setVatId($checkout['billingVatNumber']);
  739.                     }
  740.                     $persistShippingAddress = false;
  741.                     if (!$shippingAddress) {
  742.                         $shippingAddress = new CustomerAddress();
  743.                         $shippingAddress->setType(CustomerAddress::AddressType_Shipping_Id);
  744.                         $shippingAddress->setCustomer($loggedInCustomer);
  745.                         $shippingAddress->setTitle('.');
  746.                         $persistShippingAddress = true;
  747.                     }
  748.                     switch ($loggedInCustomer->getDomain()->getId()) {
  749.                         case Domain::DOMAIN_ID_RT_SK:
  750.                         case Domain::DOMAIN_ID_WS_SK:
  751.                             $country = 'SK';
  752.                             break;
  753.                         case Domain::DOMAIN_ID_RT_HU:
  754.                         case Domain::DOMAIN_ID_WS_HU:
  755.                             $country = 'HU';
  756.                             break;
  757.                         case Domain::DOMAIN_ID_RT_CZ:
  758.                         case Domain::DOMAIN_ID_WS_CZ:
  759.                             $country = 'CZ';
  760.                             break;
  761.                         default:
  762.                             $country = 'EN';
  763.                     }
  764.                     if ($country == 'EN' && !is_null($loggedInCustomer->getCountry())) {
  765.                         $country = $loggedInCustomer->getCountry();
  766.                         $checkout['billingCountry'] = $country;
  767.                         $checkout['shippingCountry'] = $country;
  768.                     }
  769.                     $street = !is_null($checkout['shippingAddress']) ? $checkout['shippingAddress'] : '';
  770.                     $shippingAddress->setFirstName($checkout['shippingFirstName']);
  771.                     $shippingAddress->setLastName($checkout['shippingLastName']);
  772.                     $shippingAddress->setBusinessName($checkout['shippingBusinessName']);
  773.                     $shippingAddress->setStreet($street);
  774.                     $shippingAddress->setCity($checkout['shippingCity']);
  775.                     $shippingAddress->setZip($checkout['shippingPostalCode']);
  776.                     $shippingAddress->setPhone($checkout['shippingPhoneNumber']);
  777.                     $shippingAddress->setEmail($loggedInCustomer->getEmail());
  778.                     $shippingAddress->setCountry($country);
  779.                     $loggedInCustomer->setPhone($checkout['shippingPhoneNumber']);
  780.                     if ($persistShippingAddress) {
  781.                         $entityManager->persist($shippingAddress);
  782.                     }
  783.                     if (!$checkout['billingAddressIsShippingAddress']) {
  784.                         $persistBillingAddress = false;
  785.                         if (!$billingAddress) {
  786.                             $billingAddress = new CustomerAddress();
  787.                             $billingAddress->setType(CustomerAddress::AddressType_Billing_Id);
  788.                             $billingAddress->setCustomer($loggedInCustomer);
  789.                             $billingAddress->setTitle('.');
  790.                             $persistBillingAddress = true;
  791.                         }
  792.                         $street = !is_null($checkout['billingAddress']) ? $checkout['billingAddress'] : '';
  793.                         $billingAddress->setFirstName($checkout['billingFirstName']);
  794.                         $billingAddress->setLastName($checkout['billingLastName']);
  795.                         $billingAddress->setBusinessName($checkout['billingBusinessName']);
  796.                         $billingAddress->setStreet($street);
  797.                         $billingAddress->setCity($checkout['billingCity']);
  798.                         $billingAddress->setZip($checkout['billingPostalCode']);
  799.                         $billingAddress->setPhone($checkout['shippingPhoneNumber']);
  800.                         $billingAddress->setEmail($loggedInCustomer->getEmail());
  801.                         $billingAddress->setCountry($country);
  802.                         if ($persistBillingAddress) {
  803.                             $entityManager->persist($billingAddress);
  804.                         }
  805.                     } else {
  806.                         $persistBillingAddress = false;
  807.                         if (!$billingAddress) {
  808.                             $billingAddress = new CustomerAddress();
  809.                             $billingAddress->setType(CustomerAddress::AddressType_Billing_Id);
  810.                             $billingAddress->setCustomer($loggedInCustomer);
  811.                             $billingAddress->setTitle('.');
  812.                             $persistBillingAddress = true;
  813.                         }
  814.                         $street = !is_null($checkout['shippingAddress']) ? $checkout['shippingAddress'] : '';
  815.                         $billingAddress->setFirstName($checkout['shippingFirstName']);
  816.                         $billingAddress->setLastName($checkout['shippingLastName']);
  817.                         $billingAddress->setBusinessName($checkout['shippingBusinessName']);
  818.                         $billingAddress->setStreet($street);
  819.                         $billingAddress->setCity($checkout['shippingCity']);
  820.                         $billingAddress->setZip($checkout['shippingPostalCode']);
  821.                         $billingAddress->setPhone($checkout['shippingPhoneNumber']);
  822.                         $billingAddress->setEmail($loggedInCustomer->getEmail());
  823.                         $billingAddress->setCountry($country);
  824.                         if ($persistBillingAddress) {
  825.                             $entityManager->persist($billingAddress);
  826.                         }
  827.                     }
  828.                 }
  829.                 $cart->setUpdated((new \DateTime('NOW')));
  830.                 $entityManager->flush();
  831.                 $request->getSession()->set('checkout', $checkout);
  832.                 if ($form->get('register')->getData() === true) {
  833.                     $domain = $entityManager->getRepository(Domain::class)->findOneById(MultiStore::defineDomainId($request->getSession()->get('customerTypeId'), $request->getHttpHost()));
  834.                     switch ($domain->getId()) {
  835.                         case Domain::DOMAIN_ID_RT_SK:
  836.                             $domainsToCheck = '1,2';
  837.                             break;
  838.                         case Domain::DOMAIN_ID_RT_HU:
  839.                             $domainsToCheck = '3,4';
  840.                             break;
  841.                         case Domain::DOMAIN_ID_RT_CZ:
  842.                             $domainsToCheck = '9,5';
  843.                             break;
  844.                         case Domain::DOMAIN_ID_RT_EU:
  845.                             $domainsToCheck = '7,11';
  846.                             break;
  847.                         default:
  848.                             $domainsToCheck = '';
  849.                     }
  850.                     $duplicateCustomerCheck = $entityManager
  851.                         ->createQuery("SELECT c FROM AtechNetCoreBundle:Customer c WHERE c.email = :email AND c.domain IN (" . $domainsToCheck . ")")
  852.                         ->setParameter('email', $checkout['email'])
  853.                         ->getResult();
  854.                     if (count($duplicateCustomerCheck) > 0) {
  855.                         $this->addFlash(
  856.                             'errorRegister',
  857.                             $translator->trans('E-Mail Address is already registered')
  858.                         );
  859.                         return $this->redirectToRoute('checkout_address');
  860.                     }
  861.                 }
  862.             }
  863.             if ($form->isSubmitted()) {
  864.                 if (!empty($form->get('password')->getData()) && SecurityHelper::insecure($form->get('password')->getData())) {
  865.                     $form->get('password')->addError(new FormError($translator->trans('Unfortunately, the password provided is not secure, therefore it cannot be used in our webshop')));
  866.                 }
  867.             }
  868.             if ($form->isSubmitted() && $form->isValid()) {
  869.                 $checkout['password'] = $form->get('password')->getData();
  870.                 if ($checkout['isCompany'] && isset($checkout['coupon']) && $checkout['coupon']['code'] == 'DIV+furbify') {
  871.                     unset($checkout['coupon']);
  872.                     $cart->setCouponCode(null);
  873.                     $entityManager->flush();
  874.                     $this->addFlash(type: 'shippingError', message: 'A "DIV+furbify" kuponkód el lett távolítva a kosaradból.');
  875.                 }
  876.                 $request->getSession()->set('checkout', $checkout);
  877.                 return $this->redirectToRoute('checkout_shipping_and_payment');
  878.             }
  879.             $data['form'] = $form->createView();
  880.             // Checkout DATA
  881.             $data['checkout'] = [
  882.                 'register' => $checkout['register'],
  883.             ];
  884.             // Order Summary
  885.             $data['orderSummary'] = $orderSummary;
  886.             $data['isCompany'] = (bool)$checkout['isCompany'];
  887.             $data['billingAddressIsShippingAddress'] = (bool)$checkout['billingAddressIsShippingAddress'];
  888.             $data['legal_links'] = $this->getLegalLinks($request, $cart->getDomain()->getId());
  889.             if ($data['domainLanguageCode'] == 'cz') {
  890.                 $data['callingCountryCode'] = '+420';
  891.             } elseif ($data['domainLanguageCode'] == 'hu') {
  892.                 $data['callingCountryCode'] = '+36';
  893.             } else {
  894.                 $data['callingCountryCode'] = '+421';
  895.             }
  896.             $domain = $this->getMultiStoreHelper($request)->getDomain();
  897.             if ($domain->getId() != Domain::DOMAIN_ID_WS_EU) {
  898.                 $data['countryValue'] = $translator->trans(strtoupper($data['domainLanguageCode']));
  899.                 if ($loggedInCustomer) {
  900.                     $country = $loggedInCustomer->getCountry() ?? $domain->getLanguage()->getCode();
  901.                     $data['countryName'] = Countries::getNames()[strtoupper($country)];
  902.                 }
  903.             } else {
  904.                 $data['countryValue'] = $cart->getCustomer()->getCountry();
  905.             }
  906.             
  907.             $data['insecurePasswords'] = SecurityHelper::getMostCommonPasswords();
  908.             $data['header'] = $this->getHeader($request);
  909.             $data['footer'] = $this->getFooter($request);
  910.             $data['contentBottom'] = $this->getContentBottom($request);
  911.             $data['stepsOptions'] = $this->checkoutSteps(3);
  912.             $data['domainType'] = $cart->getDomain()->getType();
  913.             $data['diversumCodeIsActive'] = isset($checkout['coupon']) && $checkout['coupon']['code'] == 'DIV+furbify';
  914.             return $this->render('AtechNetCoreBundle/Checkout/address.html.twig', $data);
  915.         }
  916.         return $this->redirectToRoute('cart_show');
  917.     }
  918.     /**
  919.      * @Route("/checkout/review", name="checkout_review", defaults={"_locale":""})
  920.      * @Route("/{_locale<%supported_locales%>?}/checkout/review", name="checkout_review_locale", defaults={"_locale":""})
  921.      * @param Request $request
  922.      * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
  923.      * @throws \Doctrine\ORM\OptimisticLockException
  924.      */
  925.     public function reviewAction(Request $request, UserPasswordHasherInterface $passwordHasher)
  926.     {
  927.         $data = [];
  928.         $statisticsEntityManager = $this->getEntityManager('statistics');
  929.         $data['hideChat'] = true;
  930.         // Checkout DATA
  931.         if ($request->getSession()->has('checkout')) {
  932.             $checkout = $request->getSession()->get('checkout');
  933.         } else {
  934.             $checkout = [];
  935.         }
  936.         /**
  937.          * @var Basket $cart
  938.          */
  939.         $cart = $this->getCart($request->getSession()->get('cartId'));
  940.         if ($cart) {
  941.             $entityManager = $this->getEntityManager();
  942.             $translator = $this->getTranslator();
  943.             // Multi-Store
  944.             $multiStore = $this->getMultiStoreHelper($request);
  945.             // Basket expires
  946.             $cartUpdated = clone $cart->getUpdated();
  947.             // if ($cartUpdated->add(new \DateInterval("PT" . self::TIMEOUT . "H")) <= (new \DateTime('NOW'))) {
  948.             //     $entityManager->remove($cart);
  949.             //     $entityManager->flush();
  950.             //     return $this->redirectToRoute('cart_show');
  951.             // }
  952.             $orderSummary = $this->orderSummary($cart, $request);
  953.             // Validate Pickup Point availability
  954.             if (!$orderSummary['validShipping']) {
  955.                 return $this->redirectToRoute('checkout_shipping_and_payment');
  956.             }
  957.             // Logged in Customer
  958.             if ($this->getLoginHelper($request)->getLoggedInCustomerId()) {
  959.                 $data['loggedIn'] = true;
  960.             } else {
  961.                 $data['loggedIn'] = false;
  962.             }
  963.             // Validate cart has products and has stock
  964.             if (!$orderSummary['valid'] && $orderSummary['countItems'] > 0) {
  965.                 return $this->redirectToRoute('cart_show');
  966.             }
  967.             // Validate payment method
  968.             $selectedInvalidBnpPayment = $entityManager->getRepository(Order::class)->haveNotFinishedBnpOrdersFromThisCustomer($cart, PaymentType::from($checkout['paymentMethodTypeId']));
  969.             if (empty($checkout['paymentMethodTypeId']) || $selectedInvalidBnpPayment) {
  970.                 return $this->redirectToRoute('checkout_shipping_and_payment');
  971.             }
  972.             // Validate shipping method
  973.             if (empty($checkout['shippingMethodTypeId'])) {
  974.                 return $this->redirectToRoute('checkout_shipping_and_payment');
  975.             }
  976.             // Validate Pickup Point availability
  977.             if (!$orderSummary['validShipping']) {
  978.                 return $this->redirectToRoute('checkout_shipping_and_payment');
  979.             }
  980.             // Payment method
  981.             if ($cart->getDomain()->getId() == Domain::DOMAIN_ID_WS_HU && $checkout['paymentMethodTypeId'] == PaymentType::BankTransfer->value) {
  982.                 $translationKey = 'payment.method.type.' . $checkout['paymentMethodTypeId'] . '.wshu';
  983.             } else {
  984.                 $translationKey = 'payment.method.type.' . $checkout['paymentMethodTypeId'];
  985.             }
  986.             if (($title = $translator->trans($translationKey)) == $translationKey) {
  987.                 $title = false;
  988.             }
  989.             if (($description = $translator->trans($translationKey . '.description')) == $translationKey . '.description') {
  990.                 $description = false;
  991.             }
  992.             $data['paymentMethod'] = [
  993.                 'title' => $title,
  994.                 'description' => $description,
  995.                 'cetelem_calculator' => false,
  996.             ];
  997.             $domain = $cart->getDomain();
  998.             // Cetelem
  999.             if ($checkout['paymentMethodTypeId'] == PaymentType::Cetelem->value) {
  1000.                 $data['paymentMethod']['cetelem_calculator'] = true;
  1001.                 $data['paymentMethod']['cetelem_calculator_country'] = $domain->getLanguage()->getCode();
  1002.             }
  1003.             // Shipping method
  1004.             $translationKey = 'shipping.method.type.' . $checkout['shippingMethodTypeId'];
  1005.             if (($title = $translator->trans($translationKey)) == $translationKey) {
  1006.                 $title = false;
  1007.             }
  1008.             if (($description = $translator->trans($translationKey . '.description')) == $translationKey . '.description') {
  1009.                 $description = false;
  1010.             }
  1011.             $data['shippingMethod'] = [
  1012.                 'title' => $title,
  1013.                 'description' => $description,
  1014.             ];
  1015.             if ((int)$checkout['shippingMethodPickupPointId'] > 0) {
  1016.                 $pickupPoint = $entityManager->getRepository(PickupPoint::class)->findOneById($checkout['shippingMethodPickupPointId']);
  1017.                 if ($pickupPoint) {
  1018.                     $data['pickupPoint'] = [
  1019.                         'title' => $pickupPoint->getTitle(),
  1020.                         'address' => $pickupPoint->getCity() . ', ' . $pickupPoint->getStreet(),
  1021.                         'street' => $pickupPoint->getStreet(),
  1022.                         'city' => $pickupPoint->getCity(),
  1023.                         'zip' => $pickupPoint->getZip(),
  1024.                     ];
  1025.                 }
  1026.             }
  1027.             $checkout['step'] = 5;
  1028.             $form = $this->createForm(CheckoutType::class, $checkout, [
  1029.                 'locale' => $request->getLocale(),
  1030.                 'defaultLocale' => $multiStore->getDefaultLocale(),
  1031.                 'action' => $this->generateUrl('checkout_review'),
  1032.             ]);
  1033.             $form->handleRequest($request);
  1034.             if ($form->isSubmitted()) {
  1035.                 $checkout['messageToSeller'] = $form->get('messageToSeller')->getData();
  1036.                 $checkout['newsletter'] = $form->get('newsletter')->getData();
  1037.                 $cart->setUpdated((new \DateTime('NOW')));
  1038.                 $entityManager->flush();
  1039.                 $request->getSession()->set('checkout', $checkout);
  1040.             }
  1041.             if ($form->isSubmitted() && $form->isValid()) {
  1042.                 $entityManager = $this->getEntityManager();
  1043.                 $multiStore = $this->getMultiStoreHelper($request);
  1044.                 $domain = $multiStore->getDomain();
  1045.                 // New Order
  1046.                 $order = new Order();
  1047.                 $order->setStatus(Order::STATUS_TRIAGE);
  1048.                 $order->setDomain($domain);
  1049.                 $order->setPriority(true);
  1050.                 $country = $multiStore->getDefaultCountry();
  1051.                 if (isset($checkout['billingCountry']) && $checkout['billingCountry'] != '') {
  1052.                     $country = $checkout['billingCountry'];
  1053.                 }
  1054.                 if ($this->getLoginHelper($request)->getLoggedInCustomerId()) { //Logged in Customer
  1055.                     $customer = $this->getLoginHelper($request)->getLoggedInCustomer();
  1056.                     $order->setCustomer($customer);
  1057.                 } elseif (isset($checkout['register']) && $checkout['register']) { // New Customer
  1058.                     $customer = new Customer();
  1059.                     $customer->setEmail($checkout['email']);
  1060.                     $customer->setPhone($checkout['shippingPhoneNumber']);
  1061.                     $customer->setPassword($checkout['password']);
  1062.                     $customer->setGuest(false);
  1063.                     if (!empty($checkout['billingFirstName'])) {
  1064.                         $customer->setFirstName($checkout['billingFirstName']);
  1065.                     } else {
  1066.                         $customer->setFirstName($checkout['shippingFirstName']);
  1067.                     }
  1068.                     if (!empty($checkout['billingLastName'])) {
  1069.                         $customer->setLastName($checkout['billingLastName']);
  1070.                     } else {
  1071.                         $customer->setLastName($checkout['shippingLastName']);
  1072.                     }
  1073.                     if (!empty($checkout['billingBusinessName'])) {
  1074.                         $customer->setBusinessName($checkout['billingBusinessName']);
  1075.                     }
  1076.                     if (!empty($checkout['billingBusinessId'])) {
  1077.                         $customer->setBusinessId(str_replace([' ', '-'], '', $checkout['billingBusinessId']));
  1078.                     }
  1079.                     if (!empty($checkout['billingTaxId'])) {
  1080.                         $customer->setTaxId($checkout['billingTaxId']);
  1081.                     }
  1082.                     if (!empty($checkout['billingVatNumber'])) {
  1083.                         $customer->setVatId($checkout['billingVatNumber']);
  1084.                     }
  1085.                     $registration = new Registration($this->getEntityManager(), $request, $passwordHasher);
  1086.                     $registration->save($customer, $domain);
  1087.                     $entityManager->flush();
  1088.                     // Billing Address
  1089.                     $billingAddress = new CustomerAddress();
  1090.                     $billingAddress->setCustomer($customer);
  1091.                     $billingAddress->setType(CustomerAddress::AddressType_Billing_Id);
  1092.                     $billingAddress->setTitle($translator->trans('Billing address'));
  1093.                     if ($checkout['billingAddressIsShippingAddress']) {
  1094.                         $billingAddress->setFirstName($checkout['shippingFirstName']);
  1095.                         $billingAddress->setLastName($checkout['shippingLastName']);
  1096.                         $billingAddress->setStreet($checkout['shippingAddress']);
  1097.                         $billingAddress->setZip($checkout['shippingPostalCode']);
  1098.                         $billingAddress->setCity($checkout['shippingCity']);
  1099.                         if ($domain->getId() == Domain::DOMAIN_ID_RT_EU) {
  1100.                             $billingAddress->setCountry($checkout['shippingCountry']);
  1101.                         } else {
  1102.                             $billingAddress->setCountry($country);
  1103.                         }
  1104.                     } else {
  1105.                         $billingAddress->setFirstName($checkout['billingFirstName']);
  1106.                         $billingAddress->setLastName($checkout['billingLastName']);
  1107.                         $billingAddress->setStreet($checkout['billingAddress']);
  1108.                         $billingAddress->setZip($checkout['billingPostalCode']);
  1109.                         $billingAddress->setCity($checkout['billingCity']);
  1110.                         if ($domain->getId() == Domain::DOMAIN_ID_RT_EU) {
  1111.                             $billingAddress->setCountry($checkout['billingCountry']);
  1112.                         } else {
  1113.                             $billingAddress->setCountry($country);
  1114.                         }
  1115.                     }
  1116.                     // District
  1117.                     $billingAddress->setDistrict(OrderHelper::findDistrict($billingAddress->getZip(), $billingAddress->getCountry(), $request));
  1118.                     $entityManager->persist($billingAddress);
  1119.                     $entityManager->flush();
  1120.                     // Shipping Address
  1121.                     if (!$checkout['billingAddressIsShippingAddress']) {
  1122.                         $shippingAddress = new CustomerAddress();
  1123.                         $shippingAddress->setCustomer($customer);
  1124.                         $shippingAddress->setType(CustomerAddress::AddressType_Shipping_Id);
  1125.                         $shippingAddress->setTitle($translator->trans('Shipping address'));
  1126.                         $shippingAddress->setFirstName($checkout['shippingFirstName']);
  1127.                         $shippingAddress->setLastName($checkout['shippingLastName']);
  1128.                         $shippingAddress->setStreet($checkout['shippingAddress']);
  1129.                         $shippingAddress->setZip($checkout['shippingPostalCode']);
  1130.                         $shippingAddress->setCity($checkout['shippingCity']);
  1131.                         if ($domain->getId() == Domain::DOMAIN_ID_RT_EU) {
  1132.                             $shippingAddress->setCountry($checkout['shippingCountry']);
  1133.                         } else {
  1134.                             $shippingAddress->setCountry($country);
  1135.                         }
  1136.                         $entityManager->persist($shippingAddress);
  1137.                         $entityManager->flush();
  1138.                     }
  1139.                     $entityManager->refresh($customer);
  1140.                     $order->setCustomer($customer);
  1141.                 } else { // Guest Customer
  1142.                     // Try to set customer from existing accounts
  1143.                     $guestCustomer = $entityManager->getRepository(Customer::class)->findOneBy([
  1144.                         'domain' => $domain,
  1145.                         'email' => $checkout['email'],
  1146.                     ]);
  1147.                     /**
  1148.                      * @var Customer $guestCustomer
  1149.                      */
  1150.                     if (!$guestCustomer) {
  1151.                         $guestCustomer = new Customer();
  1152.                         $guestCustomer->setDomain($domain);
  1153.                         $guestCustomer->setActive(true);
  1154.                         $guestCustomer->setEmail($checkout['email']);
  1155.                         $guestCustomer->setPhone($checkout['shippingPhoneNumber']);
  1156.                         $guestCustomer->setType(Customer::TYPE_NORMAL);
  1157.                         if ($checkout['billingAddressIsShippingAddress']) {
  1158.                             $guestCustomer->setFirstName($checkout['shippingFirstName']);
  1159.                             $guestCustomer->setLastName($checkout['shippingLastName']);
  1160.                         } else {
  1161.                             $guestCustomer->setFirstName($checkout['billingFirstName']);
  1162.                             $guestCustomer->setLastName($checkout['billingLastName']);
  1163.                         }
  1164.                         $guestCustomer->setBusinessName($checkout['billingBusinessName']);
  1165.                         $guestCustomer->setBusinessId(str_replace([' ', '-'], '', $checkout['billingBusinessId']));
  1166.                         $guestCustomer->setTaxId($checkout['billingTaxId']);
  1167.                         $guestCustomer->setVatId($checkout['billingVatNumber']);
  1168.                         $guestCustomer->setGuest(true);
  1169.                         $salesManager = $domain->getDefaultSalesManager();
  1170.                         if (!is_null($guestCustomer->getBusinessName()) && trim($guestCustomer->getBusinessName()) != ''
  1171.                             && !is_null($guestCustomer->getTaxId()) && trim($guestCustomer->getTaxId()) != '') {
  1172.                             $userRepository = $entityManager->getRepository(User::class);
  1173.                             switch ($guestCustomer->getDomain()->getId()) {
  1174.                                 case Domain::DOMAIN_ID_RT_SK:
  1175.                                 case Domain::DOMAIN_ID_RT_CZ:
  1176.                                     $salesManager = $userRepository->findOneById(User::USER_ID_BEATA_SEDLAROVA);
  1177.                                     break;
  1178.                                 case Domain::DOMAIN_ID_RT_HU:
  1179.                                     $salesManager = $userRepository->findOneById(68);
  1180.                                     break;
  1181.                                 default:
  1182.                                     $salesManager = $userRepository->findOneById(68);
  1183.                             }
  1184.                         }
  1185.                         $guestCustomer->setSalesManager($salesManager);
  1186.                         if ($checkout['newsletter']) {
  1187.                             $guestCustomer->setWantsNewsletter(true);
  1188.                         } else {
  1189.                             $guestCustomer->setWantsNewsletter(false);
  1190.                         }
  1191.                         $guestCustomer->setSource(Customer::SOURCE_SIGN_UP);
  1192.                         $entityManager->persist($guestCustomer);
  1193.                         $entityManager->flush();
  1194.                         $entityManager->refresh($guestCustomer);
  1195.                         // Billing Address
  1196.                         $billingAddress = new CustomerAddress();
  1197.                         $billingAddress->setCustomer($guestCustomer);
  1198.                         $billingAddress->setType(CustomerAddress::AddressType_Billing_Id);
  1199.                         $billingAddress->setTitle($translator->trans('Billing address'));
  1200.                         if ($checkout['billingAddressIsShippingAddress']) {
  1201.                             $billingAddress->setFirstName($checkout['shippingFirstName']);
  1202.                             $billingAddress->setLastName($checkout['shippingLastName']);
  1203.                             $billingAddress->setStreet($checkout['shippingAddress']);
  1204.                             $billingAddress->setZip($checkout['shippingPostalCode']);
  1205.                             $billingAddress->setCity($checkout['shippingCity']);
  1206.                             if ($domain->getId() == Domain::DOMAIN_ID_RT_EU) {
  1207.                                 $billingAddress->setCountry($checkout['shippingCountry']);
  1208.                             } else {
  1209.                                 $billingAddress->setCountry($country);
  1210.                             }
  1211.                         } else {
  1212.                             $billingAddress->setFirstName($checkout['billingFirstName']);
  1213.                             $billingAddress->setLastName($checkout['billingLastName']);
  1214.                             $billingAddress->setStreet($checkout['billingAddress']);
  1215.                             $billingAddress->setZip($checkout['billingPostalCode']);
  1216.                             $billingAddress->setCity($checkout['billingCity']);
  1217.                             if ($domain->getId() == Domain::DOMAIN_ID_RT_EU) {
  1218.                                 $billingAddress->setCountry($checkout['billingCountry']);
  1219.                             } else {
  1220.                                 $billingAddress->setCountry($country);
  1221.                             }
  1222.                         }
  1223.                         // District
  1224.                         $billingAddress->setDistrict(OrderHelper::findDistrict($billingAddress->getZip(), $billingAddress->getCountry(), $request));
  1225.                         $entityManager->persist($billingAddress);
  1226.                         $entityManager->flush();
  1227.                         // Shipping Address
  1228.                         if (!$checkout['billingAddressIsShippingAddress']) {
  1229.                             $shippingAddress = new CustomerAddress();
  1230.                             $shippingAddress->setCustomer($guestCustomer);
  1231.                             $shippingAddress->setType(CustomerAddress::AddressType_Shipping_Id);
  1232.                             $shippingAddress->setTitle($translator->trans('Shipping address'));
  1233.                             $shippingAddress->setFirstName($checkout['shippingFirstName']);
  1234.                             $shippingAddress->setLastName($checkout['shippingLastName']);
  1235.                             $shippingAddress->setStreet($checkout['shippingAddress']);
  1236.                             $shippingAddress->setZip($checkout['shippingPostalCode']);
  1237.                             $shippingAddress->setCity($checkout['shippingCity']);
  1238.                             if ($domain->getId() == Domain::DOMAIN_ID_RT_EU) {
  1239.                                 $shippingAddress->setCountry($checkout['shippingCountry']);
  1240.                             } else {
  1241.                                 $shippingAddress->setCountry($country);
  1242.                             }
  1243.                             $entityManager->persist($shippingAddress);
  1244.                             $entityManager->flush();
  1245.                         }
  1246.                         $entityManager->refresh($guestCustomer);
  1247.                     }
  1248.                     $order->setCustomer($guestCustomer);
  1249.                     // Newsletter Subscription
  1250.                     if ($checkout['newsletter']) {
  1251.                         $emailExists = $entityManager->getRepository(CustomerEmail::class)->findOneBy([
  1252.                             'customer' => $guestCustomer,
  1253.                             'email' => $checkout['email'],
  1254.                         ]);
  1255.                         if (empty($emailExists)) {
  1256.                             $customerEmail = new CustomerEmail();
  1257.                             $customerEmail->setCustomer($guestCustomer);
  1258.                             $customerEmail->setEmail($checkout['email']);
  1259.                             $entityManager->persist($customerEmail);
  1260.                             $entityManager->flush();
  1261.                         }
  1262.                         $connect = $this->getKlaviyoConnect($request);
  1263.                         $klaviyoProfileData = $connect->getProfileWithFilter(['email' => $checkout['email']]);
  1264.                         $klaviyoProfileData = $klaviyoProfileData[array_key_first($klaviyoProfileData)] ?? [];
  1265.                         if (!empty($klaviyoProfileData))
  1266.                         {
  1267.                             $connect->updateProfile($guestCustomer, $klaviyoProfileData);
  1268.                         }
  1269.                     }
  1270.                     $customer = $guestCustomer;
  1271.                 }
  1272.                 $order->setPaymentType($checkout['paymentMethodTypeId']);
  1273.                 $order->setPaymentStatus(Order::PaymentStatus_Pending);
  1274.                 $order->setPaymentPrice(0);
  1275.                 if ($checkout['paymentMethodTypeId'] == PaymentType::Cetelem->value && !is_null($request->request->get('cetelem'))) {
  1276.                     $checkout['cetelem'] = $request->request->get('cetelem');
  1277.                 } elseif ($checkout['paymentMethodTypeId'] == PaymentType::Klarna->value && $request->getSession()->has('klarnaSessionId')) {
  1278.                     $klarnaSessionIdOrderSetting = new OrderSetting();
  1279.                     $klarnaSessionIdOrderSetting->setType(OrderSetting::TYPE_KLARNA_PAYMENT_SESSION_ID);
  1280.                     $klarnaSessionIdOrderSetting->setOrder($order);
  1281.                     $klarnaSessionIdOrderSetting->setValue($request->getSession()->get('klarnaSessionId'));
  1282.                     $entityManager->persist($klarnaSessionIdOrderSetting);
  1283.                     //KLARNA SET SHIPPING
  1284.                     /** @var DomainShippingType $shippingMethod */
  1285.                     $shippingMethod = $entityManager->getRepository(DomainShippingType::class)->findOneById($checkout['shippingMethodId']);
  1286.                     if ($shippingMethod->getType() == DomainShippingType::ShippingType_Carrier_Id && $domain->getId() == Domain::DOMAIN_ID_WS_HU) {
  1287.                         $translationKey = 'shipping.method.type.' . $shippingMethod->getType() . '.achu';
  1288.                     }
  1289.                     else {
  1290.                         $translationKey = 'shipping.method.type.' . $shippingMethod->getType();
  1291.                     }
  1292.                     $icon = '';
  1293.                     if ($translator->trans($translationKey . '.icon') != $translationKey . '.icon') {
  1294.                         $icon = $domain->getUrl() . '/theme/images/' . $translator->trans($translationKey . '.icon');
  1295.                     }
  1296.                     $shippingCountry = $checkout['shippingCountry'] ?? null;
  1297.                     $freeShipping = false;
  1298.                     if (in_array($shippingMethod->getId(), $this->getActiveFreeShippingTypeIds($domain)))
  1299.                     {
  1300.                         $freeShipping = $cart->getBasketItems()->filter(function (BasketItem $basketItem) use ($shippingMethod) {
  1301.                             if (empty($shippingMethod->getFreeShippingProductTypes())){
  1302.                                 return true;
  1303.                             }
  1304.                             if (in_array($basketItem->getProduct()->getType()->getId(), $shippingMethod->getFreeShippingProductTypes())) {
  1305.                                 return true;
  1306.                             }
  1307.                             return false;
  1308.                         });
  1309.                         $freeShipping = $freeShipping->count() > 0;
  1310.                     }
  1311.                     $this->getKlarna($domain->getId(), $request, $shippingCountry)
  1312.                         ->addShipping(
  1313.                             $request->getSession()->get('klarnaSessionId'),
  1314.                             $icon,
  1315.                             $shippingMethod,
  1316.                             $domain,
  1317.                             $checkout,
  1318.                             $freeShipping
  1319.                         );
  1320.                 }
  1321.                 $order->setShippingType($checkout['shippingMethodTypeId']);
  1322.                 if ($order->getShippingType() == DomainShippingType::SHIPPING_TYPE_PACKETA_PICKUP_POINT_ID
  1323.                     && isset($checkout['packetaPickupPointId'])
  1324.                     && (is_numeric($checkout['packetaPickupPointId']) || ($checkout['packetaPickupPointCarrierId'] == Packeta::FOXPOST_CARRIER_ID))) {
  1325.                     $packetaIdOrderSetting = new OrderSetting();
  1326.                     $packetaIdOrderSetting->setType(OrderSetting::TYPE_PACKETA_BRANCH_ID);
  1327.                     $packetaIdOrderSetting->setOrder($order);
  1328.                     $packetaIdOrderSetting->setValue($checkout['packetaPickupPointId']);
  1329.                     $entityManager->persist($packetaIdOrderSetting);
  1330.                 }
  1331.                 if ($order->getShippingType() == DomainShippingType::SHIPPING_TYPE_PACKETA_PICKUP_POINT_ID
  1332.                     && isset($checkout['packetaPickupPointTitle'])
  1333.                     && $checkout['packetaPickupPointTitle'] != '') {
  1334.                     $packetaTitleOrderSetting = new OrderSetting();
  1335.                     $packetaTitleOrderSetting->setType(OrderSetting::TYPE_PACKETA_BRANCH_NAME);
  1336.                     $packetaTitleOrderSetting->setOrder($order);
  1337.                     $packetaTitleOrderSetting->setValue($checkout['packetaPickupPointTitle']);
  1338.                     $entityManager->persist($packetaTitleOrderSetting);
  1339.                 }
  1340.                 if ($order->getShippingType() == DomainShippingType::SHIPPING_TYPE_PACKETA_PICKUP_POINT_ID
  1341.                     && isset($checkout['packetaPickupPointCarrierId'])
  1342.                     && $checkout['packetaPickupPointCarrierId'] != '') {
  1343.                     $packetaTitleOrderSetting = new OrderSetting();
  1344.                     $packetaTitleOrderSetting->setType(OrderSetting::TYPE_PACKETA_CARRIER_ID);
  1345.                     $packetaTitleOrderSetting->setOrder($order);
  1346.                     $packetaTitleOrderSetting->setValue($checkout['packetaPickupPointCarrierId']);
  1347.                     $entityManager->persist($packetaTitleOrderSetting);
  1348.                 }
  1349.                 // Shipping Address
  1350.                 $order->setShippingBusinessName($checkout['shippingBusinessName']);
  1351.                 $order->setShippingFirstName($checkout['shippingFirstName']);
  1352.                 $order->setShippingLastName($checkout['shippingLastName']);
  1353.                 $order->setShippingStreet($checkout['shippingAddress']);
  1354.                 $order->setShippingZip($checkout['shippingPostalCode']);
  1355.                 $order->setShippingCity($checkout['shippingCity']);
  1356.                 if ($domain->getId() == Domain::DOMAIN_ID_RT_EU) {
  1357.                     $order->setShippingCountry($checkout['shippingCountry']);
  1358.                 } else {
  1359.                     $order->setShippingCountry($country);
  1360.                 }
  1361.                 $order->setShippingPhone($checkout['shippingPhoneNumber']);
  1362.                 $order->setShippingEmail($checkout['email']);
  1363.                 // Billing Address
  1364.                 if ($checkout['billingAddressIsShippingAddress']) {
  1365.                     $order->setBillingFirstName($checkout['shippingFirstName']);
  1366.                     $order->setBillingLastName($checkout['shippingLastName']);
  1367.                     $order->setBillingStreet($checkout['shippingAddress']);
  1368.                     $order->setBillingZip($checkout['shippingPostalCode']);
  1369.                     $order->setBillingCity($checkout['shippingCity']);
  1370.                     if ($domain->getId() == Domain::DOMAIN_ID_RT_EU) {
  1371.                         $order->setBillingCountry($checkout['billingCountry']);
  1372.                     } else {
  1373.                         $order->setBillingCountry($country);
  1374.                     }
  1375.                     $order->setUseBillingAddressAsShippingAddress(true);
  1376.                 } else {
  1377.                     $order->setBillingFirstName($checkout['billingFirstName']);
  1378.                     $order->setBillingLastName($checkout['billingLastName']);
  1379.                     $order->setBillingStreet($checkout['billingAddress']);
  1380.                     $order->setBillingZip($checkout['billingPostalCode']);
  1381.                     $order->setBillingCity($checkout['billingCity']);
  1382.                     if ($domain->getId() == Domain::DOMAIN_ID_RT_EU) {
  1383.                         $order->setBillingCountry($checkout['billingCountry']);
  1384.                     } else {
  1385.                         $order->setBillingCountry($country);
  1386.                     }
  1387.                     $order->setUseBillingAddressAsShippingAddress(false);
  1388.                 }
  1389.                 $order->setBillingPhone($checkout['shippingPhoneNumber']);
  1390.                 $order->setBillingEmail($checkout['email']);
  1391.                 // Company
  1392.                 $order->setBillingBusinessName($checkout['billingBusinessName']);
  1393.                 $order->setBillingBusinessId(str_replace([' ', '-'], '', $checkout['billingBusinessId']));
  1394.                 $order->setBillingTaxId($checkout['billingTaxId']);
  1395.                 $order->setBillingVatId($checkout['billingVatNumber']);
  1396.                 if (isset($checkout['3_percent_discount']) && $checkout['3_percent_discount']) {
  1397.                     $order->setDiscount(3);
  1398.                 }
  1399.                 // Message to Seller
  1400.                 $message = $this->remove_emoji($checkout['messageToSeller']);
  1401.                 $order->setMessage($message);
  1402.                 // Save Order
  1403.                 $entityManager->persist($order);
  1404.                 $entityManager->flush();
  1405.                 if (is_null($customer->getCountry())) {
  1406.                     $countryCode = Customer::getCountryCodeByDomainId($domain->getId());
  1407.                     if (is_null($countryCode)) {
  1408.                         $countryCode = $order->getBillingCountry();
  1409.                     }
  1410.                     $customer->setCountry($countryCode);
  1411.                 }
  1412.                 // Add Products
  1413.                 $cart = $this->getCart($request->getSession()->get('cartId'));
  1414.                 if ($cart) {
  1415.                     $position = 1;
  1416.                     // Validate Coupon
  1417.                     if (!empty($checkout['coupon']['code'])) {
  1418.                         $coupon = $entityManager->getRepository(Coupon::class)->findOneBy([
  1419.                             'code' => $checkout['coupon']['code'],
  1420.                             'domain' => $domain,
  1421.                         ]);
  1422.                         if ($coupon) {
  1423.                             // Set Email
  1424.                             if (!empty($checkout['email'])) {
  1425.                                 $cart->setEmail($checkout['email']);
  1426.                             } else {
  1427.                                 $cart->setEmail(null);
  1428.                             }
  1429.                             // Coupon Free Shipping
  1430.                             $isCouponApplicableForFreeShipping = CartHelper::isCouponApplicableForFreeShipping($coupon, $cart, $entityManager);
  1431.                             // Coupon Discount
  1432.                             $isCouponValidForBasket = CartHelper::isCouponValidForBasket($coupon, $cart, $entityManager);
  1433.                             if ($isCouponValidForBasket !== false || $isCouponApplicableForFreeShipping) {
  1434.                                 $checkout['coupon'] = [
  1435.                                     'code' => $coupon->getCode(),
  1436.                                     'type' => $coupon->getDiscountType(),
  1437.                                     'discount' => (float)$isCouponValidForBasket,
  1438.                                     'freeShipping' => $isCouponApplicableForFreeShipping,
  1439.                                 ];
  1440.                             } // Drop Invalid Coupon Code
  1441.                             else {
  1442.                                 unset($checkout['coupon']);
  1443.                             }
  1444.                         } // Drop Invalid Coupon Code
  1445.                         else {
  1446.                             unset($checkout['coupon']);
  1447.                         }
  1448.                     }
  1449.                     // Coupon Code
  1450.                     if (!empty($checkout['coupon']['code']) && ((isset($checkout['coupon']['discount']) && (int)$checkout['coupon']['discount'] >= 0) || in_array($checkout['coupon']['code'], $this->getWhiteListCouponCodes()))) {
  1451.                         $order->setCouponCode($checkout['coupon']['code']);
  1452.                     }
  1453.                     if (isset($checkout['coupon']['discount']) && (float)$checkout['coupon']['discount'] >= 0 && $checkout['coupon']['type'] == Coupon::DISCOUNT_TYPE_PERCENT) {
  1454.                         $coupon = $entityManager->getRepository(Coupon::class)->findOneBy([
  1455.                             'domain' => $domain,
  1456.                             'code' => $checkout['coupon']['code'],
  1457.                             'discountType' => Coupon::DISCOUNT_TYPE_PERCENT,
  1458.                         ]);
  1459.                         if ($coupon) {
  1460.                             $orderSetting = new OrderSetting();
  1461.                             $orderSetting->setOrder($order);
  1462.                             $orderSetting->setType(OrderSetting::TYPE_COUPON_CODE);
  1463.                             $orderSetting->setValue($coupon->getId());
  1464.                             $entityManager->persist($orderSetting);
  1465.                         }
  1466.                     }
  1467.                     // Sub-total for avoid Minus Total
  1468.                     $validateCouponDiscountPrice = 0;
  1469.                     if (isset($checkout['coupon']['discount']) && (float)$checkout['coupon']['discount'] >= 0 && $checkout['coupon']['type'] == Coupon::DISCOUNT_TYPE_PRICE) {
  1470.                         $coupon = $entityManager->getRepository(Coupon::class)->findOneBy([
  1471.                             'domain' => $domain,
  1472.                             'code' => $checkout['coupon']['code'],
  1473.                             'discountType' => Coupon::DISCOUNT_TYPE_PRICE,
  1474.                         ]);
  1475.                         if ($coupon) {
  1476.                             $orderSetting = new OrderSetting();
  1477.                             $orderSetting->setOrder($order);
  1478.                             $orderSetting->setType(OrderSetting::TYPE_COUPON_CODE);
  1479.                             $orderSetting->setValue($coupon->getId());
  1480.                             $entityManager->persist($orderSetting);
  1481.                         }
  1482.                     }
  1483.                     $useZeroVat = $this->useZeroVat($customer, $request);
  1484.                     if ($order->getDomain()->getId() == Domain::DOMAIN_ID_RT_HU) {
  1485.                         $adattorloProduct = $entityManager->getRepository(Product::class)->findOneById(Product::ADATTORLO_PRODUCT_ID);
  1486.                         $adattorloQuantity = 0;
  1487.                         /**
  1488.                          * @var BasketItem $basketItem
  1489.                          */
  1490.                         foreach ($cart->getBasketItems() as $basketItem) {
  1491.                             if (in_array($basketItem->getProduct()->getType()->getId(), [ProductType::PRODUCT_TYPE_ID_PC, ProductType::PRODUCT_TYPE_ID_NOTEBOOK, ProductType::PRODUCT_TYPE_ID_TABLET, ProductType::PRODUCT_TYPE_ID_SMARTPHONE])) {
  1492.                                 $adattorloQuantity += $basketItem->getQuantity();
  1493.                             }
  1494.                         }
  1495.                         if ($adattorloQuantity > 0) {
  1496.                             $adattorloBasketItem = new BasketItem();
  1497.                             $adattorloBasketItem->setBasket($cart);
  1498.                             $adattorloBasketItem->setProduct($adattorloProduct);
  1499.                             $adattorloBasketItem->setQuantity($adattorloQuantity);
  1500.                             $cart->addBasketItem($adattorloBasketItem);
  1501.                             $cart->setUpdated(new \DateTime());
  1502.                             $entityManager->persist($cart);
  1503.                             $entityManager->flush();
  1504.                         }
  1505.                     }
  1506.                     $freeEsetProductItemCount = 0;
  1507.                     /**
  1508.                      * @var BasketItem $item
  1509.                      */
  1510.                     foreach ($cart->getBasketItems() as $item) {
  1511.                         $product = $item->getProduct();
  1512.                         if ($product) {
  1513.                             $orderItem = new OrderItem();
  1514.                             $orderItem->setProduct($product);
  1515.                             if (
  1516.                                 in_array($order->getDomain()->getId(), [Domain::DOMAIN_ID_RT_SK, Domain::DOMAIN_ID_RT_CZ, Domain::DOMAIN_ID_RT_HU]) &&
  1517.                                 $request->request->has('eset-90-day-free') &&
  1518.                                 $entityManager->getRepository(Product::class)->isFreeEsetCompatible($product)
  1519.                             ) {
  1520.                                 $freeEsetProductItemCount += $item->getQuantity();
  1521.                             }
  1522.                             $productMeta = $product->getDomainMeta($domain);
  1523.                             if ($useZeroVat) {
  1524.                                 $domainPrice = $productMeta->isDiscounted()
  1525.                                     ? $productMeta->getDomainDiscount()
  1526.                                     : $productMeta->getDomainPrice();
  1527.                             } else {
  1528.                                 if (isset($customer) && $customer->getId() == Customer::MAXMEDIA_KFT_ID) {
  1529.                                     $domainPrice = $productMeta->isDiscounted()
  1530.                                         ? $domain->createVatPrice($productMeta->getDomainDiscount(), 1.27)
  1531.                                         : $domain->createVatPrice($productMeta->getDomainPrice(), 1.27);
  1532.                                 } else {
  1533.                                     $domainPrice = $productMeta->isDiscounted()
  1534.                                         ? $productMeta->getDomainVatDiscount()
  1535.                                         : $productMeta->getDomainVatPrice();
  1536.                                 }
  1537.                             }
  1538.                             $isTimedSale = $productMeta->isTimedSaleActive(true);
  1539.                             $orderItem->setFromTimedSale($isTimedSale);
  1540.                             if (!is_null($order->getDiscount()) && $order->getDiscount() > 0) {
  1541.                                 $domainPrice = $this->calculateDiscountedPrice($domainPrice, $order->getDiscount(), $domain->getLanguage()->getCode());
  1542.                             }
  1543.                             $orderItem->setPrice($domainPrice);
  1544.                             $productPrice = $domainPrice;
  1545.                             $orderItem->setQuantity($item->getQuantity());
  1546.                             $orderItem->setPosition($position);
  1547.                             $orderItem->setOrder($order);
  1548.                             // Save Order Product
  1549.                             $entityManager->persist($orderItem);
  1550.                             $entityManager->flush();
  1551.                             if ($product->isContainer()) {
  1552.                                 foreach ($product->getProductContainers() as $container) {
  1553.                                     $position++;
  1554.                                     $containerMeta = $container->getDomainMeta($domain);
  1555.                                     if ($useZeroVat) {
  1556.                                         $containerOrderItemPrice = $productMeta->isDiscounted() ? $containerMeta->getDomainDiscount() : $containerMeta->getDomainPrice();
  1557.                                     } else {
  1558.                                         if (isset($customer) && $customer->getId() == Customer::MAXMEDIA_KFT_ID) {
  1559.                                             $containerOrderItemPrice = $productMeta->isDiscounted()
  1560.                                                 ? $domain->createVatPrice($containerMeta->getDomainDiscount(), 1.27)
  1561.                                                 : $domain->createVatPrice($containerMeta->getDomainPrice(), 1.27);
  1562.                                         } else {
  1563.                                             $containerOrderItemPrice = $productMeta->isDiscounted()
  1564.                                                 ? $containerMeta->getDomainVatDiscount()
  1565.                                                 : $containerMeta->getDomainVatPrice();
  1566.                                         }
  1567.                                     }
  1568.                                     if (!is_null($order->getDiscount()) && $order->getDiscount() > 0) {
  1569.                                         $containerOrderItemPrice = $this->calculateDiscountedPrice($containerOrderItemPrice, $order->getDiscount(), $domain->getLanguage()->getCode());
  1570.                                     }
  1571.                                     $containerOrderItem = new OrderItem();
  1572.                                     $childProduct = null;
  1573.                                     if (!is_null($container->getChild())) {
  1574.                                         $childProduct = $container->getChild();
  1575.                                     } elseif (!is_null($container->getProductTag())) {
  1576.                                         $childProduct = $entityManager->getRepository(Product::class)->getAvailableProductByProductTag($container->getProductTag());
  1577.                                     }
  1578.                                     if (!$childProduct) {
  1579.                                         continue;
  1580.                                     }
  1581.                                     $containerOrderItem->setOrder($order);
  1582.                                     $containerOrderItem->setProductContainer($container);
  1583.                                     $containerOrderItem->setProduct($childProduct);
  1584.                                     $containerOrderItem->setParent($orderItem);
  1585.                                     $containerOrderItem->setQuantity($container->getMultiplier());
  1586.                                     $containerOrderItem->setPosition($position);
  1587.                                     $containerOrderItem->setPrice($containerOrderItemPrice);
  1588.                                     $entityManager->persist($containerOrderItem);
  1589.                                 }
  1590.                                 $entityManager->flush();
  1591.                             }
  1592.                             // Cross-sell Attribute Options
  1593.                             $crossSellAttributeOptions = CartHelper::getCrossSellAttributeOptionsByProductTypeId($product->getType()->getId(), $domain->getId());
  1594.                             $optionPrice = 0;
  1595.                             // Add Product Attributes
  1596.                             if ($item->getItemAttributes() != null) {
  1597.                                 /**
  1598.                                  * @var $attribute BasketItemAttributeOption
  1599.                                  */
  1600.                                 foreach ($item->getItemAttributes() as $attribute) {
  1601.                                     $option = $attribute->getAttributeOption();
  1602.                                     if ($option && !in_array($option->getId(), $this->unWantedAttributes)) {
  1603.                                         $optionMeta = $option->getDomainMeta($domain);
  1604.                                         if ($optionMeta) {
  1605.                                             $orderItemAttribute = new OrderItemAttributeOption();
  1606.                                             if ($useZeroVat) {
  1607.                                                 $optionDomainPrice = $optionMeta->isDiscounted() ? $optionMeta->getDomainDiscount() : $optionMeta->getDomainPrice();
  1608.                                             } else {
  1609.                                                 if (isset($customer) && $customer->getId() == Customer::MAXMEDIA_KFT_ID) {
  1610.                                                     $optionDomainPrice = $optionMeta->isDiscounted()
  1611.                                                         ? $domain->createVatPrice($optionMeta->getDomainDiscount(), 1.27)
  1612.                                                         : $domain->createVatPrice($optionMeta->getDomainPrice(), 1.27);
  1613.                                                 } else {
  1614.                                                     $optionDomainPrice = $optionMeta->isDiscounted()
  1615.                                                         ? $optionMeta->getDomainVatDiscount()
  1616.                                                         : $optionMeta->getDomainVatPrice();
  1617.                                                 }
  1618.                                             }
  1619.                                             // Cross-sell Attribute Options Calculated Price
  1620.                                             if (isset($crossSellAttributeOptions[$option->getId()])) {
  1621.                                                 if (isset($crossSellAttributeOptions[$option->getId()]['percentPrice'])) {
  1622.                                                     $optionDomainPrice = $domain->createVatPrice((($item->getPriceWithAttributesForDomainWithException($domain, $option) * $crossSellAttributeOptions[$option->getId()]['percentPrice']) / 100), 1.);
  1623.                                                 }
  1624.                                             }
  1625.                                             if (!is_null($order->getDiscount()) && $order->getDiscount() > 0) {
  1626.                                                 $optionDomainPrice = $this->calculateDiscountedPrice($optionDomainPrice, $order->getDiscount(), $domain->getLanguage()->getCode());
  1627.                                             }
  1628.                                             $orderItemAttribute->setPrice($optionDomainPrice);
  1629.                                             $optionPrice += $optionDomainPrice;
  1630.                                             $orderItemAttribute->setAttributeOption($option);
  1631.                                             $orderItemAttribute->setOrderItem($orderItem);
  1632.                                             $entityManager->persist($orderItemAttribute);
  1633.                                             if ($option->getAttribute()->getId() == Attribute::ATTRIBUTE_ID_NEW_BATTERY) {
  1634.                                                 $orderComment = new OrderComment();
  1635.                                                 $orderComment->setOrder($order);
  1636.                                                 $orderComment->setText("aksi belemegy\na notiba 100%\nfoto");
  1637.                                                 $orderComment->setType(OrderComment::TYPE_FOR_INSTALLATION);
  1638.                                                 $entityManager->persist($orderComment);
  1639.                                                 $newBatAtt = $entityManager->getRepository(AttributeOption::class)->find(AttributeOption::ATTRIBUTE_OPTION_ID_NEW_BATTERY);
  1640.                                                 $notAddedYet = true;
  1641.                                                 $connectedProducts = $product->getProductModel()->getConnectedProducts();
  1642.                                                 /** @var Product $connectedProduct */
  1643.                                                 foreach ($connectedProducts as $connectedProduct) {
  1644.                                                     if ($connectedProduct->getType()->getId() == ProductType::PRODUCT_TYPE_ID_NOTEBOOK_BATTERY) {
  1645.                                                         if (!$connectedProduct->isAvailable()) {
  1646.                                                             continue;
  1647.                                                         }
  1648.                                                         if (str_contains(strtolower($connectedProduct->getName()), 'used')) {
  1649.                                                             continue;
  1650.                                                         }
  1651.                                                         $batteryAtrOpt = $entityManager->getRepository(AttributeOption::class)->findOneBy(['product' => $connectedProduct->getId()]);
  1652.                                                         if (!$batteryAtrOpt) {
  1653.                                                             $batteryAtrOpt = new AttributeOption();
  1654.                                                             $batteryAtrOpt->setProduct($connectedProduct);
  1655.                                                             $batteryAtrOpt->setParent($newBatAtt);
  1656.                                                             $batteryAtrOpt->setAttribute($entityManager->getRepository(Attribute::class)->find(Attribute::ATTRIBUTE_ID_BATTERY));
  1657.                                                             $batteryAtrOpt->setSortIndex(999);
  1658.                                                             $batteryAtrOpt->setTitle($connectedProduct->getName());
  1659.                                                             $batteryAtrOpt->setLongTitle($connectedProduct->getLongName());
  1660.                                                             $batteryAtrOpt->setPrivate(false);
  1661.                                                             $batteryAtrOpt->setCreatedBy($this->getEntityManager()->getRepository(User::class)->find(User::CENTRALIS_USER_ID));
  1662.                                                             $entityManager->persist($batteryAtrOpt);
  1663.                                                         }
  1664.                                                         $batteryAttribute = new OrderItemAttributeOption();
  1665.                                                         $batteryAttribute->setOrderItem($orderItem);
  1666.                                                         $batteryAttribute->setPrice(0);
  1667.                                                         $batteryAttribute->setAttributeOption($batteryAtrOpt);
  1668.                                                         $orderItem->addItemAttribute($batteryAttribute);
  1669.                                                         $entityManager->persist($batteryAttribute);
  1670.                                                         $notAddedYet = false;
  1671.                                                         break;
  1672.                                                     }
  1673.                                                 }
  1674.                                                 if ($notAddedYet) {
  1675.                                                     foreach ($connectedProducts as $connectedProduct) {
  1676.                                                         if ($connectedProduct->getType()->getId() == ProductType::PRODUCT_TYPE_ID_NOTEBOOK_BATTERY) {
  1677.                                                             if (str_contains(strtolower($connectedProduct->getName()), 'used')) {
  1678.                                                                 continue;
  1679.                                                             }
  1680.                                                             $batteryAtrOpt = $entityManager->getRepository(AttributeOption::class)->findOneBy(['product' => $connectedProduct->getId()]);
  1681.                                                             if (!$batteryAtrOpt) {
  1682.                                                                 $batteryAtrOpt = new AttributeOption();
  1683.                                                                 $batteryAtrOpt->setProduct($connectedProduct);
  1684.                                                                 $batteryAtrOpt->setParent($newBatAtt);
  1685.                                                                 $batteryAtrOpt->setAttribute($entityManager->getRepository(Attribute::class)->find(Attribute::ATTRIBUTE_ID_BATTERY));
  1686.                                                                 $batteryAtrOpt->setSortIndex(999);
  1687.                                                                 $batteryAtrOpt->setTitle($connectedProduct->getName());
  1688.                                                                 $batteryAtrOpt->setLongTitle($connectedProduct->getLongName());
  1689.                                                                 $batteryAtrOpt->setPrivate(false);
  1690.                                                                 $batteryAtrOpt->setCreatedBy($this->getEntityManager()->getRepository(User::class)->find(User::CENTRALIS_USER_ID));
  1691.                                                                 $entityManager->persist($batteryAtrOpt);
  1692.                                                             }
  1693.                                                             $batteryAttribute = new OrderItemAttributeOption();
  1694.                                                             $batteryAttribute->setOrderItem($orderItem);
  1695.                                                             $batteryAttribute->setPrice(0);
  1696.                                                             $batteryAttribute->setAttributeOption($batteryAtrOpt);
  1697.                                                             $orderItem->addItemAttribute($batteryAttribute);
  1698.                                                             $entityManager->persist($batteryAttribute);
  1699.                                                             break;
  1700.                                                         }
  1701.                                                     }
  1702.                                                 }
  1703.                                             }
  1704.                                         }
  1705.                                     }
  1706.                                 }
  1707.                             }
  1708.                             $adapterAdded = false;
  1709.                             foreach ($product->getProductAttributes() as $productAttribute) {
  1710.                                 if ($productAttribute->isAlways()) {
  1711.                                     $attributeOption = $productAttribute->getOption();
  1712.                                     if ($domain->getId() == Domain::DOMAIN_ID_WS_EU && $attributeOption->getId() == 1194) { // No cables for WS EU
  1713.                                         continue;
  1714.                                     }
  1715.                                     if ($attributeOption->getAttribute()->getId() == 150 && ($adapterAdded || ($attributeOption->getProduct() && $attributeOption->getProduct()->getAvailable() < 1))) {
  1716.                                         continue;
  1717.                                     } else {
  1718.                                         $adapterAdded = true;
  1719.                                     }
  1720.                                     $orderItemAttribute = new OrderItemAttributeOption();
  1721.                                     $orderItemAttribute->setOrderItem($orderItem);
  1722.                                     $orderItemAttribute->setAttributeOption($attributeOption);
  1723.                                     $orderItemAttribute->setPrice(0);
  1724.                                     $entityManager->persist($orderItemAttribute);
  1725.                                 }
  1726.                             }
  1727.                             $entityManager->flush();
  1728.                             $entityManager->refresh($orderItem);
  1729.                             $validateCouponDiscountPrice += ($productPrice + $optionPrice) * $item->getQuantity();
  1730.                             $position++;
  1731.                         }
  1732.                     }
  1733.                     if ($freeEsetProductItemCount > 0) {
  1734.                         $antiVirusProductId = $domain->getId() == Domain::DOMAIN_ID_RT_SK ? Product::ESET_NOD32_90_DAY_TRIAL_PRODUCT_ID : Product::GDATA_90_DAY_TRIAL_PRODUCT_ID;
  1735.                         $product = $this->getEntityManager()->getRepository(Product::class)->findOneById($antiVirusProductId);
  1736.                         $orderItem = new OrderItem();
  1737.                         $orderItem->setProduct($product);
  1738.                         $orderItem->setPrice(0);
  1739.                         $orderItem->setQuantity($freeEsetProductItemCount);
  1740.                         $orderItem->setPosition($position);
  1741.                         $orderItem->setOrder($order);
  1742.                         // Save Order Product
  1743.                         $entityManager->persist($orderItem);
  1744.                         $entityManager->flush();
  1745.                         $position++;
  1746.                     }
  1747.                     if (!empty($orderSummary['cashOnDeliveryProductItem']) && isset($orderSummary['cashOnDeliveryProductItem']['price']) && $orderSummary['cashOnDeliveryProductItem']['price'] != 0) {
  1748.                         $product = $entityManager->getRepository(Product::class)->findOneById(Product::CASH_ON_DELIVERY_PRODUCT_ID);
  1749.                         $orderItem = new OrderItem();
  1750.                         $orderItem->setProduct($product);
  1751.                         $orderItem->setPrice($orderSummary['cashOnDeliveryProductItem']['price']);
  1752.                         $orderItem->setQuantity(1);
  1753.                         $orderItem->setPosition($position);
  1754.                         $orderItem->setOrder($order);
  1755.                         // Save Order Product
  1756.                         $entityManager->persist($orderItem);
  1757.                         $entityManager->flush();
  1758.                         $position++;
  1759.                     }
  1760.                     if ($order->getShippingType() == DomainShippingType::SHIPPING_TYPE_MPL_ID) {
  1761.                         $product = $entityManager->getRepository(Product::class)->findOneById(Product::MPL_PACKAGE_FEE_PRODUCT_ID);
  1762.                         $orderItem = new OrderItem();
  1763.                         $orderItem->setProduct($product);
  1764.                         $orderItem->setPrice($orderSummary['packageFee']['price']);
  1765.                         $orderItem->setQuantity(1);
  1766.                         $orderItem->setPosition($position);
  1767.                         $orderItem->setOrder($order);
  1768.                         // Save Order Product
  1769.                         $entityManager->persist($orderItem);
  1770.                         $entityManager->flush();
  1771.                         $position++;
  1772.                     }
  1773.                     if (isset($checkout['coupon']['discount'])) {
  1774.                         // Avoid Minus Total
  1775.                         $couponDiscountPrice = $checkout['coupon']['discount'];
  1776.                         $couponOrderItem = new OrderItem();
  1777.                         $couponProduct = $entityManager->getRepository(Product::class)->findOneById(Coupon::COUPON_PRODUCT_ID);
  1778.                         $discountPrice = '-' . $couponDiscountPrice;
  1779.                         $couponOrderItem->setOrder($order);
  1780.                         $couponOrderItem->setQuantity(1);
  1781.                         $couponOrderItem->setProduct($couponProduct);
  1782.                         $couponOrderItem->setPrice($discountPrice);
  1783.                         $couponOrderItem->setFromTimedSale(false);
  1784.                         $couponOrderItem->setPosition($position);
  1785.                         $entityManager->persist($couponOrderItem);
  1786.                     }
  1787.                 }
  1788.                 // Order Setting - Pickup Point
  1789.                 if ((int)$checkout['shippingMethodPickupPointId'] > 0) {
  1790.                     $orderSetting = new OrderSetting();
  1791.                     $orderSetting->setOrder($order);
  1792.                     $orderSetting->setType(OrderSetting::TYPE_PICKUP_POINT_ID);
  1793.                     $orderSetting->setValue($checkout['shippingMethodPickupPointId']);
  1794.                     $entityManager->persist($orderSetting);
  1795.                 }
  1796.                 $selectedStockItems = $request->getSession()->get('stockItemCodes') ?? false;
  1797.                 if ($selectedStockItems) {
  1798.                     $orderCommentStockItems = new OrderComment();
  1799.                     $orderCommentStockItems->setOrder($order);
  1800.                     $orderCommentStockItems->setCreatedBy($this->getCentralisUser());
  1801.                     $orderCommentStockItems->setType(OrderComment::TYPE_FOR_PREPARATION);
  1802.                     $stockItemCodes = StockItem::PREFIX_FOR_SELECTED_ITEMS;
  1803.                     foreach ($selectedStockItems as $product) {
  1804.                         foreach ($product as $key => $stockItemId) {
  1805.                             $stockItemCodes .= $stockItemId . ';';
  1806.                         }
  1807.                     }
  1808.                     $orderCommentStockItems->setText($stockItemCodes);
  1809.                     $entityManager->persist($orderCommentStockItems);
  1810.                 }
  1811.                 $entityManager->flush();
  1812.                 // Refresh Order
  1813.                 $entityManager->refresh($order);
  1814.                 /**
  1815.                  * @var DomainShippingType $domainShippingType
  1816.                  */
  1817.                 $domainShippingType = $entityManager->getRepository(DomainShippingType::class)->findOneBy([
  1818.                     'domain' => $domain,
  1819.                     'type' => $order->getShippingType(),
  1820.                 ]);
  1821.                 if ($domainShippingType) {
  1822.                     $domainShippingPrice = CartHelper::hasMainProductType($cart) ? 0 : $domainShippingType->getPrice();
  1823.                     // Shipping Cost
  1824.                     $order->setShippingPrice($domainShippingPrice);
  1825.                     // Free Shipping
  1826.                     if (($domainShippingType->getFreeShipLimit() > 0 && $order->getSubTotal() > $domainShippingType->getFreeShipLimit())) {
  1827.                         $order->setShippingPrice(0);
  1828.                         $order->setForceFreeShipping(true);
  1829.                     }
  1830.                 } else {
  1831.                     $order->setShippingPrice(0);
  1832.                 }
  1833.                 // Coupon Free Shipping
  1834.                 if (isset($checkout['coupon']['freeShipping']) && $checkout['coupon']['freeShipping'] === true) {
  1835.                     $order->setShippingPrice(0);
  1836.                     $order->setForceFreeShipping(true);
  1837.                 }
  1838.                 if (in_array($order->getShippingType(), $orderSummary['enableFreeShipping'])) {
  1839.                     $order->setShippingPrice(0);
  1840.                 }
  1841.                 // Update Full Price
  1842.                 $order->setFullPrice();
  1843.                 // Update customer all order price and quantity
  1844.                 $order->getCustomer()->updateAllOrderPriceAndQuantity();
  1845.                 // Add WAITING changelog
  1846.                 $orderChangelog = new OrderChangelog();
  1847.                 $orderChangelog->setOrderId($order->getId());
  1848.                 $orderChangelog->setStatus(Order::STATUS_TRIAGE);
  1849.                 $orderChangelog->setCreatedBy($this->getCentralisUser()->getId());
  1850.                 $statisticsEntityManager->persist($orderChangelog);
  1851.                 // Remove basket after successful order creation
  1852.                 $entityManager->remove($cart);
  1853.                 $entityManager->flush();
  1854.                 $statisticsEntityManager->flush();
  1855.                 // Full Price will be set on success page
  1856.                 $checkout['orderId'] = $order->getId();
  1857.                 if (!is_null($request->request->get('heureka-checkbox')) && $request->request->get('heureka-checkbox') == '1') {
  1858.                     $checkout['heureka-form'] = 1;
  1859.                 }
  1860.                 $request->getSession()->set('checkout', $checkout);
  1861.                 $this->getKlaviyoConnect($request)->createFinishedOrderEvent($order);
  1862.                 if (in_array($checkout['paymentMethodTypeId'], PaymentType::getBnplPaymentTypeIds())) {
  1863.                     $this->getKlaviyoConnect($request)->createBnplSelectedEvent($order, PaymentType::from($checkout['paymentMethodTypeId']));
  1864.                 }
  1865.                 return $this->redirectToRoute('checkout_success');
  1866.             }
  1867.             $data['form'] = $form->createView();
  1868.             // Checkout data
  1869.             $data['checkout'] = $checkout;
  1870.             // Order Summary
  1871.             $data['orderSummary'] = $orderSummary;
  1872.             $data['legal_links'] = $this->getLegalLinks($request, $cart->getDomain()->getId());
  1873.             $data['header'] = $this->getHeader($request);
  1874.             $data['footer'] = $this->getFooter($request);
  1875.             $data['contentBottom'] = $this->getContentBottom($request);
  1876.             $data['stepsOptions'] = $this->checkoutSteps(5);
  1877.             $data['cetelem_hu_shop_id'] = $this->getParameter('cetelem_hu_shop_id');
  1878.             $data['cetelem_hu_url'] = $this->getParameter('cetelem_hu_url');
  1879.             $data['cetelem_hu_barem_code'] = $this->getParameter('cetelem_hu_barem_code');
  1880.             $data['cetelem_hu_price_minimum'] = $this->getParameter('cetelem_hu_price_minimum');
  1881.             return $this->render('AtechNetCoreBundle/Checkout/review.html.twig', $data);
  1882.         }
  1883.         return $this->redirectToRoute('cart_show');
  1884.     }
  1885.     /**
  1886.      * @Route("/checkout/success", name="checkout_success", defaults={"_locale":""})
  1887.      * @Route("/{_locale<%supported_locales%>?}/checkout/success", name="checkout_success_locale", defaults={"_locale":""})
  1888.      * @param Request $request
  1889.      * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
  1890.      * @throws \Exception
  1891.      */
  1892.     public function successAction(Request $request)
  1893.     {
  1894.         $data = [];
  1895.         $data['hideChat'] = true;
  1896.         // Checkout DATA
  1897.         if ($request->getSession()->has('checkout')) {
  1898.             $checkout = $request->getSession()->get('checkout');
  1899.         } else {
  1900.             $checkout = [];
  1901.         }
  1902.         if (isset($checkout['orderId']) && (int)$checkout['orderId'] > 0) {
  1903.             $entityManager = $this->getEntityManager();
  1904.             $multiStore = $this->getMultiStoreHelper($request);
  1905.             $productHelper = $this->getProductHelper($request);
  1906.             $translator = $this->getDatabaseTranslator($request);
  1907.             $domainId = $multiStore->getDomainId();
  1908.             $order = $entityManager->getRepository(Order::class)->findOneById($checkout['orderId']);
  1909.             if ($order) {
  1910.                 $domain = $order->getDomain();
  1911.                 $orderHelper = $this->getOrderHelper($request);
  1912.                 if ($this->getEnvironment() == 'prod') {
  1913.                     $emailSendingResult = $orderHelper->sendOrderEmail(
  1914.                         $order,
  1915.                         $productHelper,
  1916.                         $this->getContactInfos(),
  1917.                         $this->getWhiteListCouponCodes(),
  1918.                         true
  1919.                     );
  1920.                     //for testing the email
  1921.                     //you need to enable this part in OrderHelper return $emailData;
  1922.                     /*return $this->render('AtechNetCoreBundle/Email/order.html.twig', $emailSendingResult);*/
  1923.                     // Marketing
  1924.                     $data['marketingProducts'] = $emailSendingResult ? $emailSendingResult['marketingProducts'] : '';
  1925.                     $data['marketingProductsGA4'] = $emailSendingResult ? $emailSendingResult['marketingProductsGA4'] : '';
  1926.                 }
  1927.                 if (
  1928.                     $this->getEnvironment() == 'prod' &&
  1929.                     in_array($domain->getId(), [Domain::DOMAIN_ID_RT_SK, Domain::DOMAIN_ID_RT_CZ]) &&
  1930.                     isset($checkout['heureka-form']) && $checkout['heureka-form'] == 1
  1931.                 ) {
  1932.                     $heureka = new Heureka($this->getTwig());
  1933.                     $heureka->sendOrderInfo($order);
  1934.                 }
  1935.                 $data['orderId'] = $order->getId();
  1936.                 $data['email'] = $order->getBillingEmail();
  1937.                 $data['domainName'] = $domain->getName();
  1938.                 $data['orderTotal'] = $order->getFullPrice();
  1939.                 $data['orderTax'] = round($order->getTaxOutOfFullPrice(), 2);
  1940.                 switch ($domain->getCurrency()) {
  1941.                     case 'Ft':
  1942.                         $data['currencyCode'] = 'HUF';
  1943.                         break;
  1944.                     case 'Kč':
  1945.                         $data['currencyCode'] = 'CZK';
  1946.                         break;
  1947.                     case '€':
  1948.                         $data['currencyCode'] = 'EUR';
  1949.                         break;
  1950.                     default:
  1951.                         $data['currencyCode'] = 'EUR';
  1952.                 }
  1953.                 $data['orderShipping'] = $order->getShippingPrice();
  1954.                 $data['payAtDelivery'] = false;
  1955.                 $data['gopay_data'] = null;
  1956.                 $data['simplepay_data'] = null;
  1957.                 $data['klarna_data'] = null;
  1958.                 $notebookCount = 0;
  1959.                 $upgradableNotebookCount = 0;
  1960.                 $upgradablePcCount = 0;
  1961.                 $pcCount = 0;
  1962.                 $monitorCount = 0;
  1963.                 $checkForAddedRamAccessories = false;
  1964.                 $oldPrice = 0;
  1965.                 $newPrice = 0;
  1966.                 $trustPilotData = [
  1967.                     'skuList' => [],
  1968.                     'products' => [],
  1969.                 ];
  1970.                 /**
  1971.                  * @var OrderItem $oi
  1972.                  * @var OrderItemAttributeOption $oia
  1973.                  * @var Product $product
  1974.                  */
  1975.                 foreach ($order->getOrderItems() as $oi) {
  1976.                     $product = $oi->getProduct();
  1977.                     if (
  1978.                         in_array($domainId, [Domain::DOMAIN_ID_RT_HU, Domain::DOMAIN_ID_WS_HU]) &&
  1979.                         in_array($order->getBillingEmail(), ['roland.toth@furbify.eu', 'sandor.lakatos@furbify.eu']) // for testing
  1980.                     ) {
  1981.                         $productPhotoList = $product->getAlbum()->getPhotos();
  1982.                         $productPhoto = $productPhotoList->count() > 0 ? $productPhotoList->first() : false;
  1983.                         $productImage = $productPhoto ? $this->getImage($productPhoto, 'product/' . $product->getCode())->resize(Image::PRODUCT_LIST_THUMB_WIDTH, Image::PRODUCT_LIST_THUMB_HEIGHT) : '';
  1984.                         $trustPilotData['products'][] = [
  1985.                             'sku' => $oi->getProduct()->getCode(),
  1986.                             'productUrl' => $this->url($request)->link('product', [
  1987.                                 'product_id' => $oi->getProduct()->getId(), 
  1988.                                 'isBazaar'   => $oi->getProduct()->isBazaar()
  1989.                             ]),
  1990.                             'imageUrl' => $productImage,
  1991.                             'name' => $product->getFullTitle(),
  1992.                         ];
  1993.                         $trustPilotData['skuList'][] = $product->getCode();
  1994.                     }
  1995.                     switch ($product->getType()->getId()) {
  1996.                         case 52: // Notebook
  1997.                             $checkForAddedRamAccessories = false;
  1998.                             foreach ($oi->getItemAttributes() as $oia) {
  1999.                                 if (in_array($oia->getAttributeOption()->getAttribute()->getId(), [29, 31, 153])) {
  2000.                                     $checkForAddedRamAccessories = true;
  2001.                                 }
  2002.                             }
  2003.                             $isChromeBook = in_array('Chromebook', $product->getBadges());
  2004.                             foreach ($product->getSpecificationAttributeOptions() as $ao) {
  2005.                                 $attribute = $ao->getAttribute();
  2006.                                 if ($attribute->getId() == 4 && in_array($ao->getId(), [100, 937])
  2007.                                     && strpos($product->getName(), 'EliteBook Folio 1040') === false
  2008.                                     && strpos($product->getName(), 'S1 Yoga') === false) {
  2009.                                     $upgradableNotebookCount = $upgradableNotebookCount + $oi->getQuantity();
  2010.                                     switch ($ao->getId()) {
  2011.                                         case 100: // DDR3
  2012.                                             $accesoryId = 421;
  2013.                                             break;
  2014.                                         case 937: // DDR4
  2015.                                             $accesoryId = 1706;
  2016.                                             break;
  2017.                                     }
  2018.                                     $ramAccessory = $entityManager->getRepository(AttributeOption::class)->findOneById($accesoryId);
  2019.                                     $ramAccessoryMeta = $ramAccessory->getDomainMeta($domain);
  2020.                                     $oldPrice = $ramAccessoryMeta->getDomainVatPrice() . ' ' . $domain->getCurrency();
  2021.                                     $newPrice = $domain->createVatPrice($ramAccessoryMeta->getDomainPrice() * 0.9) . ' ' . $domain->getCurrency();
  2022.                                 }
  2023.                             }
  2024.                             $notebookCount = $notebookCount + $oi->getQuantity();
  2025.                             break;
  2026.                         case 60: // PC
  2027.                             $checkForAddedRamAccessories = false;
  2028.                             foreach ($oi->getItemAttributes() as $oia) {
  2029.                                 if (in_array($oia->getAttributeOption()->getAttribute()->getId(), [28, 30, 147])) {
  2030.                                     $checkForAddedRamAccessories = true;
  2031.                                 }
  2032.                             }
  2033.                             foreach ($product->getSpecificationAttributeOptions() as $ao) {
  2034.                                 $attribute = $ao->getAttribute();
  2035.                                 if ($attribute->getId() == 3 && in_array($ao->getId(), [81, 1276])) {
  2036.                                     $upgradablePcCount = $upgradablePcCount + $oi->getQuantity();
  2037.                                     switch ($ao->getId()) {
  2038.                                         case 81: // DDR3
  2039.                                             $accesoryId = 417;
  2040.                                             break;
  2041.                                         case 1276: // DDR4
  2042.                                             $accesoryId = 1521;
  2043.                                             break;
  2044.                                     }
  2045.                                     $ramAccessory = $entityManager->getRepository(AttributeOption::class)->findOneById($accesoryId);
  2046.                                     $ramAccessoryMeta = $ramAccessory->getDomainMeta($domain);
  2047.                                     $oldPrice = $ramAccessoryMeta->getDomainVatPrice() . ' ' . $domain->getCurrency();
  2048.                                     $newPrice = $domain->createVatPrice($ramAccessoryMeta->getDomainPrice() * 0.9) . ' ' . $domain->getCurrency();
  2049.                                 }
  2050.                             }
  2051.                             $pcCount = $pcCount + $oi->getQuantity();
  2052.                             break;
  2053.                         case 44: // Monitor
  2054.                             $monitorCount++;
  2055.                             $cleanerAccessory = $entityManager->getRepository(AttributeOption::class)->findOneById(1766);
  2056.                             $cleanerAccessoryMeta = $cleanerAccessory->getDomainMeta($domain);
  2057.                             $oldPrice = $cleanerAccessoryMeta->getDomainVatPrice() . ' ' . $domain->getCurrency();
  2058.                             $newPrice = $domain->createVatPrice($cleanerAccessoryMeta->getDomainPrice() * 0.9) . ' ' . $domain->getCurrency();
  2059.                             break;
  2060.                     }
  2061.                 }
  2062.                 $data['show_upsell'] = false;
  2063.                 $data['upsell_type'] = 0;
  2064.                 $data['upsell_old_price'] = 0;
  2065.                 $data['upsell_new_price'] = 0;
  2066.                 $data['surveyQuestions'] = [];
  2067.                 // NB RAM UPSELL
  2068.                 if (in_array($domain->getId(), [Domain::DOMAIN_ID_RT_SK, Domain::DOMAIN_ID_RT_HU])) {
  2069.                     if ($upgradableNotebookCount == 1
  2070.                         && $notebookCount == 1
  2071.                         && !$isChromeBook
  2072.                         && $pcCount == 0
  2073.                         && $monitorCount == 0
  2074.                         && !$checkForAddedRamAccessories
  2075.                         && $order->getPaymentType() == PaymentType::CashOnDelivery->value) {
  2076.                         $data['upsell_type'] = 1;
  2077.                         $data['show_upsell'] = true;
  2078.                         $data['upsell_old_price'] = $oldPrice;
  2079.                         $data['upsell_new_price'] = $newPrice;
  2080.                         $upsellOrderSetting = new OrderSetting();
  2081.                         $upsellOrderSetting->setOrder($order);
  2082.                         $upsellOrderSetting->setType(OrderSetting::TYPE_UPSELL_STATS);
  2083.                         $upsellOrderSetting->setValue(OrderSetting::SUB_TYPE_UPSELL_STATS_VIEW);
  2084.                         $entityManager->persist($upsellOrderSetting);
  2085.                         $entityManager->flush();
  2086.                     }
  2087.                     // PC RAM UPSELL
  2088.                     if ($upgradablePcCount == 1
  2089.                         && $notebookCount == 0
  2090.                         && $pcCount == 1
  2091.                         && $monitorCount == 0
  2092.                         && !$checkForAddedRamAccessories
  2093.                         && $order->getPaymentType() == PaymentType::CashOnDelivery->value) {
  2094.                         $data['upsell_type'] = 2;
  2095.                         $data['show_upsell'] = true;
  2096.                         $data['upsell_old_price'] = $oldPrice;
  2097.                         $data['upsell_new_price'] = $newPrice;
  2098.                         $upsellOrderSetting = new OrderSetting();
  2099.                         $upsellOrderSetting->setOrder($order);
  2100.                         $upsellOrderSetting->setType(OrderSetting::TYPE_UPSELL_STATS);
  2101.                         $upsellOrderSetting->setValue(OrderSetting::SUB_TYPE_UPSELL_STATS_VIEW);
  2102.                         $entityManager->persist($upsellOrderSetting);
  2103.                         $entityManager->flush();
  2104.                     }
  2105.                     // MONITOR UPSELL
  2106.                     if ($notebookCount == 0
  2107.                         && $pcCount == 0
  2108.                         && $monitorCount == 1
  2109.                         && $order->getPaymentType() == PaymentType::CashOnDelivery->value
  2110.                         && $domain->getId() == 3) {
  2111.                         $data['upsell_type'] = 3;
  2112.                         $data['show_upsell'] = true;
  2113.                         $data['upsell_old_price'] = $oldPrice;
  2114.                         $data['upsell_new_price'] = $newPrice;
  2115.                         $upsellOrderSetting = new OrderSetting();
  2116.                         $upsellOrderSetting->setOrder($order);
  2117.                         $upsellOrderSetting->setType(OrderSetting::TYPE_UPSELL_STATS);
  2118.                         $upsellOrderSetting->setValue(OrderSetting::SUB_TYPE_UPSELL_STATS_VIEW);
  2119.                         $entityManager->persist($upsellOrderSetting);
  2120.                         $entityManager->flush();
  2121.                     }
  2122.                 }
  2123.                 $data['externalPayment'] = in_array($order->getPaymentType(), $this->extenalCheckPaymentTypes);
  2124.                 /**
  2125.                  * @var Order $order
  2126.                  */
  2127.                 if (in_array($order->getPaymentType(), $this->extenalCheckPaymentTypes)) {
  2128.                     if ($order->getPaymentType() == PaymentType::Quatro->value) {
  2129.                         $callbackUrl = $this->generateUrl('checkout_payment_check', [
  2130.                             'paymentTypeId' => PaymentType::Quatro->value,
  2131.                             'orderId' => $order->getId(),
  2132.                         ], UrlGeneratorInterface::ABSOLUTE_URL);
  2133.                         $quatroPaymentURL = $this->getParameter('quatro_order_url');
  2134.                         $quatroKey = $this->getParameter('quatro_key');
  2135.                         $quatroSubject = '';
  2136.                         foreach ($order->getOrderItems() as $oi) {
  2137.                             if ($quatroSubject != '') {
  2138.                                 $quatroSubject .= ', ';
  2139.                             }
  2140.                             $product = $oi->getProduct();
  2141.                             $quatroSubject .= $product->getType()->getTitle($translator) . ' - ' . $product->getVendor()->getName() . ' - ' . $product->getName();
  2142.                         }
  2143.                         $payload = [
  2144.                             'application' => [
  2145.                                 'orderNumber' => $order->getId(),
  2146.                                 'applicant' => [
  2147.                                     'firstName' => $order->getBillingFirstName(),
  2148.                                     'lastName' => $order->getBillingLastName(),
  2149.                                     'email' => $order->getBillingEmail(),
  2150.                                     'mobile' => $order->getBillingPhone(),
  2151.                                     'permanentAddress' => [
  2152.                                         'addressLine' => $order->getBillingStreet(),
  2153.                                         'city' => $order->getBillingCity(),
  2154.                                         'zipCode' => $order->getBillingZip(),
  2155.                                         'country' => 'SVK',
  2156.                                     ],
  2157.                                 ],
  2158.                                 'subject' => $quatroSubject,
  2159.                                 'totalAmount' => number_format($order->getFullPrice(), 2, '.', ''),
  2160.                                 'callback' => $callbackUrl,
  2161.                             ],
  2162.                             'iat' => time(),
  2163.                         ];
  2164.                         $signatureToken = JWT::encode($payload, base64_decode($quatroKey));
  2165.                         $quatroUrl = $quatroPaymentURL . $signatureToken;
  2166.                         $entityManager->flush();
  2167.                         $data['quatro_url'] = $quatroUrl;
  2168.                     }
  2169.                     if ($order->getPaymentType() == PaymentType::Cetelem->value) {
  2170.                         $domainId = $order->getDomain()->getId();
  2171.                         if ($domainId == 1) { // CETELEM SK - LPC
  2172.                             $cetelemSkId = $this->getParameter('cetelem_sk_id');
  2173.                             $cetelem = $this->getCetelemHelperSK();
  2174.                             $cetelemData = $cetelem->getCalculatorData([
  2175.                                 'kodBaremu' => $checkout['cetelem']['kodBaremu'],
  2176.                                 'kodPoistenia' => $checkout['cetelem']['kodPoistenia'],
  2177.                                 'kodMaterialu' => $checkout['cetelem']['kodMaterialu'],
  2178.                                 'cenaTovaru' => $order->getFullPrice(),
  2179.                                 'priamaPlatba' => $checkout['cetelem']['priamaPlatba'],
  2180.                                 'pocetSplatok' => $checkout['cetelem']['pocetSplatok'],
  2181.                                 'odklad' => $checkout['cetelem']['odklad'],
  2182.                             ]);
  2183.                             $orderedItemTitles = '';
  2184.                             foreach ($order->getOrderItems() as $orderItem) {
  2185.                                 $orderedItemTitles .= $orderedItemTitles == '' ? $orderItem->getProduct()->getName() : ',' . $orderItem->getProduct()->getName();
  2186.                             }
  2187.                             $orderedItemTitles = mb_substr($orderedItemTitles, 0, 30);
  2188.                             $cetelemReturnURL = $this->generateUrl('checkout_payment_check', [
  2189.                                 'paymentTypeId' => PaymentType::Cetelem->value,
  2190.                                 'orderId' => $order->getId(),
  2191.                             ], UrlGeneratorInterface::ABSOLUTE_URL);
  2192.                             $data['cetelem_form'] = $this->renderView('AtechNetCoreBundle/Module/cetelemSubmitFormSK.html.twig', [
  2193.                                 'postUrl' => $cetelem->getPostUrl(),
  2194.                                 'cetelem_sk_id' => $cetelemSkId,
  2195.                                 'cetelem' => $cetelemData,
  2196.                                 'customerId' => $order->getCustomer()->getId(),
  2197.                                 'orderId' => $order->getId(),
  2198.                                 'orderedItemTitles' => $orderedItemTitles,
  2199.                                 'cetelemReturnURL' => $cetelemReturnURL,
  2200.                             ]);
  2201.                         } elseif ($domainId == Domain::DOMAIN_ID_RT_HU) { // CETELEM HU - FPC
  2202.                             $cetelemHuReturnURLs['cbZold'] = $cetelemBaseReturnUrl = $this->generateUrl('checkout_payment_check', [
  2203.                                 'paymentTypeId' => PaymentType::Cetelem->value,
  2204.                                 'orderId' => $order->getId(),
  2205.                                 'gateResponse' => md5($order->getId() . '1'),
  2206.                             ], UrlGeneratorInterface::ABSOLUTE_URL);
  2207.                             $cetelemHuReturnURLs['cbNarancs'] = $cetelemBaseReturnUrl = $this->generateUrl('checkout_payment_check', [
  2208.                                 'paymentTypeId' => PaymentType::Cetelem->value,
  2209.                                 'orderId' => $order->getId(),
  2210.                                 'gateResponse' => md5($order->getId() . '2'),
  2211.                             ], UrlGeneratorInterface::ABSOLUTE_URL);
  2212.                             $cetelemHuReturnURLs['cbPiros'] = $cetelemBaseReturnUrl = $this->generateUrl('checkout_payment_check', [
  2213.                                 'paymentTypeId' => PaymentType::Cetelem->value,
  2214.                                 'orderId' => $order->getId(),
  2215.                                 'gateResponse' => md5($order->getId() . '3'),
  2216.                             ], UrlGeneratorInterface::ABSOLUTE_URL);
  2217.                             $data['cetelem_form'] = $this->renderView('AtechNetCoreBundle/Module/cetelemSubmitFormHU.html.twig', [
  2218.                                 'postUrl' => $this->getParameter('cetelem_hu_url'),
  2219.                                 'shopCode' => $this->getParameter('cetelem_hu_shop_id'),
  2220.                                 'purchaseAmount' => number_format($order->getFullPrice(), 0, '.', ''),
  2221.                                 'orderId' => $order->getId(),
  2222.                                 'cbZold' => $cetelemHuReturnURLs['cbZold'],
  2223.                                 'cbNarancs' => $cetelemHuReturnURLs['cbNarancs'],
  2224.                                 'cbPiros' => $cetelemHuReturnURLs['cbPiros'],
  2225.                             ]);
  2226.                         }
  2227.                     }
  2228.                     if (in_array($order->getPaymentType(), [PaymentType::DebitCard->value, PaymentType::DebitCard3Percent->value])) {
  2229.                         $gopayHelper = $this->getGopayHelper($request);
  2230.                         $data['gopay_data'] = $gopayHelper->getInlineGatewayDataForOrder($order);
  2231.                     }
  2232.                     if ($order->getPaymentType() == PaymentType::Instacash->value) {
  2233.                         $instacash = $this->getInstacash($domain->getLanguage()->getCode());
  2234.                         $redirectUrl = $this->generateUrl(
  2235.                             'checkout_payment_check',
  2236.                             [
  2237.                                 'orderId' => $order->getId(),
  2238.                                 'paymentTypeId' => PaymentType::Instacash->value,
  2239.                             ]
  2240.                         );
  2241.                         $response = $instacash->createApplication($order, $redirectUrl);
  2242.                         $instacashRedirectUrl = $instacash->getRedirectToMerchantUrl($response['publicId']);
  2243.                         $data['instacashRedirectUrl'] = $instacashRedirectUrl;
  2244.                     }
  2245.                     if ($order->getPaymentType() == PaymentType::Milpay->value) {
  2246.                         $milpay = $this->getMilpay($domain->getLanguage()->getCode());
  2247.                         $redirectUrl = $this->generateUrl(
  2248.                             'checkout_payment_check',
  2249.                             [
  2250.                                 'orderId' => $order->getId(),
  2251.                                 'paymentTypeId' => PaymentType::Milpay->value,
  2252.                             ],
  2253.                             UrlGeneratorInterface::ABSOLUTE_URL
  2254.                         );
  2255.                         $response = $milpay->createApplication($order, $redirectUrl);
  2256.                         $app = $milpay->getApplicationStatus($response['applicationId']);
  2257.                         $milpayRedirectUrl = $milpay->getRedirectToMerchantUrl($domain->getLanguage()->getCode(), $response['publicId'], $app['financier']);
  2258.                         $data['milpayRedirectUrl'] = $milpayRedirectUrl;
  2259.                     }
  2260.                     if ($order->getPaymentType() == PaymentType::PastPay->value) {
  2261.                         $pastPay = $this->getPastPay($order->getDomain()->getId());
  2262.                         $redirectUrl = $this->generateUrl('checkout_payment_check', [
  2263.                             'orderId' => $order->getId(),
  2264.                             'paymentTypeId' => PaymentType::PastPay->value,
  2265.                         ]);
  2266.                         $pastPay->setOrder($order);
  2267.                         $pastPay->setDebtorTaxNumber($checkout['billingTaxId']);
  2268.                         $redirectUrl = $pastPay->createOrderAndGetRedirectUrl($redirectUrl);
  2269.                         if (!is_array($redirectUrl)) {
  2270.                             $data['pastPayRedirectUrl'] = $redirectUrl;
  2271.                         }
  2272.                     }
  2273.                     if ($order->getPaymentType() == PaymentType::Klarna->value) {
  2274.                         $klarna = $this->getKlarna($domainId, $request, $order->getShippingCountry());
  2275.                         $redirectUrl = $this->generateUrl('checkout_payment_check', [
  2276.                             'paymentTypeId' => PaymentType::Klarna->value,
  2277.                             'orderId' => $order->getId(),
  2278.                         ]);
  2279.                         $redirectUrl = $klarna->createKlarnaUrl($redirectUrl, $request->getSession()->get('klarnaSessionId'));
  2280.                         $data['klarna_data'] = $redirectUrl['redirect_url'];
  2281.                     }
  2282.                     if ($order->getPaymentType() == PaymentType::PayPal->value) {
  2283.                         $orderItems = [];
  2284.                         /** @var OrderItem $oi */
  2285.                         foreach ($order->getOrderItems() as $oi) {
  2286.                             $orderItems[] = [
  2287.                                 'id'       => $oi->getProduct()->getCode(),
  2288.                                 'quantity' => $oi->getQuantity(),
  2289.                             ];
  2290.                         }
  2291.                         $data['paypal_data'] = [
  2292.                             'items'      => $orderItems,
  2293.                             'totalPrice' => $order->getFullPrice(),
  2294.                             'scriptSrc'  => $this->getPaypal()->getScriptSrc($order),
  2295.                             'currency'   => $order->getDomain()->getCurrencyTextCode(),
  2296.                         ];
  2297.                         if ($order->getPaymentStatus() == Order::PAYMENT_STATUS_PAID) {
  2298.                             $request->getSession()->remove('checkout');
  2299.                             //This will be moved to stock movement creation
  2300.                             #$request->getSession()->remove('stockItemCodes');
  2301.                             $data['paypal_data']['success'] = true;
  2302.                         }
  2303.                     }
  2304.                 } else {
  2305.                     $request->getSession()->remove('checkout');
  2306.                     //This will be moved to stock movement creation
  2307.                     #$request->getSession()->remove('stockItemCodes');
  2308.                     /**
  2309.                      * Success survey
  2310.                      * @var Survey $survey
  2311.                      * @var SurveyQuestion $question
  2312.                      * @var SurveyQuestionOption $questionOption
  2313.                      */
  2314.                     if ($domain->getType() == 'retail') {
  2315.                         switch ($domainId) {
  2316.                             case 1:
  2317.                                 $surveyId = 2;
  2318.                                 break;
  2319.                             case 3:
  2320.                                 $surveyId = 1;
  2321.                                 break;
  2322.                             default:
  2323.                                 $surveyId = 0;
  2324.                         }
  2325.                         $survey = $entityManager->getRepository(Survey::class)->findOneById($surveyId);
  2326.                         if ($survey) {
  2327.                             foreach ($survey->getQuestions() as $question) {
  2328.                                 $options = [];
  2329.                                 if (in_array($question->getType(), [SurveyQuestion::TYPE_OPTIONS, SurveyQuestion::TYPE_CHECKBOXES])) {
  2330.                                     foreach ($question->getOptions() as $questionOption) {
  2331.                                         $options[] = [
  2332.                                             'id' => $questionOption->getId(),
  2333.                                             'text' => $questionOption->getOptionText(),
  2334.                                         ];
  2335.                                     }
  2336.                                 }
  2337.                                 $data['surveyQuestions'][] = [
  2338.                                     'id' => $question->getId(),
  2339.                                     'type' => $question->getType(),
  2340.                                     'text' => $question->getQuestion(),
  2341.                                     'options' => $options,
  2342.                                 ];
  2343.                             }
  2344.                         }
  2345.                     }
  2346.                 }
  2347.                 //-> Google enhanced conversion
  2348.                 $data['customerEmail'] = $order->getBillingEmail();
  2349.                 $data['customerPhone'] = $order->getBillingPhone();
  2350.                 $data['customerFirstName'] = $order->getBillingFirstName();
  2351.                 $data['customerLastName'] = $order->getBillingLastName();
  2352.                 $data['customerStreet'] = $order->getBillingStreet();
  2353.                 $data['customerCity'] = $order->getBillingCity();
  2354.                 $data['customerPostalCode'] = $order->getBillingZip();
  2355.                 $data['customerCountry'] = $order->getBillingCountry();
  2356.                 //<- Google enhanced conversion
  2357.                 $data['trustPilot'] = count($trustPilotData['products']) > 0 ? $trustPilotData : false;
  2358.                 $data['header'] = $this->getHeader($request);
  2359.                 $data['footer'] = $this->getFooter($request);
  2360.                 $data['contentBottom'] = $this->getContentBottom($request);
  2361.                 return $this->render('AtechNetCoreBundle/Checkout/success.html.twig', $data);
  2362.             }
  2363.         } else if ($request->getSession()->get('canceledOrderId')) {
  2364.             $data['header'] = $this->getHeader($request);
  2365.             $data['footer'] = $this->getFooter($request);
  2366.             $data['contentBottom'] = $this->getContentBottom($request);
  2367.             $data['show_upsell'] = false;
  2368.             $data['payAtDelivery'] = false;
  2369.             $data['surveyQuestions'] = [];
  2370.             $data['externalPayment'] = null;
  2371.             $data['canceledOrderId'] = $request->getSession()->get('canceledOrderId');
  2372.             $request->getSession()->remove('canceledOrderId');
  2373.             return $this->render('AtechNetCoreBundle/Checkout/success.html.twig', $data);
  2374.         }
  2375.         return $this->redirectToRoute('cart_show');
  2376.     }
  2377.     /**
  2378.      * @Route("/checkout/payment-check/{orderId}/{paymentTypeId}/{gateResponse}", name="checkout_payment_check", defaults={"_locale":""})
  2379.      * @Route("/{_locale<%supported_locales%>?}/checkout/payment-check/{orderId}/{paymentTypeId}/{gateResponse}", name="checkout_payment_check_locale", defaults={"_locale":""})
  2380.      * @param Request $request
  2381.      * @param int $paymentTypeId
  2382.      * @param int $orderId
  2383.      * @param int|string $gateResponse
  2384.      * @return Response
  2385.      * @throws InvalidArgumentException
  2386.      */
  2387.     public function paymentCheckAction(Request $request, int $paymentTypeId, int $orderId, $gateResponse = 0): Response
  2388.     {
  2389.         $data = [];
  2390.         $data['hideChat'] = true;
  2391.         $entityManager = $this->getEntityManager();
  2392.         if ($request->getSession()->has('checkout')) {
  2393.             $checkout = $request->getSession()->get('checkout');
  2394.         } else {
  2395.             $checkout = [];
  2396.         }
  2397.         if ($request->getSession()->has('paymentOrderId')) {
  2398.             $paymentOrderId = $request->getSession()->get('paymentOrderId');
  2399.         } else {
  2400.             $paymentOrderId = 0;
  2401.         }
  2402.         if ($request->getSession()->has('updateOrderId')) {
  2403.             $updateOrderId = $request->getSession()->get('updateOrderId');
  2404.         } else {
  2405.             $updateOrderId = 0;
  2406.         }
  2407.         $data['header'] = $this->getHeader($request);
  2408.         $data['footer'] = $this->getFooter($request);
  2409.         $data['contentBottom'] = $this->getContentBottom($request);
  2410.         $data['payment_verification_valid'] = false;
  2411.         $data['payment_check_result'] = false;
  2412.         $data['cetelem_hu_check'] = false;
  2413.         $data['cetelem_sk_check'] = false;
  2414.         $data['gopay_check'] = false;
  2415.         $data['simplepay_check'] = false;
  2416.         $data['simplepay_canceled'] = false;
  2417.         $data['simplepay_timeout'] = false;
  2418.         $data['simplepay_transaction_id'] = false;
  2419.         $data['gopay_payment_result_link'] = false;
  2420.         $data['publicOrderLink'] = false;
  2421.         $data['instacash_check'] = false;
  2422.         $data['milpay_check'] = false;
  2423.         $data['pastpay_check'] = false;
  2424.         $data['klarna_check'] = false;
  2425.         $data['klarna_check_result'] = false;
  2426.         $data['orderId'] = 0;
  2427.         if ((isset($checkout['orderId']) && (int)$checkout['orderId'] > 0 && $checkout['orderId'] == $orderId) || ($paymentOrderId == $orderId) || ($updateOrderId == $orderId)) {
  2428.             $data['payment_verification_valid'] = true;
  2429.             /**
  2430.              * @var Order $order
  2431.              */
  2432.             if (in_array($paymentTypeId, $this->extenalCheckPaymentTypes)) {
  2433.                 $orderRepository = $this->getEntityManager()->getRepository(Order::class);
  2434.                 $order = $orderRepository->findOneById($orderId);
  2435.                 if ($order) {
  2436.                     $domainId = $order->getDomain()->getId();
  2437.                     if ($paymentTypeId == PaymentType::Quatro->value) {
  2438.                         if (!is_null($request->query->get('state'))) {
  2439.                             $state = $request->query->get('state');
  2440.                             switch ($state) {
  2441.                                 case 'approved':
  2442.                                     $data['payment_check_result'] = false;
  2443.                                     $order->setPaymentStatus(0);
  2444.                                     break;
  2445.                                 case 'signed':
  2446.                                     $data['payment_check_result'] = true;
  2447.                                     $order->setPaymentStatus(1);
  2448.                                     break;
  2449.                                 case 'canceled':
  2450.                                     $data['payment_check_result'] = false;
  2451.                                     $order->setPaymentStatus(2);
  2452.                                     break;
  2453.                                 default:
  2454.                                     $order->setPaymentStatus(2);
  2455.                                     $data['payment_check_result'] = false;
  2456.                             }
  2457.                         } else {
  2458.                             $order->setPaymentStatus(2);
  2459.                             $data['payment_check_result'] = false;
  2460.                         }
  2461.                         $entityManager->flush();
  2462.                     }
  2463.                     if ($paymentTypeId == PaymentType::Cetelem->value) {
  2464.                         if ($domainId == 1) { // CETELEM SK - LPC SK
  2465.                             $data['cetelem_sk_check'] = true;
  2466.                             if (!is_null($request->query->get('result')) && is_numeric($request->query->get('result'))) {
  2467.                                 $result = $request->query->get('result');
  2468.                                 switch ($result) {
  2469.                                     case 1:
  2470.                                         $order->setPaymentStatus(1);
  2471.                                         $data['payment_check_result'] = true;
  2472.                                         break;
  2473.                                     case 2:
  2474.                                         $order->setStatus(Order::STATUS_WAITING);
  2475.                                         $order->setPaymentStatus(0);
  2476.                                         break;
  2477.                                     case 3:
  2478.                                     case 5:
  2479.                                         $order->setStatus(Order::STATUS_WAITING);
  2480.                                         $order->setPaymentStatus(2);
  2481.                                         break;
  2482.                                     default:
  2483.                                         $order->setStatus(Order::STATUS_WAITING);
  2484.                                         $order->setPaymentStatus(2);
  2485.                                 }
  2486.                                 $entityManager->flush();
  2487.                             }
  2488.                         } elseif ($domainId == 3) { // CETELEM HU - FPC HU
  2489.                             if ($gateResponse != 0) {
  2490.                                 switch ($gateResponse) {
  2491.                                     case md5($order->getId() . '1'): // OK
  2492.                                         $order->setPaymentStatus(0);
  2493.                                         $data['cetelem_hu_check'] = 1;
  2494.                                         break;
  2495.                                     case md5($order->getId() . '2'): // Pending
  2496.                                         $order->setPaymentStatus(0);
  2497.                                         $data['cetelem_hu_check'] = 2;
  2498.                                         break;
  2499.                                     case md5($order->getId() . '3'): // Rejected
  2500.                                         $order->setPaymentStatus(2);
  2501.                                         $data['cetelem_hu_check'] = 3;
  2502.                                         break;
  2503.                                     default:
  2504.                                         $order->setPaymentStatus(2);
  2505.                                         $data['cetelem_hu_check'] = 3;
  2506.                                 }
  2507.                                 $entityManager->flush();
  2508.                             }
  2509.                         }
  2510.                     }
  2511.                     if (in_array($paymentTypeId, [PaymentType::DebitCard->value, PaymentType::DebitCard3Percent->value])) {
  2512.                         $domainIdsForGoPay = [
  2513.                             Domain::DOMAIN_ID_RT_SK,
  2514.                             Domain::DOMAIN_ID_WS_SK,
  2515.                             Domain::DOMAIN_ID_RT_CZ,
  2516.                             Domain::DOMAIN_ID_WS_CZ,
  2517.                             Domain::DOMAIN_ID_RT_EU,
  2518.                             Domain::DOMAIN_ID_WS_EU,
  2519.                             Domain::DOMAIN_ID_WS_HU,
  2520.                             Domain::DOMAIN_ID_RT_HU,
  2521.                         ];
  2522.                         // GoPay
  2523.                         if (in_array($domainId, $domainIdsForGoPay)) {
  2524.                             $data['gopay_check'] = true;
  2525.                             $paymentid = $request->query->get('id');
  2526.                             $goPayHelper = $this->getGopayHelper($request);
  2527.                             // Order Helper
  2528.                             $orderHelper = $this->getOrderHelper($request);
  2529.                             $productHelper = $this->getProductHelper($request);
  2530.                             if ($goPayHelper->checkPaymentStatus($paymentid)) {
  2531.                                 $data['payment_check_result'] = true;
  2532.                                 $order->setPaymentStatus(Order::PAYMENT_STATUS_PAID);
  2533.                                 $orderSetting = new OrderSetting();
  2534.                                 $orderSetting->setOrder($order);
  2535.                                 $orderSetting->setType(OrderSetting::TYPE_PAID_PRICE_BY_CARD);
  2536.                                 $orderSetting->setValue($order->getFullPrice());
  2537.                                 $entityManager->persist($orderSetting);
  2538.                                 if ($order->getPaymentType() != $paymentTypeId) {
  2539.                                     $order->setPaymentType($paymentTypeId);
  2540.                                     $entityManager->persist($order);
  2541.                                 }
  2542.                                 // Send Email
  2543.                                 $orderHelper->sendPaymentStatusEmail(
  2544.                                     'success',
  2545.                                     $order,
  2546.                                     $productHelper,
  2547.                                     $this->getContactInfos(),
  2548.                                     $this->getWhiteListCouponCodes()
  2549.                                 );
  2550.                             } else {
  2551.                                 // Check if paid status is not set already to paid, if yes, do not change it back to failed
  2552.                                 if ($order->getPaymentStatus() != Order::PAYMENT_STATUS_PAID) {
  2553.                                     $order->setPaymentStatus(Order::PAYMENT_STATUS_FAILED);
  2554.                                     // Send Email
  2555.                                     /*$orderHelper->sendPaymentStatusEmail(
  2556.                                         'fail',
  2557.                                         $order,
  2558.                                         $productHelper,
  2559.                                         $this->getContactInfos(),
  2560.                                         $this->getWhiteListCouponCodes()
  2561.                                     );*/
  2562.                                     $this->getKlaviyoConnect($request)->createNewOrderIsNotPayedDebitCartEvent($order);
  2563.                                     // Payment Helper
  2564.                                     $gopayHelper = $this->getGopayHelper($request);
  2565.                                     // Payment Data
  2566.                                     $data['gopay_data'] = $gopayHelper->getInlineGatewayDataForOrder($order);
  2567.                                     // Save Order ID
  2568.                                     $request->getSession()->set('updateOrderId', $order->getId());
  2569.                                 }
  2570.                             }
  2571.                             $entityManager->flush();
  2572.                         }
  2573.                         $data['publicOrderLink'] = $order->getDomain()->getUrl() . $this->generateUrl(
  2574.                             'customer_order_show',
  2575.                             [
  2576.                                 'orderId' => $order->getId(),
  2577.                                 'token' => $orderRepository->generatePublicLinkToken(
  2578.                                     [
  2579.                                         'orderId' => $order->getId(),
  2580.                                     ]
  2581.                                 ),
  2582.                             ]
  2583.                         );
  2584.                     }
  2585.                     if ($order->getPaymentType() == PaymentType::Instacash->value) {
  2586.                         $data['payment_verification_valid'] = true;
  2587.                         $data['instacash_check'] = true;
  2588.                     }
  2589.                     if ($order->getPaymentType() == PaymentType::Milpay->value) {
  2590.                         $data['payment_verification_valid'] = true;
  2591.                         $data['milpay_check'] = true;
  2592.                     }
  2593.                     if ($order->getPaymentType() == PaymentType::PastPay->value) {
  2594.                         $data['pastpay_check'] = true;
  2595.                         switch ($gateResponse) {
  2596.                             case 'success':
  2597.                                 $data['payment_verification_valid'] = true;
  2598.                                 $data['pastpay_check_result'] = true;
  2599.                                 $orderSettingApplicationStatus = OrderSetting::createSetting(
  2600.                                     $order,
  2601.                                     OrderSetting::TYPE_PAST_PAY_RESERVE,
  2602.                                     'CREATED'
  2603.                                 );
  2604.                                 $entityManager->persist($orderSettingApplicationStatus);
  2605.                                 $entityManager->flush();
  2606.                                 break;
  2607.                             case 'failure':
  2608.                                 $data['pastpay_check_result'] = false;
  2609.                                 $domainIdsForGoPay = [
  2610.                                     Domain::DOMAIN_ID_RT_SK,
  2611.                                     Domain::DOMAIN_ID_WS_SK,
  2612.                                     Domain::DOMAIN_ID_RT_CZ,
  2613.                                     Domain::DOMAIN_ID_WS_CZ,
  2614.                                     Domain::DOMAIN_ID_RT_EU,
  2615.                                     Domain::DOMAIN_ID_WS_EU,
  2616.                                 ];
  2617.                                 if ($this->isYear2025() || ($this->getLoginHelper($request)->getLoggedInCustomer() && $this->getLoginHelper($request)->getLoggedInCustomer()->getId() == 11463)) {
  2618.                                     $domainIdsForGoPay = array_merge([], $domainIdsForGoPay, [Domain::DOMAIN_ID_RT_HU, Domain::DOMAIN_ID_WS_HU]);
  2619.                                 }
  2620.                                 if (in_array($domainId, $domainIdsForGoPay)) {
  2621.                                     $gopayHelper = $this->getGopayHelper($request);
  2622.                                     $data['gopay_data'] = $gopayHelper->getInlineGatewayDataForOrder($order);
  2623.                                 } elseif (in_array($domainId, [Domain::DOMAIN_ID_RT_HU, Domain::DOMAIN_ID_WS_HU])) {
  2624.                                     $simplePayHelper = $this->getSimplePayHelper($request);
  2625.                                     $data['simplepay_data'] = $simplePayHelper->createPaymentUrlForOrder($order, $request);
  2626.                                 }
  2627.                                 $request->getSession()->set('updateOrderId', $order->getId());
  2628.                                 break;
  2629.                         }
  2630.                     }
  2631.                     if ($order->getPaymentType() == PaymentType::Klarna->value) {
  2632.                         $data['klarna_check'] = true;
  2633.                         $klarna = $this->getKlarna($domainId, $request, $order->getShippingCountry());
  2634.                         if ($request->query->has('session_id') && $request->query->has('authorization_token')) {
  2635.                             $klarnaSession = $klarna->getKlarnaHppSession($request->query->get('session_id'));
  2636.                             if (gettype($klarnaSession) == "array" && $klarnaSession['status'] == Klarna::ACCPETED_HPP_STATUS) {
  2637.                                 $data['klarna_check_result'] = $this->klarnaAuthorizationCallback($domainId, $order, $request);
  2638.                                 if ($data['klarna_check_result'] != false && $data['klarna_check_result']['status'] == 'complete') {
  2639.                                     switch ($order->getDomain()->getCurrency()) {
  2640.                                         case 'Ft':
  2641.                                             $data['currencyCode'] = 'HUF';
  2642.                                             break;
  2643.                                         case 'Kč':
  2644.                                             $data['currencyCode'] = 'CZK';
  2645.                                             break;
  2646.                                         case '€':
  2647.                                             $data['currencyCode'] = 'EUR';
  2648.                                             break;
  2649.                                         default:
  2650.                                             $data['currencyCode'] = 'EUR';
  2651.                                     }
  2652.                                     $orderData = $this->getOrderHelper($request)->getDataFromEmail(
  2653.                                         $order,
  2654.                                         $this->getProductHelper($request),
  2655.                                         $this->getContactInfos(),
  2656.                                         $this->getWhiteListCouponCodes()
  2657.                                     );
  2658.                                     $data['ecommerce_klarna'] = [
  2659.                                         'orderId'              => $order->getId(),
  2660.                                         'domainName'           => $order->getDomain()->getName(),
  2661.                                         'currencyCode'         => match ($order->getDomain()->getCurrency()) {
  2662.                                             'Ft'    => $data['currencyCode'] = 'HUF',
  2663.                                             'Kč'    => $data['currencyCode'] = 'CZK',
  2664.                                             default => $data['currencyCode'] = 'EUR',
  2665.                                         },
  2666.                                         'orderTotal'           => $order->getFullPrice(),
  2667.                                         'orderTax'             => round($order->getTaxOutOfFullPrice(), 2),
  2668.                                         'orderShipping'        => $order->getShippingPrice(),
  2669.                                         'marketingProductsGA4' => $orderData['response']['marketingProductsGA4'],
  2670.                                         'customerEmail'        => $order->getShippingEmail(),
  2671.                                         'customerPhone'        => $order->getShippingPhone(),
  2672.                                         'customerFirstName'    => $order->getShippingFirstName(),
  2673.                                         'customerLastName'     => $order->getSHippingLastName(),
  2674.                                         'customerStreet'       => $order->getShippingStreet(),
  2675.                                         'customerCity'         => $order->getShippingCity(),
  2676.                                         'customerPostalCode'   => $order->getShippingZip(),
  2677.                                         'customerCountry'      => $order->getShippingCountry(),
  2678.                                     ];
  2679.                                 }
  2680.                             }
  2681.                         } else {
  2682.                             $klarnaSession = $klarna->getKlarnaSession($request->getSession()->get('klarnaSessionId'));
  2683.                             if ($klarnaSession['status'] == Klarna::INCOMPLETE_STATUS) {
  2684.                                 $redirectUrl = $this->generateUrl('checkout_payment_check', [
  2685.                                     'paymentTypeId' => PaymentType::Klarna->value,
  2686.                                     'orderId'       => $order->getId(),
  2687.                                 ]);
  2688.                                 $redirectUrl = $klarna->createKlarnaUrl($redirectUrl, $request->getSession()->get('klarnaSessionId'));
  2689.                                 $gopayHelper = $this->getGopayHelper($request);
  2690.                                 $data['klarna_data'] = [
  2691.                                     'redirectUrl' => $redirectUrl['redirect_url'],
  2692.                                     'gopay_data'  => $gopayHelper->getInlineGatewayDataForOrder($order),
  2693.                                 ];
  2694.                                 $data['payment_verification_valid'] = true;
  2695.                                 $request->getSession()->set('updateOrderId', $order->getId());
  2696.                             }
  2697.                         }
  2698.                     }
  2699.                     $data['orderId'] = $order->getId();
  2700.                     $data['shippingTypeId'] = $order->getShippingType();
  2701.                 }
  2702.             }
  2703.             if ($request->getSession()->has('checkout')) {
  2704.                 $request->getSession()->remove('checkout');
  2705.             }
  2706.             if ($request->getSession()->has('paymentOrderId')) {
  2707.                 $request->getSession()->remove('paymentOrderId');
  2708.             }
  2709.             if (!in_array($domainId, [Domain::DOMAIN_ID_RT_HU, Domain::DOMAIN_ID_WS_HU, Domain::DOMAIN_ID_RT_CZ, Domain::DOMAIN_ID_WS_CZ])) {
  2710.                 $data['overLimit'] = $order->getFullPrice() > 300;
  2711.             } elseif (in_array($domainId, [Domain::DOMAIN_ID_RT_HU, Domain::DOMAIN_ID_WS_HU])) {
  2712.                 $data['overLimit'] = $order->getFullPrice() > 120_000;
  2713.             } else {
  2714.                 $data['overLimit'] = $order->getFullPrice() > 7_500;
  2715.             }
  2716.         }
  2717.         return $this->render('AtechNetCoreBundle/Checkout/paymentResult.html.twig', $data);
  2718.     }
  2719.     /**
  2720.      * @Route("/checkout/payment-notification/{orderId}/{paymentTypeId}", name="checkout_payment_notification", defaults={"_locale":""})
  2721.      * @Route("/{_locale<%supported_locales%>?}/checkout/payment-notification/{orderId}/{paymentTypeId}", name="checkout_payment_notification_locale", defaults={"_locale":""})
  2722.      * @param Request $request
  2723.      * @param int $paymentTypeId
  2724.      * @param int $orderId
  2725.      * @param int|string $gateResponse
  2726.      * @return Response
  2727.      * @throws InvalidArgumentException
  2728.      */
  2729.     public function paymentNotificationAction(Request $request, $paymentTypeId, $orderId)
  2730.     {
  2731.         $data = [];
  2732.         $entityManager = $this->getEntityManager();
  2733.         $paymentId = $request->query->get('id');
  2734.         if (is_numeric($paymentId)) {
  2735.             $order = $entityManager->getRepository(Order::class)->find($orderId);
  2736.             if ($order) {
  2737.                 $goPayHelper = $this->getGopayHelper($request);
  2738.                 if ($goPayHelper->checkPaymentStatus($paymentId)) {
  2739.                     $order->setPaymentStatus(Order::PAYMENT_STATUS_PAID);
  2740.                 } else {
  2741.                     if ($order->getPaymentStatus() != Order::PAYMENT_STATUS_PAID) {
  2742.                         $order->setPaymentStatus(Order::PAYMENT_STATUS_FAILED);
  2743.                     }
  2744.                 }
  2745.                 $entityManager->flush();
  2746.                 $data['result'] = true;
  2747.             }
  2748.         }
  2749.         if (!isset($data['result'])) {
  2750.             $data['result'] = false;
  2751.         }
  2752.         return new JsonResponse($data);
  2753.     }
  2754.     /**
  2755.      * @Route("/checkout/payment-ipn-check", name="checkout_payment_ipn_check", defaults={"_locale":""})
  2756.      * @Route("/{_locale<%supported_locales%>?}/checkout/payment-ipn-check", name="checkout_payment_ipn_check_locale", defaults={"_locale":""})
  2757.      * @param Request $request
  2758.      * @throws \Exception
  2759.      */
  2760.     public function paymentIpnCheckAction(Request $request)
  2761.     {
  2762.         $simplePayHelper = $this->getSimplePayHelper($request);
  2763.         $json = file_get_contents('php://input');
  2764.         $result = $simplePayHelper->getIpnValidationData($request, $json);
  2765.         if (is_array($result)) {
  2766.             $response = new Response(
  2767.                 $result['confirmContent'],
  2768.                 Response::HTTP_OK,
  2769.                 [
  2770.                     'Accept-language' => 'EN',
  2771.                     'Content-type' => 'application/json',
  2772.                     'Signature' => $result['signature'],
  2773.                 ]
  2774.             );
  2775.         } else {
  2776.             $response = new Response('Invalid data');
  2777.         }
  2778.         return $response;
  2779.     }
  2780.     /**
  2781.      * @param Basket $cart
  2782.      * @param Request $request
  2783.      * @return array
  2784.      * @throws \Exception
  2785.      */
  2786.     private function orderSummary(Basket $cart, Request $request)
  2787.     {
  2788.         $data = [];
  2789.         $data['hideChat'] = true;
  2790.         $entityManager = $this->getEntityManager();
  2791.         $multiStore = $this->getMultiStoreHelper($request);
  2792.         $productHelper = $this->getProductHelper($request);
  2793.         $translator = $this->getDatabaseTranslator($request);
  2794.         $customer = $this->getLoginHelper($request)->getLoggedInCustomer();
  2795.         $useZeroVat = $this->useZeroVat($customer, $request);
  2796.         $domain = $multiStore->getDomain();
  2797.         $data['currency'] = $domain->getCurrency();
  2798.         $data['precision'] = $domain->getPricePrecision();
  2799.         $placeholder = $this->getImage('placeholder.jpg', '')->resize(Image::PRODUCT_CART_THUMB_WIDTH, Image::PRODUCT_CART_THUMB_HEIGHT);
  2800.         $data['total'] = 0;
  2801.         $data['subTotal'] = 0;
  2802.         $data['items'] = [];
  2803.         $data['marketingProductsGA4'] = '';
  2804.         $data['countItems'] = 0;
  2805.         $data['valid'] = true;
  2806.         $data['validShipping'] = true;
  2807.         $data['enableFreeShipping'] = [];
  2808.         $data['cartId'] = $cart->getId();
  2809.         $checkout = $request->getSession()->get('checkout');
  2810.         $checkoutCustomerIsCompany = $this->checkoutCustomerIsCompany($request);
  2811.         /**
  2812.          * CHECK IF EXIST A SHIPPING METHOD WITH FREE SHIPPING
  2813.          */
  2814.         $shippingTypesWithFreeShipping = $this->getActiveFreeShippingTypes($domain);
  2815.         foreach ($cart->getBasketItems() as $index => $item) {
  2816.             $stock = true;
  2817.             $product = $productHelper->getStructuredDataForProduct($item->getProduct(), 'cart');
  2818.             if ($product) {
  2819.                 $image = $placeholder;
  2820.                 if (is_object($product['images'])) {
  2821.                     $image = $this->getImage($product['images'], 'product/' . $product['code'])->resize(Image::PRODUCT_CART_THUMB_WIDTH, Image::PRODUCT_CART_THUMB_HEIGHT);
  2822.                 }
  2823.                 // Cross-sell Attribute Options
  2824.                 $crossSellAttributeOptions = CartHelper::getCrossSellAttributeOptionsByProductTypeId($product['productTypeId'], $domain->getId());
  2825.                 $optionPrice = $optionPriceValue = $optionSpecialValue = 0;
  2826.                 $accessories = '';
  2827.                 /**
  2828.                  * @var AttributeOption $option
  2829.                  */
  2830.                 foreach ($item->getItemAttributes() as $attribute) {
  2831.                     $option = $attribute->getAttributeOption();
  2832.                     if ($option && !in_array($option->getId(), $this->unWantedAttributes)) {
  2833.                         $optionMeta = $option->getDomainMeta($domain);
  2834.                         if ($optionMeta) {
  2835.                             // Option Price excluding VAT
  2836.                             if ($useZeroVat) {
  2837.                                 if ($optionMeta->isDiscounted()) {
  2838.                                     $price = $optionMeta->getDomainDiscount();
  2839.                                     $optionSpecialValue += $optionMeta->getDomainDiscount();
  2840.                                 } else {
  2841.                                     $price = $optionMeta->getDomainPrice();
  2842.                                 }
  2843.                                 $optionPriceValue += $optionMeta->getDomainPrice();
  2844.                             }
  2845.                             // Option Price including VAT
  2846.                             else {
  2847.                                 if ($optionMeta->isDiscounted()) {
  2848.                                     if (isset($customer) && $customer->getId() == Customer::MAXMEDIA_KFT_ID) {
  2849.                                         $price = $domain->createVatPrice($optionMeta->getDiscount(), 1.27);
  2850.                                         $optionSpecialValue += $domain->createVatPrice($optionMeta->getDiscount(), 1.27);
  2851.                                     } else {
  2852.                                         $price = $optionMeta->getDomainVatDiscount();
  2853.                                         $optionSpecialValue += $optionMeta->getDomainVatDiscount();
  2854.                                     }
  2855.                                 } else {
  2856.                                     if (isset($customer) && $customer->getId() == Customer::MAXMEDIA_KFT_ID) {
  2857.                                         $price = $domain->createVatPrice($optionMeta->getPrice(), 1.27);
  2858.                                     } else {
  2859.                                         $price = $optionMeta->getDomainVatPrice();
  2860.                                     }
  2861.                                 }
  2862.                                 if (isset($customer) && $customer->getId() == Customer::MAXMEDIA_KFT_ID) {
  2863.                                     $optionPriceValue += $domain->createVatPrice($optionMeta->getPrice(), 1.27);
  2864.                                 } else {
  2865.                                     $optionPriceValue += $optionMeta->getDomainVatPrice();
  2866.                                 }
  2867.                             }
  2868.                             // Cross-sell Attribute Options Calculated Price
  2869.                             if (isset($crossSellAttributeOptions[$option->getId()])) {
  2870.                                 if (isset($crossSellAttributeOptions[$option->getId()]['percentPrice'])) {
  2871.                                     $price = $domain->createVatPrice((($item->getPriceWithAttributesForDomainWithException($domain, $option) * $crossSellAttributeOptions[$option->getId()]['percentPrice']) / 100), 1.);
  2872.                                 }
  2873.                             }
  2874.                             $accessories .= $option->getAttribute()->getTitle($translator) . ': ' . $option->getTitle($translator) . '<br>';
  2875.                             $optionPrice += $price;
  2876.                         }
  2877.                     }
  2878.                 }
  2879.                 // Price
  2880.                 $priceValue = $specialValue = 0;
  2881.                 if ($useZeroVat) {
  2882.                     if ($product['isDiscounted']) {
  2883.                         $price = $specialValue = $product['rawDiscountPrice'];
  2884.                     } else {
  2885.                         $price = $product['price'];
  2886.                     }
  2887.                     $priceValue = $product['price'];
  2888.                 } else {
  2889.                     if ($product['isDiscounted']) {
  2890.                         if (isset($customer) && $customer->getId() == Customer::MAXMEDIA_KFT_ID) {
  2891.                             $price = $specialValue = $domain->createVatPrice($product['discountPrice'], 1.27);
  2892.                         } else {
  2893.                             $price = $specialValue = $product['discountVatPrice'];
  2894.                         }
  2895.                     } else {
  2896.                         if (isset($customer) && $customer->getId() == Customer::MAXMEDIA_KFT_ID) {
  2897.                             $price = $domain->createVatPrice($product['rawPrice'], 1.27);
  2898.                         } else {
  2899.                             $price = $product['vatPrice'];
  2900.                         }
  2901.                     }
  2902.                     $priceValue = $product['vatPrice'];
  2903.                 }
  2904.                 if ($product['availableQty'] < $item->getQuantity() && !$product['isReservable'] && $product['outOfStockStatus'] !== Product::OutOfStockStatus_VisibleShadow) {
  2905.                     $stock = $data['valid'] = false;
  2906.                 }
  2907.                 if (
  2908.                     $domain->getId() == Domain::DOMAIN_ID_RT_EU &&
  2909.                     is_array($checkout) &&
  2910.                     array_key_exists('billingCountry', $checkout) &&
  2911.                     $checkoutCustomerIsCompany
  2912.                 ) {
  2913.                     $country = $checkout['billingCountry'];
  2914.                     $price = $domain->createWithoutVatPriceFromVatPrice($price, $country);
  2915.                     $optionPrice = $domain->createWithoutVatPriceFromVatPrice($optionPrice, $country);
  2916.                 }
  2917.                 $data['items'][] = [
  2918.                     'id' => $item->getId(),
  2919.                     'productId' => $product['id'],
  2920.                     'stock' => $stock,
  2921.                     'model' => $product['code'],
  2922.                     'name' => ($product['vendor'] !== '' ? $product['vendor'] . ' ' : '') . $product['title'],
  2923.                     'image' => $image,
  2924.                     'price' => ($price + $optionPrice) * $item->getQuantity(),
  2925.                     'href' => $this->url($request)->link('product', [
  2926.                         'product_id' => $product['id'], 
  2927.                         'isBazaar'   => $product['isBazaar'] ?? 0
  2928.                     ]),
  2929.                     'accessories' => $accessories,
  2930.                     'quantity' => $item->getQuantity(),
  2931.                 ];
  2932.                 $data['subTotal'] += ($price + $optionPrice) * $item->getQuantity();
  2933.                 $data['countItems'] += (int)$item->getQuantity();
  2934.                 $data['marketingProductsGA4'] .= ($data['marketingProductsGA4'] !== '' ? ',' : '') . '{ item_id: \'' . $product['code'] . '\', item_name: \'' . ($product['vendor'] !== '' ? $product['vendor'] . ' ' : '') . $product['title'] . '\', item_brand: \'' . $product['vendor'] . '\', item_category: \'' . $product['productType'] . '\', quantity: ' . $item->getQuantity() . ', discount: \'' . (round(($specialValue + $optionSpecialValue), $data['precision']) > 0 ? (round(($priceValue + $optionPriceValue), $data['precision']) - round(($specialValue + $optionSpecialValue), $data['precision'])) : 0) . '\', price: \'' . round(($priceValue + $optionPriceValue), $data['precision']) . '\', index: ' . $index . '}';
  2935.             }
  2936.             $filteredShippingTypes = array_filter($shippingTypesWithFreeShipping, function ($shippingType) use ($product) {
  2937.                 /** @var DomainShippingType $shippingType */
  2938.                 if (empty($shippingType->getFreeShippingProductTypes())) {
  2939.                     return true;
  2940.                 }
  2941.                 return in_array($product['productTypeId'], $shippingType->getFreeShippingProductTypes(), true);
  2942.             });
  2943.             if (count($filteredShippingTypes) > 0) {
  2944.                 /** @var DomainShippingType $shippingType */
  2945.                 foreach ($filteredShippingTypes as $shippingType) {
  2946.                     $data['enableFreeShipping'][] = $shippingType->getType();
  2947.                 }
  2948.             }
  2949.         }
  2950.         $data['estimation'] = true;
  2951.         $data['coupon'] = '';
  2952.         $data['discount'] = 0;
  2953.         $data['shippingCost'] = $data['paymentCost'] = $data['packageFee'] = null;
  2954.         if ($domain->getId() == Domain::DOMAIN_ID_RT_HU) {
  2955.             $packageFeeProduct = $entityManager->getRepository(Product::class)->findOneById(Product::MPL_PACKAGE_FEE_PRODUCT_ID);
  2956.             $data['packageFee'] = [
  2957.                 'title' => 'Package fee',
  2958.                 'price' => $packageFeeProduct->getDomainMeta($domain)->getCurrentVatPrice(),
  2959.             ];
  2960.         }
  2961.         $mplIsSelected = false;
  2962.         if ($request->getSession()->has('checkout')) {
  2963.             $checkout = $request->getSession()->get('checkout');
  2964.             // Selected Shipping Method
  2965.             if (isset($checkout['shippingMethodId']) && (int)$checkout['shippingMethodId'] > 0) {
  2966.                 $shippingMethod = $entityManager->getRepository(DomainShippingType::class)->findOneBy([
  2967.                     'id' => $checkout['shippingMethodId'],
  2968.                     'domain' => $multiStore->getDomainId(),
  2969.                 ]);
  2970.                 if ($shippingMethod) {
  2971.                     // Shipping Cost
  2972.                     $data['shippingCost'] = in_array($shippingMethod->getType(), $data['enableFreeShipping']) ? 0 : $shippingMethod->getPrice();
  2973.                     // Shipping Type
  2974.                     $data['shippingType'] = $shippingMethod->getType();
  2975.                     // Free Shipping
  2976.                     if (((float)$shippingMethod->getFreeShipLimit() > 0 && (float)$shippingMethod->getFreeShipLimit() < $data['subTotal'])) {
  2977.                         $data['shippingCost'] = 0;
  2978.                     }
  2979.                     $data['estimation'] = false;
  2980.                     // Validate Pickup Point availability
  2981.                     if ($shippingMethod->getType() == DomainShippingType::ShippingType_PICKUP_POINT_Id) {
  2982.                         if (!$cart->isPickupPointAvailable()) {
  2983.                             $data['validShipping'] = false;
  2984.                         }
  2985.                     }
  2986.                     if ($shippingMethod->getType() == DomainShippingType::SHIPPING_TYPE_MPL_ID) {
  2987.                         $mplIsSelected = true;
  2988.                     }
  2989.                 }
  2990.             } // Default Shipping Method
  2991.             else {
  2992.                 // Shipping Cost
  2993.                 $data['shippingCost'] = null;
  2994.                 $data['estimation'] = false;
  2995.             }
  2996.             if (isset($checkout['paymentMethodId']) && (int)$checkout['paymentMethodId'] > 0) {
  2997.                 $paymentMethod = $entityManager->getRepository(DomainPaymentType::class)->findOneBy([
  2998.                     'id' => $checkout['paymentMethodId'],
  2999.                     'domain' => $multiStore->getDomainId(),
  3000.                 ]);
  3001.                 if ($paymentMethod) {
  3002.                     $data['paymentCost'] = $paymentMethod->getPrice();
  3003.                 }
  3004.             }
  3005.             $cashonDeliveryPaymentTypes = [
  3006.                 PaymentType::CashOnDelivery->value,
  3007.                 PaymentType::CashOnDelivery3Percent->value,
  3008.             ];
  3009.             if (isset($checkout['paymentMethodTypeId']) && in_array((int)$checkout['paymentMethodTypeId'], $cashonDeliveryPaymentTypes)) {
  3010.                 $domainPaymentType = $entityManager->getRepository(DomainPaymentType::class)->findOneBy(
  3011.                     [
  3012.                         'domain' => $multiStore->getDomainId(),
  3013.                         'type' => $checkout['paymentMethodTypeId'],
  3014.                     ]
  3015.                 );
  3016.                 if ($domainPaymentType) {
  3017.                     $data['cashOnDeliveryProductItem'] = [
  3018.                         'title' => $translator->trans('Cash on delivery'),
  3019.                         'price' => $domainPaymentType->getPrice(),
  3020.                     ];
  3021.                 }
  3022.             }
  3023.         } else {
  3024.             $data['shippingCost'] = null;
  3025.             $data['estimation'] = false;
  3026.         }
  3027.         // Coupon
  3028.         if (isset($checkout['coupon']['code']) && $checkout['coupon']['code'] != '') {
  3029.             $data['coupon'] = $checkout['coupon']['code'];
  3030.             $coupon = $entityManager->getRepository(Coupon::class)->findOneBy([
  3031.                 'code' => $checkout['coupon']['code'],
  3032.                 'domain' => $domain,
  3033.             ]);
  3034.             if ($coupon && $cart) {
  3035.                 // Set Email
  3036.                 if (!empty($checkout['email'])) {
  3037.                     $cart->setEmail($checkout['email']);
  3038.                 } else {
  3039.                     $cart->setEmail(null);
  3040.                 }
  3041.                 // Coupon Free Shipping
  3042.                 $isCouponApplicableForFreeShipping = CartHelper::isCouponApplicableForFreeShipping($coupon, $cart, $entityManager);
  3043.                 // Coupon Discount
  3044.                 $isCouponValidForBasket = CartHelper::isCouponValidForBasket($coupon, $cart, $entityManager);
  3045.                 if ($isCouponValidForBasket !== false || $isCouponApplicableForFreeShipping) {
  3046.                     $data['discount'] = (float)$isCouponValidForBasket;
  3047.                 } else {
  3048.                     $data['coupon'] = '';
  3049.                 }
  3050.                 // Free Shipping
  3051.                 if ($isCouponApplicableForFreeShipping) {
  3052.                     $data['shippingCost'] = 0;
  3053.                 }
  3054.             } else {
  3055.                 $data['coupon'] = '';
  3056.             }
  3057.         } else {
  3058.             $data['coupon'] = '';
  3059.         }
  3060.         if (isset($checkout['3_percent_discount']) && $checkout['3_percent_discount'] && $data['discount'] == 0) {
  3061.             if ($cart) {
  3062.                 $data['discount'] = CartHelper::getPercentDiscountForBasket($cart, 3);
  3063.                 $data['three_percent_partner_discount'] = true;
  3064.             }
  3065.         }
  3066.         $data['total'] = $data['subTotal'] + $data['shippingCost'] + $data['paymentCost'] - $data['discount'];
  3067.         if ($mplIsSelected) {
  3068.             $data['total'] += $data['packageFee']['price'];
  3069.         }
  3070.         $data['currency_ISO'] = $this->getCurrencyISOForm($domain->getCurrency());
  3071.         // Basket expires in...
  3072.         $cartUpdated = clone $cart->getUpdated();
  3073.         $data['expire'] = $cartUpdated->add(new \DateInterval("PT" . self::TIMEOUT . "H"))->format('Y-m-d H:i:s');
  3074.         return $data;
  3075.     }
  3076.     /**
  3077.      * @Route("/checkout/success-upsell", name="checkout_add_upsell", defaults={"_locale":""})
  3078.      * @Route("/{_locale<%supported_locales%>?}/checkout/success-upsell", name="checkout_add_upsell_locale", defaults={"_locale":""})
  3079.      * @param Request $request
  3080.      * @return JsonResponse
  3081.      */
  3082.     public function successUpsellAction(Request $request)
  3083.     {
  3084.         $response = [
  3085.             'result' => 'fail',
  3086.         ];
  3087.         $entityManager = $this->getEntityManager();
  3088.         $req = $request->request;
  3089.         $orderId = $req->get('orderId');
  3090.         $upsellType = $req->get('upsellType');
  3091.         $price = $req->get('price');
  3092.         $want = $req->get('want');
  3093.         if (is_numeric($orderId)) {
  3094.             $order = $entityManager->getRepository(Order::class)->findOneById($orderId);
  3095.             if ($order) {
  3096.                 $centralisUser = $this->getCentralisUser();
  3097.                 $orderUpsellSetting = $order->getUpsellStatSetting();
  3098.                 if ($want == 1) {
  3099.                     if (in_array($upsellType, [1, 2])) {
  3100.                         $text = 'YES, +4GB RAM UPSELL ' . $price;
  3101.                     }
  3102.                     if ($upsellType == 3) {
  3103.                         $text = 'YES, CLEANER KIT ' . $price;
  3104.                     }
  3105.                     if ($orderUpsellSetting) {
  3106.                         $orderUpsellSetting->setValue(OrderSetting::SUB_TYPE_UPSELL_STATS_WANT);
  3107.                     }
  3108.                 } else {
  3109.                     $text = 'NO UPSELL';
  3110.                     if ($orderUpsellSetting) {
  3111.                         $orderUpsellSetting->setValue(OrderSetting::SUB_TYPE_UPSELL_STATS_WANT);
  3112.                     }
  3113.                 }
  3114.                 $orderComment = new OrderComment();
  3115.                 $orderComment->setOrder($order);
  3116.                 $orderComment->setText($text);
  3117.                 $orderComment->isDeletableByUser($centralisUser);
  3118.                 $orderComment->setCreatedBy($centralisUser);
  3119.                 $orderComment->setType(OrderComment::TYPE_FOR_PREPARATION);
  3120.                 $entityManager->persist($orderComment);
  3121.                 $entityManager->flush();
  3122.                 $response = [
  3123.                     'result' => 'success',
  3124.                 ];
  3125.             }
  3126.         }
  3127.         return new JsonResponse($response);
  3128.     }
  3129.     /**
  3130.      * @param float $originalPrice
  3131.      * @param int $discountPercentage
  3132.      * @param string $domainLanguageCode
  3133.      * @return float|int
  3134.      */
  3135.     private function calculateDiscountedPrice($originalPrice, $discountPercentage, $domainLanguageCode)
  3136.     {
  3137.         $discountedPrice = $originalPrice * (1 - ($discountPercentage / 100));
  3138.         if ($domainLanguageCode == 'hu') {
  3139.             $discountedPrice = ceil($discountedPrice / 10) * 10;
  3140.         }
  3141.         if ($domainLanguageCode == 'cz') {
  3142.             $discountedPrice = round($discountedPrice);
  3143.         }
  3144.         return $discountedPrice;
  3145.     }
  3146.     /**
  3147.      * @Route("/checkout/order/{orderId}/create-stock-reservation", name="checkout_add_stock_movement", defaults={"_locale":""})
  3148.      * @Route("/{_locale<%supported_locales%>?}/checkout/order/{orderId}/create-stock-reservation", name="checkout_add_stock_movement_locale", defaults={"_locale":""})
  3149.      * @param Request $request
  3150.      * @param int $orderId
  3151.      *
  3152.      * @return JsonResponse
  3153.      * @throws ContainerExceptionInterface
  3154.      * @throws NotFoundExceptionInterface
  3155.      */
  3156.     public function createStockMovementAction(Request $request, $orderId): JsonResponse
  3157.     {
  3158.         $json = [];
  3159.         $entityManager = $this->getEntityManager();
  3160.         /** @var Order $order */
  3161.         $order = $entityManager->getRepository(Order::class)->findOneById($orderId);
  3162.         //> Order Statistics
  3163.             // Manager's Pick
  3164.             $managersPick = $this->getHiglightedFlashSaleData($request, $order->getDomain());
  3165.             // Record
  3166.             OrderStatistics::record($order, $entityManager, $managersPick);
  3167.         //< Order Statistics
  3168.         // AntiVirus comment
  3169.         if ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_SK, Domain::DOMAIN_ID_RT_CZ, Domain::DOMAIN_ID_RT_HU ]) ) {
  3170.             $antiVirusProductId = $order->getDomain()->getId() == Domain::DOMAIN_ID_RT_SK
  3171.                 ? Product::ESET_NOD32_90_DAY_TRIAL_PRODUCT_ID
  3172.                 : Product::GDATA_90_DAY_TRIAL_PRODUCT_ID;
  3173.             /**
  3174.              * @var OrderItem $antiVirusOrderItem
  3175.              */
  3176.             $antiVirusOrderItem = $order->getOrderItems()
  3177.                 ->filter(
  3178.                     function (OrderItem $orderItem) use ($antiVirusProductId) {
  3179.                         return $orderItem->getProduct()->getId() == $antiVirusProductId;
  3180.                     }
  3181.                 )
  3182.                 ->last();
  3183.             if ( $antiVirusOrderItem ) {
  3184.                 // ESET
  3185.                 if ( $antiVirusProductId == Product::ESET_NOD32_90_DAY_TRIAL_PRODUCT_ID ) {
  3186.                     $prefix = 'ESET-trial#';
  3187.                 }
  3188.                 // G DATA
  3189.                 else {
  3190.                     $prefix = 'GDATA-trial#';
  3191.                 }
  3192.                 $orderCommentEsetSerialTexts = $entityManager
  3193.                     ->createQuery("SELECT oc.text
  3194.                         FROM AtechNetCoreBundle:OrderComment oc
  3195.                         WHERE oc.type = :typeInstallation AND oc.text LIKE '" . $prefix . "%'")
  3196.                     ->setParameter('typeInstallation', OrderComment::TYPE_FOR_INSTALLATION)
  3197.                     ->getResult()
  3198.                 ;
  3199.                 $usedEsetSerialList = [];
  3200.                 foreach ( $orderCommentEsetSerialTexts as $serials ) {
  3201.                     $serialKey = explode(',', str_replace($prefix, '', $serials['text']));
  3202.                     foreach ( $serialKey as $key => $keyValue ) {
  3203.                         if ( str_contains($keyValue, 'email') ) {
  3204.                             $serialKey[$key] = substr($keyValue, 0, strpos($keyValue, "; email"));
  3205.                         }
  3206.                     }
  3207.                     $usedEsetSerialList = array_merge([], $serialKey, $usedEsetSerialList);
  3208.                 }
  3209.                 $productRepo = $entityManager->getRepository(Product::class);
  3210.                 $availableEsetStockItemList = $productRepo->getStockItems(
  3211.                     $antiVirusOrderItem->getProduct(),
  3212.                     [
  3213.                         'inStock' => true,
  3214.                         'available' => true,
  3215.                         'filterEsetCommentSerials' => $usedEsetSerialList,
  3216.                     ]
  3217.                 );
  3218.                 if ( count($availableEsetStockItemList) < $antiVirusOrderItem->getQuantity() ) {
  3219.                     $orderCommentForEsetProductText = "Serial Number WARNING: not enough serial numbers available for this order!";
  3220.                 } else {
  3221.                     $orderCommentForEsetProductText = $prefix;
  3222.                     $esetStockItemSerials = [];
  3223.                     for ( $i = 0; $i < $antiVirusOrderItem->getQuantity(); $i++ ) {
  3224.                         $esetStockItemSerials[] = $availableEsetStockItemList[$i]->getSerialNumber();
  3225.                     }
  3226.                     $orderCommentForEsetProductText .= implode(',', $esetStockItemSerials) . '; email#' . $order->getCustomer()->getEmail();
  3227.                 }
  3228.                 $orderComment = new OrderComment();
  3229.                 $orderComment->setOrder($order);
  3230.                 $orderComment->setCreatedBy($this->getCentralisUser());
  3231.                 $orderComment->setType(OrderComment::TYPE_FOR_INSTALLATION);
  3232.                 $orderComment->setText($orderCommentForEsetProductText);
  3233.                 $entityManager->persist($orderComment);
  3234.                 $entityManager->flush();
  3235.             }
  3236.         }
  3237.          // Replace Windows Attributes
  3238.         if ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_SK, Domain::DOMAIN_ID_WS_SK, Domain::DOMAIN_ID_RT_HU, Domain::DOMAIN_ID_WS_HU, Domain::DOMAIN_ID_RT_CZ, Domain::DOMAIN_ID_WS_CZ ]) ) {
  3239.             $refresh = false;
  3240.             foreach ( $order->getOrderItems() as $orderItem ) {
  3241.                 foreach ( $orderItem->getItemAttributes() as $orderItemAttribute ) {
  3242.                     if ( $orderItemAttribute->getAttributeOption()->getAttribute()->getId() == Attribute::ATTRIBUTE_ID_ACCESSORY_OS ) {
  3243.                         $windowsAttributeOption = null;
  3244.                         // Windows 10 Pro
  3245.                         if ( $orderItemAttribute->getAttributeOption()->getId() == AttributeOption::ATTRIBUTE_OPTION_ID_WINDOWS_10_PRO ) {
  3246.                             // HU
  3247.                             if ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_HU, Domain::DOMAIN_ID_WS_HU ]) ) {
  3248.                                 $windowsAttributeOption = $entityManager->getRepository(AttributeOption::class)->findOneById(AttributeOption::ATTRIBUTE_OPTION_ID_WIN10_PRO_HU);
  3249.                             }
  3250.                             // SK
  3251.                             elseif ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_SK, Domain::DOMAIN_ID_WS_SK ]) ) {
  3252.                                 $windowsAttributeOption = $entityManager->getRepository(AttributeOption::class)->findOneById(AttributeOption::ATTRIBUTE_OPTION_ID_WIN10_PRO_SK);
  3253.                             }
  3254.                             // CZ
  3255.                             if ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_CZ, Domain::DOMAIN_ID_WS_CZ ]) ) {
  3256.                                 $windowsAttributeOption = $entityManager->getRepository(AttributeOption::class)->findOneById(AttributeOption::ATTRIBUTE_OPTION_ID_WIN10_PRO_CZ);
  3257.                             }
  3258.                         }
  3259.                         // Windows 11 Pro
  3260.                         if ( $orderItemAttribute->getAttributeOption()->getId() == AttributeOption::ATTRIBUTE_OPTION_ID_WINDOWS_11_PRO ) {
  3261.                             // HU
  3262.                             if ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_HU, Domain::DOMAIN_ID_WS_HU ]) ) {
  3263.                                 $windowsAttributeOption = $entityManager->getRepository(AttributeOption::class)->findOneById(AttributeOption::ATTRIBUTE_OPTION_ID_WIN11_PRO_HU);
  3264.                             }
  3265.                             // SK
  3266.                             elseif ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_SK, Domain::DOMAIN_ID_WS_SK ]) ) {
  3267.                                 $windowsAttributeOption = $entityManager->getRepository(AttributeOption::class)->findOneById(AttributeOption::ATTRIBUTE_OPTION_ID_WIN11_PRO_SK);
  3268.                             }
  3269.                             // CZ
  3270.                             if ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_CZ, Domain::DOMAIN_ID_WS_CZ ]) ) {
  3271.                                 $windowsAttributeOption = $entityManager->getRepository(AttributeOption::class)->findOneById(AttributeOption::ATTRIBUTE_OPTION_ID_WIN11_PRO_CZ);
  3272.                             }
  3273.                         }
  3274.                         // Windows 10 Home
  3275.                         if ( $orderItemAttribute->getAttributeOption()->getId() == AttributeOption::ATTRIBUTE_OPTION_ID_WINDOWS_10_HOME ) {
  3276.                             // HU
  3277.                             if ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_HU, Domain::DOMAIN_ID_WS_HU ]) ) {
  3278.                                 $windowsAttributeOption = $entityManager->getRepository(AttributeOption::class)->findOneById(AttributeOption::ATTRIBUTE_OPTION_ID_WIN10_HOME_HU);
  3279.                             }
  3280.                             // SK
  3281.                             elseif ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_SK, Domain::DOMAIN_ID_WS_SK ]) ) {
  3282.                                 $windowsAttributeOption = $entityManager->getRepository(AttributeOption::class)->findOneById(AttributeOption::ATTRIBUTE_OPTION_ID_WIN10_HOME_SK);
  3283.                             }
  3284.                             // CZ
  3285.                             if ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_CZ, Domain::DOMAIN_ID_WS_CZ ]) ) {
  3286.                                 $windowsAttributeOption = $entityManager->getRepository(AttributeOption::class)->findOneById(AttributeOption::ATTRIBUTE_OPTION_ID_WIN10_HOME_CZ);
  3287.                             }
  3288.                         }
  3289.                         // Windows 11 Home
  3290.                         if ( $orderItemAttribute->getAttributeOption()->getId() == AttributeOption::ATTRIBUTE_OPTION_ID_WINDOWS_11_HOME ) {
  3291.                             // HU
  3292.                             if ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_HU, Domain::DOMAIN_ID_WS_HU ]) ) {
  3293.                                 $windowsAttributeOption = $entityManager->getRepository(AttributeOption::class)->findOneById(AttributeOption::ATTRIBUTE_OPTION_ID_WIN11_HOME_HU);
  3294.                             }
  3295.                             // SK
  3296.                             elseif ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_SK, Domain::DOMAIN_ID_WS_SK ]) ) {
  3297.                                 $windowsAttributeOption = $entityManager->getRepository(AttributeOption::class)->findOneById(AttributeOption::ATTRIBUTE_OPTION_ID_WIN11_HOME_SK);
  3298.                             }
  3299.                             // CZ
  3300.                             if ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_CZ, Domain::DOMAIN_ID_WS_CZ ]) ) {
  3301.                                 $windowsAttributeOption = $entityManager->getRepository(AttributeOption::class)->findOneById(AttributeOption::ATTRIBUTE_OPTION_ID_WIN11_HOME_CZ);
  3302.                             }
  3303.                         }
  3304.                         // Update
  3305.                         if ( $windowsAttributeOption ) {
  3306.                             $orderItemAttribute->setAttributeOption($windowsAttributeOption);
  3307.                             $entityManager->flush();
  3308.                             $refresh = true;
  3309.                         }
  3310.                     }
  3311.                 }
  3312.             }
  3313.             if ( $refresh ) {
  3314.                 $entityManager->refresh($order);
  3315.             }
  3316.         }
  3317.         if (
  3318.             /*$this->getEnvironment() == 'prod' &&*/
  3319.             $order &&
  3320.             is_null($order->getLastStockMovement())
  3321.         ) {
  3322.             $stockItems = $request->getSession()->get('stockItemCodes');
  3323.             $entityManager->getRepository(StockMovement::class)->createOrderStockMovement($order, $this->getCentralisUser(), $stockItems);
  3324.             $request->getSession()->remove('stockItemCodes');
  3325.         }
  3326.         return new JsonResponse($json);
  3327.     }
  3328.     /**
  3329.      * @Route("/checkout/order/{orderId}/active-campaign-sync", name="checkout_sync_active_campaign")
  3330.      * @param Request $request
  3331.      * @param int $orderId
  3332.      *
  3333.      * @return JsonResponse
  3334.      */
  3335.     public function syncActiveCampaignAction(Request $request, $orderId): JsonResponse
  3336.     {
  3337.         $json = [];
  3338.         $entityManager = $this->getEntityManager();
  3339.         $order = $entityManager->getRepository(Order::class)->findOneById($orderId);
  3340.         if (
  3341.             $this->getEnvironment() == 'prod' &&
  3342.             $order &&
  3343.             in_array($order->getDomain()->getId(), Domain::DOMAIN_IDS_FOR_ACTIVE_CAMPAIGN)
  3344.         ) {
  3345.             $activeCampaign = $this->getActiveCampaignConnect();
  3346.             if (!$this->getLoginHelper($request)->getLoggedInCustomerId()) {
  3347.                 $activeCampaign->createContactFromCentralisCustomer($order->getCustomer());
  3348.             } else {
  3349.                 $activeCampaign->updateContactFromCentralisCustomer($order->getCustomer());
  3350.             }
  3351.             // Finish abandoned cart
  3352.             if ($request->getSession()->get('abandonedCart')) {
  3353.                 $activeCampaign->finishAbandonedCart($order, $request->getSession()->get('abandonedCart'));
  3354.             } else {
  3355.                 $activeCampaign->createEcomOrderFromCentralisOrder($order);
  3356.             }
  3357.             $request->getSession()->remove('abandonedCart');
  3358.         }
  3359.         return new JsonResponse($json);
  3360.     }
  3361.     /**
  3362.      * @Route("/checkout/order-summary-ajax", name="checkout_order_summary_ajax", defaults={"_locale":""})
  3363.      * @Route("/{_locale<%supported_locales%>?}/checkout/order-summary-ajax", name="checkout_order_summary_ajax_locale", defaults={"_locale":""})
  3364.      * @param Request $request
  3365.      * @return JsonResponse
  3366.      */
  3367.     public function orderSummaryAjaxAction(Request $request): JsonResponse
  3368.     {
  3369.         $cart = $this->getCart($request->getSession()->get('cartId'));
  3370.         $orderSummary = $this->orderSummary($cart, $request);
  3371.         return new JsonResponse($orderSummary);
  3372.     }
  3373.     /**
  3374.      * @Route("/checkout/pay-at-delivery", name="checkout_pay_at_delivery", defaults={"_locale":""})
  3375.      * @Route("/{_locale<%supported_locales%>?}/checkout/pay-at-delivery", name="checkout_pay_at_delivery_locale", defaults={"_locale":""})
  3376.      *
  3377.      * @param Request $request
  3378.      * @return RedirectResponse
  3379.      * @throws NotSupported
  3380.      * @throws ORMException
  3381.      * @throws \Doctrine\ORM\ORMException
  3382.      * @throws OptimisticLockException
  3383.      */
  3384.     public function payAtDeliveryAction(Request $request): RedirectResponse
  3385.     {
  3386.         $entityManager = $this->getEntityManager();
  3387.         // Order ID - Session
  3388.         if ($request->getSession()->has('updateOrderId')) {
  3389.             $orderId = (int)$request->getSession()->get('updateOrderId');
  3390.         } else {
  3391.             $orderId = 0;
  3392.         }
  3393.         $_orderId = (int)$request->query->get('orderId');
  3394.         if ($orderId != $_orderId) {
  3395.             return $this->redirectToRoute('not_found');
  3396.         }
  3397.         $orderRepository = $entityManager->getRepository(Order::class);
  3398.         $multiStore = $this->getMultiStoreHelper($request);
  3399.         /**
  3400.          * @var Order $order
  3401.          */
  3402.         $order = $orderRepository->findOneById($orderId);
  3403.         if (empty($order)) {
  3404.             return $this->redirectToRoute('not_found');
  3405.         }
  3406.         if ($order->getPaymentType() == PaymentType::CashOnDelivery->value) {
  3407.             return $this->redirectToRoute('checkout_success_update');
  3408.         }
  3409.         $order->setPaymentType(PaymentType::CashOnDelivery->value);
  3410.         $order->setPaymentStatus(Order::PaymentStatus_Pending);
  3411.         $domainPaymentType = $entityManager->getRepository(DomainPaymentType::class)->findOneBy([
  3412.             'domain' => $multiStore->getDomainId(),
  3413.             'type' => PaymentType::CashOnDelivery->value,
  3414.         ]);
  3415.         $order->setPaymentPrice($domainPaymentType->getPrice());
  3416.         if ((float)$order->getPaymentPrice() > 0) {
  3417.             $product = $entityManager->getRepository(Product::class)->findOneById(Product::CASH_ON_DELIVERY_PRODUCT_ID);
  3418.             $orderItem = new OrderItem();
  3419.             $orderItem->setProduct($product);
  3420.             $orderItem->setPrice((float)$order->getPaymentPrice());
  3421.             $orderItem->setQuantity(1);
  3422.             $orderItem->setPosition($order->getOrderItems()->count());
  3423.             $orderItem->setOrder($order);
  3424.             // Save Order Product
  3425.             $entityManager->persist($orderItem);
  3426.             $entityManager->flush();
  3427.             // Add cash on delivery to stock movement
  3428.             $stockMovement = $order->getStockMovements()->first();
  3429.             if ($stockMovement) {
  3430.                 $stockMovementItem = new StockMovementItem();
  3431.     
  3432.                 $stockMovementItem->setMovement($stockMovement);
  3433.                 $stockMovementItem->setProduct($product);
  3434.                 $stockMovementItem->setPrice((float)$order->getPaymentPrice() / (1 + $order->getDomain()->getVat() / 100));
  3435.                 $stockMovementItem->setOrderItem($orderItem);
  3436.                 $stockMovementItem->setQuantity(1);
  3437.     
  3438.                 $entityManager->persist($stockMovementItem);
  3439.                 $entityManager->flush();
  3440.     
  3441.                 $entityManager->refresh($stockMovement);
  3442.     
  3443.                 $totalPrice = 0;
  3444.                 foreach ($stockMovement->getMovementItems() as $movementItem) {
  3445.                     $totalPrice += $movementItem->getTotalPricePerItem();
  3446.                 }
  3447.     
  3448.                 $stockMovement->setTotalPrice($totalPrice);
  3449.     
  3450.                 $entityManager->flush();
  3451.             }
  3452.         }
  3453.         $order->setFullPrice();
  3454.         $entityManager->flush();
  3455.         return $this->redirectToRoute('checkout_success_update');
  3456.     }
  3457.     /**
  3458.      * @Route("/checkout/pay-bank-transfer", name="checkout_pay_bank_transfer", defaults={"_locale":""})
  3459.      * @Route("/{_locale<%supported_locales%>?}/checkout/pay-bank-transfer", name="checkout_pay_bank_transfer_locale", defaults={"_locale":""})
  3460.      *
  3461.      * @param Request $request
  3462.      * @return RedirectResponse|void
  3463.      * @throws NotSupported
  3464.      */
  3465.     public function payVieBankTransferAction(Request $request)
  3466.     {
  3467.         $entityManager = $this->getEntityManager();
  3468.         // Order ID - Session
  3469.         if ($request->getSession()->has('updateOrderId')) {
  3470.             $orderId = (int)$request->getSession()->get('updateOrderId');
  3471.         } else {
  3472.             $orderId = 0;
  3473.         }
  3474.         $_orderId = (int)$request->query->get('orderId');
  3475.         if ($orderId != $_orderId) {
  3476.             return $this->redirectToRoute('not_found');
  3477.         }
  3478.         $orderRepository = $entityManager->getRepository(Order::class);
  3479.         /**
  3480.          * @var Order $order
  3481.          */
  3482.         $order = $orderRepository->findOneById($orderId);
  3483.         if (empty($order)) {
  3484.             return $this->redirectToRoute('not_found');
  3485.         }
  3486.         if (in_array($order->getPaymentType(), [PaymentType::BankTransfer->value, PaymentType::BankTransfer3Percent->value])) {
  3487.             return $this->redirectToRoute('checkout_success_update');
  3488.         }
  3489.         $order->setPaymentType(PaymentType::BankTransfer->value);
  3490.         $order->setPaymentStatus(Order::PaymentStatus_Pending);
  3491.         $entityManager->flush();
  3492.         return $this->redirectToRoute('checkout_success_update');
  3493.     }
  3494.     /**
  3495.      * @Route("/checkout/success/update", name="checkout_success_update", defaults={"_locale":""})
  3496.      * @Route("/{_locale<%supported_locales%>?}/checkout/success/update", name="checkout_success_update_locale", defaults={"_locale":""})
  3497.      *
  3498.      * @param Request $request
  3499.      * @return RedirectResponse|Response
  3500.      * @throws \Exception
  3501.      */
  3502.     public function successUpdateAction(Request $request)
  3503.     {
  3504.         $data = [];
  3505.         $data['hideChat'] = true;
  3506.         // Order ID - Session
  3507.         if ($request->getSession()->has('updateOrderId')) {
  3508.             $orderId = (int)$request->getSession()->get('updateOrderId');
  3509.         } else {
  3510.             $orderId = 0;
  3511.         }
  3512.         if ($orderId > 0) {
  3513.             $entityManager = $this->getEntityManager();
  3514.             $productHelper = $this->getProductHelper($request);
  3515.             $order = $entityManager->getRepository(Order::class)->findOneById($orderId);
  3516.             if ($order) {
  3517.                 $domain = $order->getDomain();
  3518.                 $orderHelper = $this->getOrderHelper($request);
  3519.                 $emailSendingResult = $orderHelper->sendOrderEmail(
  3520.                     $order,
  3521.                     $productHelper,
  3522.                     $this->getContactInfos(),
  3523.                     $this->getWhiteListCouponCodes(),
  3524.                     true
  3525.                 );
  3526.                 $data['orderId'] = $order->getId();
  3527.                 $data['email'] = $order->getBillingEmail();
  3528.                 $data['domainName'] = $domain->getName();
  3529.                 $data['orderTotal'] = $emailSendingResult['total'];
  3530.                 $data['orderTax'] = round($data['orderTotal'] - $order->getTaxOutOfFullPrice(), 2);
  3531.                 switch ($domain->getCurrency()) {
  3532.                     case 'Ft':
  3533.                         $data['currencyCode'] = 'HUF';
  3534.                         break;
  3535.                     case 'Kč':
  3536.                         $data['currencyCode'] = 'CZK';
  3537.                         break;
  3538.                     case '€':
  3539.                         $data['currencyCode'] = 'EUR';
  3540.                         break;
  3541.                     default:
  3542.                         $data['currencyCode'] = 'EUR';
  3543.                 }
  3544.                 $data['surveyQuestions'] = [];
  3545.                 $data['show_upsell'] = false;
  3546.                 $data['externalPayment'] = null;
  3547.                 $data['gopay_data'] = null;
  3548.                 $data['simplepay_data'] = null;
  3549.                 $data['payAtDelivery'] = true;
  3550.                 if ($request->getSession()->has('checkout')) {
  3551.                     $request->getSession()->remove('checkout');
  3552.                 }
  3553.                 if ($request->getSession()->has('paymentOrderId')) {
  3554.                     $request->getSession()->remove('paymentOrderId');
  3555.                 }
  3556.                 if ($request->getSession()->has('updateOrderId')) {
  3557.                     $request->getSession()->remove('updateOrderId');
  3558.                 }
  3559.                 $data['header'] = $this->getHeader($request);
  3560.                 $data['footer'] = $this->getFooter($request);
  3561.                 $data['contentBottom'] = $this->getContentBottom($request);
  3562.                 return $this->render('AtechNetCoreBundle/Checkout/success.html.twig', $data);
  3563.             }
  3564.         }
  3565.         if ($request->getSession()->has('checkout')) {
  3566.             $request->getSession()->remove('checkout');
  3567.         }
  3568.         if ($request->getSession()->has('paymentOrderId')) {
  3569.             $request->getSession()->remove('paymentOrderId');
  3570.         }
  3571.         if ($request->getSession()->has('updateOrderId')) {
  3572.             $request->getSession()->remove('updateOrderId');
  3573.         }
  3574.         return $this->redirectToRoute('cart_show');
  3575.     }
  3576.     /**
  3577.      * @Route("/checkout/instacash-webhook/{token}", name="checkout_instacash_webhook", defaults={"_locale":""})
  3578.      * @Route("/{_locale<%supported_locales%>?}/checkout/instacash-webhook/{token}", name="checkout_instacash_webhook_locale", defaults={"_locale":""})
  3579.      *
  3580.      * @param Request $request
  3581.      * @param string $token
  3582.      * @return JsonResponse
  3583.      * @throws NotSupported
  3584.      * @throws ORMException
  3585.      * @throws OptimisticLockException
  3586.      */
  3587.     public function intacashWebhookAction(Request $request, string $token): JsonResponse
  3588.     {
  3589.         $instacashToken = '328943154gjfvr-emvdscf894j31gt3df9e-wqruf4938tfds13t';
  3590.         if ($token != $instacashToken) {
  3591.             throw new AccessDeniedException('Access denied');
  3592.         }
  3593.         $response = 'error on sync';
  3594.         $requestContent = $request->getContent();
  3595.         $requestBody = json_decode($requestContent, true);
  3596.         if (isset($requestBody['application']['status']) && in_array($requestBody['application']['status'], Instacash::getApplicationStatusChoices())) {
  3597.             $status = $requestBody['application']['status'];
  3598.             $applicationId = $requestBody['application']['id'];
  3599.             $transactions = [];
  3600.             if (isset($requestBody['deal']) && isset($requestBody['deal']['transactions'])) {
  3601.                 $transactions = $requestBody['deal']['transactions'];
  3602.             }
  3603.             $orderApplicationIdStatus = $this->getEntityManager()->getRepository(OrderSetting::class)->findOneBy([
  3604.                 'type' => OrderSetting::TYPE_INSTACASH_APPLICATION_ID,
  3605.                 'value' => $applicationId,
  3606.             ]);
  3607.             if ($orderApplicationIdStatus) {
  3608.                 $order = $orderApplicationIdStatus->getOrder();
  3609.                 $entityManager = $this->getEntityManager();
  3610.                 $orderApplicationStatusSetting = $order->getInstacashApplicationStatusSetting();
  3611.                 if ((!$orderApplicationStatusSetting && $status == 'COMPLETED') ||
  3612.                     ($orderApplicationStatusSetting && $orderApplicationStatusSetting->getValue() != 'COMPLETED' && $status == 'COMPLETED')) {
  3613.                     $order->setPaymentStatus(Order::PAYMENT_STATUS_PARTIAL);
  3614.                 }
  3615.                 if ($status == 'COMPLETED' && count($transactions) > 0) {
  3616.                     $paid = 0.0;
  3617.                     $alreadyAddedPayments = $order->getInstacashPaymentSettings();
  3618.                     foreach ($transactions as $transaction) {
  3619.                         if ($transaction['status'] != 'PAID') {
  3620.                             continue;
  3621.                         }
  3622.                         $transactionSum = (float)$transaction['sum'];
  3623.                         $paid = $paid + $transactionSum;
  3624.                         $createPaymentSetting = true;
  3625.                         $paymentAlreadyAdded = false;
  3626.                         foreach ($alreadyAddedPayments as $key => $alreadyAddedPayment) {
  3627.                             if ($alreadyAddedPayment->getValue() == $transactionSum && !$paymentAlreadyAdded) {
  3628.                                 $createPaymentSetting = false;
  3629.                                 unset($alreadyAddedPayments[$key]);
  3630.                                 $paymentAlreadyAdded = true;
  3631.                             }
  3632.                         }
  3633.                         if ($createPaymentSetting) {
  3634.                             $instacashPaymentSetting = OrderSetting::createSetting(
  3635.                                 $order,
  3636.                                 OrderSetting::TYPE_INSTACASH_PAYMENT,
  3637.                                 $transactionSum
  3638.                             );
  3639.                             $entityManager->persist($instacashPaymentSetting);
  3640.                             if ($order->getDomain()->getId() == Domain::DOMAIN_ID_RT_SK) {
  3641.                                 if (count($transactions) > 1 && $order->getDocuments()->count() > 0) {
  3642.                                     $document = $order->getDocuments()->first();
  3643.                                     $documentPayment = new DocumentPayment();
  3644.                                     $sequence = '';
  3645.                                     if (isset($transaction['seq'])) {
  3646.                                         $sequence = $transaction['seq'];
  3647.                                     }
  3648.                                     $centralisUser = $entityManager->getRepository(User::class)->findOneById(User::CENTRALIS_USER_ID);
  3649.                                     $documentPayment->setPaymentSource(DocumentPayment::INSTACASH);
  3650.                                     $documentPayment->setPaymentDate(new \DateTime());
  3651.                                     $documentPayment->setNote('Instacash payment ' . $sequence);
  3652.                                     $documentPayment->setAmount($transactionSum);
  3653.                                     $documentPayment->setCreatedBy($centralisUser);
  3654.                                     $documentPayment->setDocument($document);
  3655.                                     $entityManager->persist($documentPayment);
  3656.                                 }
  3657.                             }
  3658.                             if ($order->getDomain()->getId() == Domain::DOMAIN_ID_RT_HU) {
  3659.                                 if (count($transactions) > 1 && $order->getBillingoDocuments()->count() > 0) {
  3660.                                     $customerBillingoData = $order->getBillingoDocuments()->first();
  3661.                                     $billingoPayment = new BillingoPayment();
  3662.                                     $sequence = '';
  3663.                                     if (isset($transaction['seq'])) {
  3664.                                         $sequence = $transaction['seq'];
  3665.                                     }
  3666.                                     $billingoPayment->setPaymentSource(DocumentPayment::INSTACASH);
  3667.                                     $billingoPayment->setPaymentDate(new \DateTime());
  3668.                                     $billingoPayment->setNote('Instacash payment ' . $sequence);
  3669.                                     $billingoPayment->setAmount($transactionSum);
  3670.                                     $centralisUser = $entityManager->getRepository(User::class)->findOneById(User::CENTRALIS_USER_ID);
  3671.                                     $entityManager->getRepository(BillingoPayment::class)->createBillingoPayment($this->getBillingo(), $customerBillingoData, $billingoPayment, $centralisUser);
  3672.                                 }
  3673.                             }
  3674.                         }
  3675.                     }
  3676.                     if ($paid == $order->getFullPrice()) {
  3677.                         $order->setPaymentStatus(Order::PAYMENT_STATUS_PAID);
  3678.                     } elseif ($paid > 0) {
  3679.                         $order->setPaymentStatus(Order::PAYMENT_STATUS_PARTIAL);
  3680.                     } else {
  3681.                         $order->setPaymentStatus(Order::PAYMENT_STATUS_PENDING);
  3682.                     }
  3683.                 }
  3684.                 if ($orderApplicationStatusSetting) {
  3685.                     $orderApplicationStatusSetting->setValue($status);
  3686.                 } else {
  3687.                     $orderSettingApplicationStatus = OrderSetting::createSetting(
  3688.                         $order,
  3689.                         OrderSetting::TYPE_INSTACASH_APPLICATION_STATUS,
  3690.                         $status
  3691.                     );
  3692.                     $entityManager->persist($orderSettingApplicationStatus);
  3693.                 }
  3694.                 $entityManager->flush();
  3695.                 $response = 'synced';
  3696.             }
  3697.         }
  3698.         
  3699.         return new JsonResponse($response);
  3700.     }
  3701.     /**
  3702.      * @Route("/checkout/milpay-webhook/{token}", name="checkout_milpay_webhook", defaults={"_locale":""})
  3703.      * @Route("/{_locale<%supported_locales%>?}/checkout/milpay-webhook/{token}", name="checkout_milpay_webhook_locale", defaults={"_locale":""})
  3704.      *
  3705.      * @param Request $request
  3706.      * @param string $token
  3707.      * @return JsonResponse
  3708.      * @throws NotSupported
  3709.      * @throws ORMException
  3710.      * @throws OptimisticLockException
  3711.      */
  3712.     public function milpayWebhookAction(Request $request, string $token): JsonResponse
  3713.     {
  3714.         if ($token != Milpay::MILPAY_WEBHOOK_TOKE) {
  3715.             throw new AccessDeniedException('Access denied');
  3716.         }
  3717.         $response = 'error on sync';
  3718.         $requestContent = $request->getContent();
  3719.         $requestBody = json_decode($requestContent, true);
  3720.         if (isset($requestBody['application']['status']) && in_array($requestBody['application']['status'], Milpay::getApplicationStatusChoices())) {
  3721.             $status = $requestBody['application']['status'];
  3722.             $applicationId = $requestBody['application']['id'];
  3723.             $transactions = [];
  3724.             if (isset($requestBody['deal']) && isset($requestBody['deal']['transactions'])) {
  3725.                 $transactions = $requestBody['deal']['transactions'];
  3726.             }
  3727.             $orderApplicationIdStatus = $this->getEntityManager()->getRepository(OrderSetting::class)->findOneBy([
  3728.                 'type'  => OrderSetting::TYPE_MILPAY_APPLICATION_ID,
  3729.                 'value' => $applicationId,
  3730.             ]);
  3731.             if ($orderApplicationIdStatus) {
  3732.                 $order = $orderApplicationIdStatus->getOrder();
  3733.                 $entityManager = $this->getEntityManager();
  3734.                 $orderApplicationStatusSetting = $order->getMilpayApplicationStatusSetting();
  3735.                 /*if ((!$orderApplicationStatusSetting && $status == 'COMPLETED') ||
  3736.                     ($orderApplicationStatusSetting && $orderApplicationStatusSetting->getValue() != 'COMPLETED' && $status == 'COMPLETED')) {
  3737.                     $order->setPaymentStatus(Order::PAYMENT_STATUS_PAID);
  3738.                 }*/
  3739.                 if ($status == 'COMPLETED' && count($transactions) > 0) {
  3740.                     $alreadyAddedPayments = $order->getMilpayPaymentSettings();
  3741.                     if (empty($alreadyAddedPayments)) {
  3742.                         foreach ($transactions as $transaction) {
  3743.                             if ($transaction['status'] != 'PAID') {
  3744.                                 continue;
  3745.                             }
  3746.                             $milpayPaymentSetting = OrderSetting::createSetting(
  3747.                                 $order,
  3748.                                 OrderSetting::TYPE_MILPAY_PAYMENT,
  3749.                                 $order->getFullPrice()
  3750.                             );
  3751.                             $entityManager->persist($milpayPaymentSetting);
  3752.                             $order->setPaymentStatus(Order::PAYMENT_STATUS_PAID);
  3753.                             break;
  3754.                         }
  3755.                     }
  3756.                 }
  3757.                 if ($orderApplicationStatusSetting) {
  3758.                     $orderApplicationStatusSetting->setValue($status);
  3759.                 } else {
  3760.                     $orderSettingApplicationStatus = OrderSetting::createSetting(
  3761.                         $order,
  3762.                         OrderSetting::TYPE_MILPAY_APPLICATION_STATUS,
  3763.                         $status
  3764.                     );
  3765.                     $entityManager->persist($orderSettingApplicationStatus);
  3766.                 }
  3767.                 $entityManager->flush();
  3768.                 $response = 'synced';
  3769.             }
  3770.         }
  3771.         return new JsonResponse($response);
  3772.     }
  3773.     private function remove_emoji($string)
  3774.     {
  3775.         $symbols = "\x{1F100}-\x{1F1FF}" // Enclosed Alphanumeric Supplement
  3776.             . "\x{1F300}-\x{1F5FF}" // Miscellaneous Symbols and Pictographs
  3777.             . "\x{1F600}-\x{1F64F}" //Emoticons
  3778.             . "\x{1F680}-\x{1F6FF}" // Transport And Map Symbols
  3779.             . "\x{1F900}-\x{1F9FF}" // Supplemental Symbols and Pictographs
  3780.             . "\x{2600}-\x{26FF}" // Miscellaneous Symbols
  3781.             . "\x{2700}-\x{27BF}"; // Dingbats
  3782.         return preg_replace('/[' . $symbols . ']+/u', '', $string);
  3783.     }
  3784.     public function klarnaAuthorizationCallback(int $domainId, Order $order, Request $request)
  3785.     {
  3786.         $orderSetting = $order->getKlarnaPaymentSessionIdSetting(false);
  3787.         $klarna = $this->getKlarna($domainId, $request, $order->getShippingCountry());
  3788.         $klarnaOrder = $klarna->createKlarnaOrder($klarna->getKlarnaSession($orderSetting->getValue()));
  3789.         $klarna->updateKlarnaMerchantReference($order->getId(), $klarnaOrder['order_id']);
  3790.         $getKlarnaOrderDetails = $klarna->getKlarnaOrder($klarnaOrder['order_id']);
  3791.         $sessionData = $klarna->getKlarnaSession($orderSetting->getValue());
  3792.         if ($sessionData['status'] == Klarna::ACCEPTED_STATUS) {
  3793.             $order->setPaymentStatus(Order::PAYMENT_STATUS_PAID);
  3794.             $this->getEntityManager()->persist($order);
  3795.             $klarnaOrderSettingOrderId = new OrderSetting();
  3796.             $klarnaOrderSettingOrderId->setOrder($order);
  3797.             $klarnaOrderSettingOrderId->setType(OrderSetting::TYPE_KLARNA_ORDER_ID);
  3798.             $klarnaOrderSettingOrderId->setValue($getKlarnaOrderDetails['klarna_reference']);
  3799.             $this->getEntityManager()->persist($klarnaOrderSettingOrderId);
  3800.             foreach ($order->getAllKlarnaPaymentSessionIdSettings() as $setting) {
  3801.                 $klarna->deleteKlarnaSession($setting->getValue());
  3802.                 $this->getEntityManager()->remove($setting);
  3803.             }
  3804.             $this->getEntityManager()->flush();
  3805.         }
  3806.         return [
  3807.             'status' => $sessionData['status'],
  3808.             'orderID' => $getKlarnaOrderDetails['klarna_reference'],
  3809.         ];
  3810.     }
  3811.     /**
  3812.      * @param Domain $domain
  3813.      * @return float|int|mixed|string
  3814.      */
  3815.     public function getActiveFreeShippingTypes(Domain $domain): mixed
  3816.     {
  3817.         return $this->getEntityManager()->createQueryBuilder()
  3818.             ->select('dst')
  3819.             ->from('AtechNetCoreBundle:DomainShippingType', 'dst')
  3820.             ->where('dst.domain = :domain')
  3821.             ->andWhere('dst.freeShippingStartDate IS NOT NULL AND dst.freeShippingEndDate IS NOT NULL')
  3822.             ->andWhere('dst.freeShippingStartDate <= :now AND dst.freeShippingEndDate >= :now')
  3823.             ->setParameters([
  3824.                 'domain' => $domain->getId(),
  3825.                 'now' => (new \DateTime())->format('Y-m-d'),
  3826.             ])
  3827.             ->getQuery()
  3828.             ->getResult();
  3829.     }
  3830.     /**
  3831.      * @param Domain $domain
  3832.      * @return float|int|mixed|string
  3833.      */
  3834.     public function getActiveFreeShippingTypeIds(Domain $domain): mixed
  3835.     {
  3836.         return $this->getEntityManager()->createQueryBuilder()
  3837.             ->select('dst.id')
  3838.             ->from('AtechNetCoreBundle:DomainShippingType', 'dst')
  3839.             ->where('dst.domain = :domain')
  3840.             ->andWhere('dst.freeShippingStartDate IS NOT NULL AND dst.freeShippingEndDate IS NOT NULL')
  3841.             ->andWhere('dst.freeShippingStartDate <= :now AND dst.freeShippingEndDate >= :now')
  3842.             ->setParameters([
  3843.                 'domain' => $domain->getId(),
  3844.                 'now' => (new \DateTime())->format('Y-m-d'),
  3845.             ])
  3846.             ->getQuery()
  3847.             ->getSingleColumnResult();
  3848.     }
  3849.     //PAYPAL
  3850.     /**
  3851.      * @Route("/checkout/paypal/create/order", name="checkout_paypal_create_order")
  3852.      */
  3853.     public function paypalCreteOrderAction(Request $request): JsonResponse
  3854.     {
  3855.         $content = $request->getContent();
  3856.         $data = json_decode($content, true);
  3857.         $entityManager = $this->getEntityManager();
  3858.         if (isset($data['cart']) && isset($data['amount']) && isset($data['currency']) && isset($data['centralisOrderId'])) {
  3859.             header('Content-Type: application/json');
  3860.             try {
  3861.                 $orderResponse = $this->getPaypal()->createOrder($data['amount'], $data['currency']);
  3862.                 $order = $entityManager->find(Order::class, $data['centralisOrderId']);
  3863.                 $orderSetting = new OrderSetting();
  3864.                 $orderSetting->setOrder($order);
  3865.                 $orderSetting->setType(OrderSetting::TYPE_PAYPAL_ORDER_ID);
  3866.                 $orderSetting->setValue($orderResponse['jsonResponse']->getId());
  3867.                 $entityManager->persist($orderSetting);
  3868.                 $entityManager->flush();
  3869.                 return new JsonResponse($orderResponse['jsonResponse']);
  3870.             } catch (Exception $e) {
  3871.                 return new JsonResponse(['error' => $e->getMessage()], 500);
  3872.             }
  3873.         }
  3874.         // If 'cart' does not exist in the payload
  3875.         return new JsonResponse([
  3876.             'success' => false,
  3877.             'message' => 'No cart data received',
  3878.         ], 400);
  3879.     }
  3880.     /**
  3881.      * @Route("/checkout/paypal/capture/order/{orderId}", name="checkout_paypal_capture_order")
  3882.      */
  3883.     public function paypalCaptureOrderAction(Request $request, string $orderId): JsonResponse
  3884.     {
  3885.         $entityManager = $this->getEntityManager();
  3886.         try {
  3887.             $captureResponse = $this->getPaypal()->captureOrder($orderId);
  3888.             $centralisOrder = $entityManager->getRepository(OrderSetting::class)->findOneBy([
  3889.                 'value' => $orderId,
  3890.             ])?->getOrder();
  3891.             if (isset($captureResponse['jsonResponse']) && !is_array($captureResponse['jsonResponse'])){
  3892.                 if ($centralisOrder) {
  3893.                     $status = $captureResponse['jsonResponse']->getStatus();
  3894.                     $transactionId = $captureResponse['jsonResponse']
  3895.                         ?->getPurchaseUnits()[0]
  3896.                         ?->getPayments()
  3897.                         ?->getCaptures()[0]
  3898.                         ?->getId() ?? null;
  3899.                     if ($status == Paypal::SUCCESS_STATUS) {
  3900.                         $centralisOrder->setPaymentStatus(Order::PAYMENT_STATUS_PAID);
  3901.                         if ($transactionId) {
  3902.                             $entityManager->persist(OrderSetting::createSetting(
  3903.                                 $centralisOrder,
  3904.                                 OrderSetting::TYPE_PAYPAL_TRANSACTION_ID,
  3905.                                 $transactionId
  3906.                             ));
  3907.                         }
  3908.                         $entityManager->flush();
  3909.                     }
  3910.                     else {
  3911.                         $this->getKlaviyoConnect($request)->createNewOrderIsNotPayedPaypalEvent($centralisOrder);
  3912.                     }
  3913.                 }
  3914.             }
  3915.             return new JsonResponse($captureResponse['jsonResponse']);
  3916.         } catch (Exception $e) {
  3917.             return new JsonResponse(['error' => $e->getMessage()], 500);
  3918.         }
  3919.     }
  3920.     /**
  3921.      * @Route("/checkout/klarna/cancel/order/{orderId}", name="checkout_klarna_cancel_order")
  3922.      * @param Request $request
  3923.      * @param int $orderId
  3924.      * @return RedirectResponse
  3925.      */
  3926.     public function calcelOrder(Request $request, int $orderId): RedirectResponse
  3927.     {
  3928.         $entityManager = $this->getEntityManager();
  3929.         $order = $entityManager->find(Order::class, $orderId);
  3930.         $order->setStatus(Order::STATUS_CANCELED);
  3931.         $stockMovementRepo = $entityManager->getRepository(StockMovement::class);
  3932.         foreach ($order->getStockMovements() as $stockMovement) {
  3933.             $stockMovementRepo->deleteStockMovement($stockMovement);
  3934.         }
  3935.         $entityManager->flush();
  3936.         $request->getSession()->set('canceledOrderId', $orderId);
  3937.         return $this->redirectToRoute('checkout_success');
  3938.     }
  3939. }