src/Controller/Admin/OfferController.php line 2485

Open in your IDE?
  1. <?php
  2. namespace Slivki\Controller\Admin;
  3. use DateTimeImmutable;
  4. use Doctrine\ORM\EntityManager;
  5. use GeoIO\Dimension;
  6. use GeoIO\Geometry\Factory;
  7. use Imagine\Gd\Imagine;
  8. use Imagine\Image\Box;
  9. use Imagine\Image\Point;
  10. use Slivki\Command\SavePurchaseCountCommand;
  11. use Slivki\Dao\InteriorGallery\InteriorGalleryDaoInterface;
  12. use Slivki\Dao\Offer\FoodOfferExtension\FoodOfferExtensionDaoInterface;
  13. use Slivki\Dao\Offer\MobApiOfferDaoInterface;
  14. use Slivki\Dto\FoodCourt\DeliveryOneDayWorkingTimeDto;
  15. use Slivki\Entity\AntiTag;
  16. use Slivki\Entity\BankCurrency;
  17. use Slivki\Entity\Category;
  18. use Slivki\Entity\City;
  19. use Slivki\Entity\CityArea;
  20. use Slivki\Entity\Comment;
  21. use Slivki\Entity\Director;
  22. use Slivki\Entity\EntityDescription;
  23. use Slivki\Entity\EntityDescriptionSliderImage;
  24. use Slivki\Entity\EntityOption;
  25. use Slivki\Entity\FoodOfferExtension;
  26. use Slivki\Entity\FoodOfferOptionExtension;
  27. use Slivki\Entity\GeoLocation;
  28. use Slivki\Entity\GiftCertificate;
  29. use Slivki\Entity\GiftCertificateCategory;
  30. use Slivki\Entity\GiftCertificateGiftCategory;
  31. use Slivki\Entity\GiftCertificateTag;
  32. use Slivki\Entity\HotFeed;
  33. use Slivki\Entity\ItemOfferExtension;
  34. use Slivki\Entity\MallGeoLocation;
  35. use Slivki\Entity\Media;
  36. use Slivki\Entity\Media\OfferDeliveryZoneMedia;
  37. use Slivki\Entity\Media\OfferMapLogoMedia;
  38. use Slivki\Entity\Media\OnlineOrderPopupLogoMedia;
  39. use Slivki\Entity\MediaType;
  40. use Slivki\Entity\Offer;
  41. use Slivki\Entity\OfferCategoryPosition;
  42. use Slivki\Entity\OfferCodePool;
  43. use Slivki\Entity\OfferExtension;
  44. use Slivki\Entity\OfferExtensionCategory;
  45. use Slivki\Entity\OfferExtensionOnlineCategory;
  46. use Slivki\Entity\OfferOrder;
  47. use Slivki\Entity\OfferOrderDetails;
  48. use Slivki\Entity\OfferPayedCategory;
  49. use Slivki\Entity\OfferPayedCategoryMobile;
  50. use Slivki\Entity\OfferProposal;
  51. use Slivki\Entity\OnlineOrderSettings;
  52. use Slivki\Entity\OperatorActionLog;
  53. use Slivki\Entity\PhoneNumber;
  54. use Slivki\Entity\ProductFastDelivery;
  55. use Slivki\Entity\RenewedOffer;
  56. use Slivki\Entity\Seo;
  57. use Slivki\Entity\SiteSettings;
  58. use Slivki\Entity\User;
  59. use Slivki\Entity\UserGroup;
  60. use Slivki\Message\Command\Admin\Category\OfferExtensionOnlineCategory\SaveOfferExtensionOnlineCategoryOfferRelationsCommand;
  61. use Slivki\Message\Command\Admin\Offer\EditOfferNoteCommand;
  62. use Slivki\Message\Command\OfferStatusLog\CreateOfferStatusLogCommand;
  63. use Slivki\Message\Query\Admin\Offer\OfferExtension\OfferExtensionVisibility\GetOfferExtensionVisibilitiesQuery;
  64. use Slivki\Messenger\Query\QueryBusInterface;
  65. use Slivki\Repository\Category\Admin\CategoryRepositoryInterface;
  66. use Slivki\Repository\Category\OfferExtensionOnlineCategory\Admin\OfferExtensionOnlineCategoryRepositoryInterface;
  67. use Slivki\Repository\City\Admin\CityRepositoryInterface;
  68. use Slivki\Repository\DeliverySchedule\Admin\DeliveryScheduleRepositoryInterface;
  69. use Slivki\Repository\GiftCertificate\GiftCertificateGroup\Admin\GiftCertificateGroupRepositoryInterface;
  70. use Slivki\Repository\GiftCertificateCategory\Admin\GiftCertificateCategoryRepositoryInterface;
  71. use Slivki\Repository\GiftCertificateGiftCategory\Admin\GiftCertificateGiftCategoryRepositoryInterface;
  72. use Slivki\Repository\Offer\Admin\FoodDeliveryZoneRepositoryInterface;
  73. use Slivki\Repository\OfferRepository;
  74. use Slivki\Repository\ProductFastDeliveryRepository;
  75. use Slivki\Repository\SaleRepository;
  76. use Slivki\Repository\SeoRepository;
  77. use Slivki\Serializer\Config\SerializerConfig;
  78. use Slivki\Services\CacheService;
  79. use Slivki\Services\CategoryBoxCacheService;
  80. use Slivki\Services\FoodCourt\DeliveryWorkingTimeService;
  81. use Slivki\Services\ImageService;
  82. use Slivki\Services\Mailer;
  83. use Slivki\Services\Offer\CodePoolService;
  84. use Slivki\Services\Offer\GalleryVideo\VideoPackageDtoGetter;
  85. use Slivki\Services\Offer\GalleryVideo\VideoPackageSaver;
  86. use Slivki\Services\Offer\OfferCacheService;
  87. use Slivki\Services\Offer\OfferFoodDeliveryZoneSaver;
  88. use Slivki\Services\Offer\OfferNoteGetter;
  89. use Slivki\Services\Offer\OfferResponseCacheService;
  90. use Slivki\Services\OnlineOrderSettings\ReceivingOrdersScheduleService;
  91. use Slivki\Services\Seo\SeoResourceService;
  92. use Slivki\Util\CommonUtil;
  93. use Slivki\Util\Iiko\AbstractDelivery;
  94. use Slivki\Util\Logger;
  95. use Symfony\Component\Filesystem\Filesystem;
  96. use Symfony\Component\HttpFoundation\JsonResponse;
  97. use Symfony\Component\HttpFoundation\Request;
  98. use Symfony\Component\HttpFoundation\Response;
  99. use Symfony\Component\HttpFoundation\StreamedResponse;
  100. use Symfony\Component\HttpKernel\KernelInterface;
  101. use Symfony\Component\Messenger\MessageBusInterface;
  102. use Symfony\Component\Routing\Annotation\Route;
  103. use Symfony\Component\Security\Core\Role\Role;
  104. use Symfony\Component\Serializer\SerializerInterface;
  105. use Symfony\Component\Validator\Validator\ValidatorInterface;
  106. use function array_map;
  107. use function explode;
  108. use function in_array;
  109. use function random_int;
  110. class OfferController extends AdminController
  111. {
  112.     public const BELARUS_PHONE_CODE '';
  113.     private GiftCertificateCategoryRepositoryInterface $giftCertificateCategoryRepository;
  114.     private FoodOfferExtensionDaoInterface $foodOfferExtensionDao;
  115.     private MessageBusInterface $messageBus;
  116.     private DeliveryWorkingTimeService $deliveryWorkingTimeService;
  117.     private SerializerInterface $serializer;
  118.     private MobApiOfferDaoInterface $mobApiOfferDao;
  119.     private GiftCertificateGroupRepositoryInterface $giftCertificateGroupRepository;
  120.     private VideoPackageDtoGetter $videoPackageDtoGetter;
  121.     private VideoPackageSaver $videoPackageSaver;
  122.     private GiftCertificateGiftCategoryRepositoryInterface $giftCertificateGiftCategoryRepository;
  123.     private OfferFoodDeliveryZoneSaver $offerFoodDeliveryZoneSaver;
  124.     private CategoryRepositoryInterface $categoryRepository;
  125.     private CityRepositoryInterface $cityRepository;
  126.     private InteriorGalleryDaoInterface $interiorGalleryDao;
  127.     private OfferResponseCacheService $offerResponseCacheService;
  128.     public function __construct(
  129.         KernelInterface $kernel,
  130.         GiftCertificateCategoryRepositoryInterface $giftCertificateCategoryRepository,
  131.         GiftCertificateGiftCategoryRepositoryInterface $giftCertificateGiftCategoryRepository,
  132.         FoodOfferExtensionDaoInterface $foodOfferExtensionDao,
  133.         MessageBusInterface $messageBus,
  134.         DeliveryWorkingTimeService $deliveryWorkingTimeService,
  135.         SerializerInterface $serializer,
  136.         MobApiOfferDaoInterface $mobApiOfferDao,
  137.         GiftCertificateGroupRepositoryInterface $giftCertificateGroupRepository,
  138.         VideoPackageDtoGetter $videoPackageDtoGetter,
  139.         VideoPackageSaver $videoPackageSaver,
  140.         OfferFoodDeliveryZoneSaver $offerFoodDeliveryZoneSaver,
  141.         CategoryRepositoryInterface $categoryRepository,
  142.         CityRepositoryInterface $cityRepository,
  143.         InteriorGalleryDaoInterface $interiorGalleryDao,
  144.         OfferResponseCacheService $offerResponseCacheService
  145.     ) {
  146.         parent::__construct($kernel);
  147.         $this->giftCertificateCategoryRepository $giftCertificateCategoryRepository;
  148.         $this->giftCertificateGiftCategoryRepository $giftCertificateGiftCategoryRepository;
  149.         $this->foodOfferExtensionDao $foodOfferExtensionDao;
  150.         $this->messageBus $messageBus;
  151.         $this->deliveryWorkingTimeService $deliveryWorkingTimeService;
  152.         $this->serializer $serializer;
  153.         $this->mobApiOfferDao $mobApiOfferDao;
  154.         $this->giftCertificateGroupRepository $giftCertificateGroupRepository;
  155.         $this->videoPackageDtoGetter $videoPackageDtoGetter;
  156.         $this->videoPackageSaver $videoPackageSaver;
  157.         $this->offerFoodDeliveryZoneSaver $offerFoodDeliveryZoneSaver;
  158.         $this->categoryRepository $categoryRepository;
  159.         $this->cityRepository $cityRepository;
  160.         $this->interiorGalleryDao $interiorGalleryDao;
  161.         $this->offerResponseCacheService $offerResponseCacheService;
  162.     }
  163.     /**
  164.      * @Route("/admin/offer/ajax_get_by_category")
  165.      */
  166.     public function ajaxGetByCategory(Request $request) {
  167.         ini_set('memory_limit''512m');
  168.         if (!$request->isXmlHttpRequest()) {
  169.             return $this->redirect("/admin");
  170.         }
  171.         $data = array();
  172.         $categoryID = (int)$request->request->get('categoryID');
  173.         $entityManager $this->getDoctrine()->getManager("admin");
  174.         $offerRepository $entityManager->getRepository(Offer::class);
  175.         $data['offers'] = $offerRepository->getOffersByCategoryWithPositions($categoryID);
  176.         $categoryRepository $entityManager->getRepository(Category::class);
  177.         $data['category'] = $categoryRepository->find($categoryID);
  178.         $payedOffersList $categoryRepository->getPayedOffersByCategoryID($categoryID);
  179.         $data['mobApiPaidOffersPositions'] = [];
  180.         foreach ($this->mobApiOfferDao->getPaidOffersPositionsByCategoryId($categoryID) as $mobApiPaidOffersPosition) {
  181.             $data['mobApiPaidOffersPositions'][$mobApiPaidOffersPosition->getId()] = $mobApiPaidOffersPosition->getPosition();
  182.         }
  183.         $data['payedOffersList'] = $payedOffersList;
  184.         $result $this->get('twig')->render('Slivki/admin/offers/index.html.twig'$data);
  185.         return new Response($result);
  186.     }
  187.     /**
  188.      * @Route("/admin/offer/ajax_get_by_category_without_tags")
  189.      */
  190.     public function ajaxGetByCategoryWithoutTags(Request $request) {
  191.         $data = [];
  192.         $domainObjectID = (int)$request->request->get('domainObjectID');
  193.         $cityID = (int)$request->request->get('cityID');
  194.         $entityManager $this->getDoctrine()->getManager("admin");
  195.         $offerRepository $entityManager->getRepository(Offer::class);
  196.         $data['offers'] = $offerRepository->getActiveOffersByCategoryWithoutTags($domainObjectID$cityID);
  197.         return $this->render('Slivki/admin/offers/index_without_tags.html.twig'$data);
  198.     }
  199.     /**
  200.      * @Route("/admin/offer/ajax_get_by_category_without_tags_all_city")
  201.      */
  202.     public function ajaxGetByCategoryWithoutTagsAllCity(Request $request) {
  203.         $data = [];
  204.         $entityManager $this->getDoctrine()->getManager("admin");
  205.         $offerRepository $entityManager->getRepository(Offer::class);
  206.         $data['offers'] = $offerRepository->getActiveOffersByCategoryWithoutTagsAllCity();
  207.         return $this->render('Slivki/admin/offers/index_without_tags.html.twig'$data);
  208.     }
  209.     /**
  210.      * @Route("/admin/offer/ajax_offers_on_review")
  211.      */
  212.     public function ajaxGetByCategoryOnReview(Request $request) {
  213.         $data = [];
  214.         $domainObjectID = (int)$request->request->get('domainObjectID');
  215.         $cityID = (int)$request->request->get('cityID');
  216.         $entityManager $this->getDoctrine()->getManager("admin");
  217.         $offerRepository $entityManager->getRepository(Offer::class);
  218.         $offers $offerRepository->getOffersOnReview($domainObjectID$cityID);
  219.         if ($offers) {
  220.             foreach ($offers as $offer) {
  221.                 $data['offers'][] = $offerRepository->find($offer['id']);
  222.             }
  223.         } else {
  224.             $data['offers'] = [];
  225.         }
  226.         return $this->render('Slivki/admin/offers/index_on_review.html.twig'$data);
  227.     }
  228.     /**
  229.      * @Route("/admin/offer/ajax_get_offer/{ID}")
  230.      */
  231.     public function ajaxGetOffer(
  232.         Request $request,
  233.         DeliveryScheduleRepositoryInterface $deliveryScheduleRepository,
  234.         ImageService $imageService,
  235.         OfferNoteGetter $offerNoteGetter,
  236.         ReceivingOrdersScheduleService $receivingOrdersScheduleService,
  237.         FoodDeliveryZoneRepositoryInterface $foodDeliveryZoneRepository,
  238.         SeoResourceService $seoResourceService,
  239.         $ID
  240.     ): Response {
  241.         if (!$request->isXmlHttpRequest()) {
  242.             return $this->redirect("/admin");
  243.         }
  244.         ini_set('memory_limit''256m');
  245.         $session $request->getSession();
  246.         $session->set('geoLocationList', []);
  247.         $result = array();
  248.         $entityManager $this->getDoctrine()->getManager("admin");
  249.         $offerRepository $entityManager->getRepository(Offer::class);
  250.         $entityOptionRepository $entityManager->getRepository(EntityOption::class);
  251.         /** @var Offer $offer */
  252.         $offer $offerRepository->find($ID);
  253.         $result['offer'] = $offer;
  254.         $user $this->getUserRepository()->findOneBy(["ID" => $this->getUser()->getID()]);
  255.         if (!$offer->isNeedReview() || $user->hasRole(UserGroup::ROLE_REVIEWER) || $user->hasRole(UserGroup::ROLE_ADMIN_ID)) {
  256.             $result['activeView'] = true;
  257.         } else {
  258.             $result['activeView'] = false;
  259.         }
  260.         if ($offer->isNeedReview() && !$offer->isOnReview() && $user->hasRole(UserGroup::ROLE_JUNIOR)) {
  261.             $result['sendOnReviewActive'] = true;
  262.         } else {
  263.             $result['sendOnReviewActive'] = false;
  264.         }
  265.         $result['activeSince'] = $offer->getActiveSince()->format('d.m.Y');
  266.         $result['activeTill'] = $offer->getActiveTill()->format('d.m.Y');
  267.         $result['codeActiveTill'] = $offer->getCodeActiveTill()->format('d.m.Y');
  268.         $result['lastModified'] = $offer->getLastModified()->format('Y-m-d H:i:s');
  269.         $seoRepository $entityManager->getRepository(Seo::class);
  270.         $seo $seoRepository->findBy(array('entityID' => $ID'resourceURL' => 'Slivki:Default:details'), array('ID' => 'DESC'), 1);
  271.         if ($seo) {
  272.             $seo $seo[0];
  273.             $result['seo']['alias'] = $seo->getMainAlias();
  274.             $result['seo']['metaTitle'] = $seo->getMetaTitle();
  275.             $result['seo']['metaDescription'] = $seo->getMetaDescription();
  276.             $result['seo']['metaKeywords'] = $seo->getMetaKeywords();
  277.         } else {
  278.             $result['seo']['alias'] = '';
  279.             $result['seo']['metaTitle'] = '';
  280.             $result['seo']['metaDescription'] = '';
  281.             $result['seo']['metaKeywords'] = '';
  282.         }
  283.         $offerPaidCategoryList $entityManager->getRepository(OfferPayedCategory::class)->getPayedCategoriesByEntityID($IDCategory::OFFER_CATEGORY_ID);
  284.         $offerPaidCategoryIDList = [];
  285.         foreach ($offerPaidCategoryList as $offerPaidCategory) {
  286.             $offerPaidCategoryIDList[] = $offerPaidCategory->getCategoryID();
  287.         }
  288.         $cityID $offer->getDefaultCity()->getID();
  289.         $offerCategoryList $offer->getCategories()->toArray();
  290.         $offerCityCategoryList $offerCategoryList;
  291.         $offerPaidCategoryMobile $entityManager->getRepository(OfferPayedCategoryMobile::class);
  292.         $offerPaidCategoryMobileList = [];
  293.         foreach ($offerCityCategoryList as $category) {
  294.             $categoryID $category->getID();
  295.             $mobilePosition $offerPaidCategoryMobile->findOneBy(['categoryID' => $categoryID'entityID' => $ID]);
  296.             if ($mobilePosition) {
  297.                 $offerPaidCategoryMobileList[$categoryID] = $mobilePosition->getPosition();
  298.             }
  299.         }
  300.         $offerCategoryIDList = [];
  301.         $offerCityCategoryCurrentIDList = [];
  302.         $priceCategoryID 0;
  303.         $genderCategoryIDs = [];
  304.         $transportTypeID 0;
  305.         $tourtypeIDs = [];
  306.         if ($offer->getID() === Offer::BOOKING_OFFER_ID) {
  307.             $result['bookingTabVisible'] = true;
  308.         }
  309.         foreach ($offerCategoryList as $key => $offerCategory) {
  310.             if ($offerCategory->getID() === Category::FOOD_CATEGORY_ID || trim($offerCategory->getName()) == 'Еда') {
  311.                 $result['foodTabVisible'] = true;
  312.             }
  313.             if ($offerCategory->getDomainObjectID() <= Category::SUPPLIER_CATEGORY_TYPE) {
  314.                 $offerCategoryIDList[] = $offerCategory->getID();
  315.                 if ($offerCategory->getCity()->getID() == $cityID) {
  316.                     $offerCityCategoryCurrentIDList[] = $offerCategory->getID();
  317.                 } else {
  318.                     unset($offerCityCategoryList[$key]);
  319.                 }
  320.             } else {
  321.                 unset($offerCategoryList[$key]);
  322.                 unset($offerCityCategoryList[$key]);
  323.                 switch ($offerCategory->getDomainObjectID()) {
  324.                     case Category::PRICE_CATEGORY_ID:
  325.                         $priceCategoryID $offerCategory->getID();
  326.                         break;
  327.                     case Category::GENDER_CATEGORY_ID:
  328.                         $genderCategoryIDs[] = $offerCategory->getID();
  329.                         break;
  330.                     case Category::TRANSPORT_TYPE_CATEGORY_ID:
  331.                         $transportTypeID $offerCategory->getID();
  332.                         break;
  333.                     case Category::TOUR_TYPE_CATEGORY_ID:
  334.                         $tourtypeIDs[] = $offerCategory->getID();
  335.                 }
  336.             }
  337.         }
  338.         $result['cityID'] = $cityID;
  339.         $result['allCityCategoryIDList'] = $offerCategoryIDList;
  340.         $result['genderCategoryIDs'] = $genderCategoryIDs;
  341.         $result['priceCategoryID'] = $priceCategoryID;
  342.         $result['transportTypeID'] = $transportTypeID;
  343.         $result['tourTypeIDs'] = $tourtypeIDs;
  344.         $result['tourismOffer'] = false;
  345.         if (in_array(Category::TOURISM_CATEGORY_ID$offerCategoryIDList)) {
  346.             $result['tourismOffer'] = true;
  347.         }
  348.         $result['unlimitedCodes'] = false;
  349.         $result['offerForSlivkiDelivery'] = false;
  350.         $entityOptions $entityOptionRepository->findBy([
  351.             'entityID' => $ID,
  352.             'entityTypeID' => EntityOption::OFFER_ENTITY_TYPE
  353.         ]);
  354.         /** @var EntityOption $entityOption */
  355.         foreach ($entityOptions as $entityOption) {
  356.             switch ($entityOption->getName()) {
  357.                 case EntityOption::OPTION_CODES_UNLIMITED:
  358.                     $result['unlimitedCodes'] = true;
  359.                     break;
  360.                 case EntityOption::OPTION_SLIVKI_DELIVERY:
  361.                     $result['offerForSlivkiDelivery'] = true;
  362.                     break;
  363.             }
  364.         }
  365.         $result['offerCategories'] = $this->get('twig')->render('Slivki/admin/offers/edit_offer_selected_categories.html.twig', [
  366.             'offerCategoryList' => $offerCityCategoryList,
  367.             'offerPaidCategoryIDList' => $offerPaidCategoryIDList,
  368.             'defaultCategoryID' => $offer->getDefaultCategoryID(),
  369.             'offerPaidCategoryMobile' => $offerPaidCategoryMobileList
  370.         ]);
  371.         $categoryRepository $entityManager->getRepository(Category::class);
  372.         $data['categories'] = $categoryRepository->getCategoryTree(Category::OFFER_CATEGORY_ID0$cityID);
  373.         $data['selectedCategoryIDList'] = $offerCityCategoryCurrentIDList;
  374.         $result['categories'] = $this->get('twig')->render('Slivki/admin/categories/recursive_category_with_checkboxes_macro.html.twig'$data);
  375.         $mediaRepository $entityManager->getRepository(Media::class);
  376.         $teaserImage $offer->getTeaserMedia();
  377.         if ($teaserImage) {
  378.             $result['teaserImage'] = $imageService->getImageURL($teaserImage500324);
  379.         }
  380.         $appTeaserImage $offer->getAppTeaserMedia();
  381.         if ($appTeaserImage) {
  382.             $result['appTeaserImage'] = $imageService->getImageURL($appTeaserImageImageService::OFFER_APP_TEASER_WIDTHImageService::OFFER_APP_TEASER_HEIGHT);
  383.         }
  384.         $mobileTeaserImage $offer->getMobileTeaserMedia();
  385.         if ($mobileTeaserImage) {
  386.             $result['mobileTeaserImage'] = $imageService->getImageURL($mobileTeaserImage764382);
  387.         }
  388.         $additionalTeaserImage $mediaRepository->getOfferAdditionalTeaserMedia($ID);
  389.         if ($additionalTeaserImage) {
  390.             $result['additionalTeaserImage'] = $imageService->getImageURL($additionalTeaserImage250162);
  391.         }
  392.         $hotFeedIconImage $mediaRepository->getOfferHotFeedIconMedia($ID);
  393.         if ($hotFeedIconImage) {
  394.             $result['hotFeedIconImage'] = $imageService->getImageURL($hotFeedIconImage500324);
  395.         }
  396.         $offerTopBlockMedia $offer->getTopBlockMedia();
  397.         if ($offerTopBlockMedia) {
  398.             $result['offerTopBlockMedia'] = $imageService->getImageURL($offerTopBlockMedia00);
  399.         }
  400.         $offerTopBlockMobileMedia $offer->getTopBlockMobileMedia();
  401.         if ($offerTopBlockMobileMedia) {
  402.             $result['offerTopBlockMobileMedia'] = $imageService->getImageURL($offerTopBlockMobileMedia00);
  403.         }
  404.         $onlineOrderPopupLogoMedia $offer->getOnlineOrderPopupLogoMedia();
  405.         if (null !== $onlineOrderPopupLogoMedia) {
  406.             $result['onlineOrderPopupLogoMedia'] = $imageService->getImageURL($onlineOrderPopupLogoMedia350175);
  407.         }
  408.         $giftCertificatePdfBgMedia $offer->getGiftCertificatePdfBgMedia();
  409.         if ($giftCertificatePdfBgMedia) {
  410.             $result['giftCertificatePdfBgMedia'] = $imageService->getImageURL($giftCertificatePdfBgMedia00);
  411.         }
  412.         $mapLogoMedia $offer->getMapLogoMedia();
  413.         if (null !== $mapLogoMedia) {
  414.             $result['mapLogoMedia'] = $imageService->getImageURL($mapLogoMedia00);
  415.         }
  416.         $deliveryZoneMedia $offer->getDeliveryZoneMedia();
  417.         if (null !== $deliveryZoneMedia) {
  418.             $result['deliveryZoneMedia'] = $imageService->getImageURL($deliveryZoneMedia00);
  419.         }
  420.         $offerTeaserLogo $mediaRepository->getOfferTeaserLogo($ID);
  421.         if ($offerTeaserLogo) {
  422.             $result['offerTeaserLogo'] = $imageService->getImageURL($offerTeaserLogo$offer->getTeaserLogoWidth(), $offer->getTeaserLogoHeight());
  423.         }
  424.         $offerShopMedias $mediaRepository->getOfferShopMedias($ID);
  425.         $result['offerShopMedias'] = $this->renderView('Slivki/admin/offers/shop_medias.html.twig', [
  426.             'images' => $offerShopMedias,
  427.             'interiorGalleryMediaIds' => $this->interiorGalleryDao->getByOfferId($ID),
  428.         ]);
  429.         $offerDetailMedias $mediaRepository->getOfferDetailMedias($ID);
  430.         $result['offerDetailMedias'] = $this->get('twig')->render('Slivki/admin/offers/detail_medias.html.twig', array('images' => $offerDetailMedias));
  431.         $descriptionRepository $entityManager->getRepository(EntityDescription::class);
  432.         $descriptionTypeIDList = [
  433.             'Condition' => EntityDescription::TYPE_OFFER_CONDITIONS_ID,
  434.             'Features' => EntityDescription::TYPE_OFFER_FEATURES_ID,
  435.             'Location' => EntityDescription::TYPE_OFFER_LOCATION_ID,
  436.             'Logo' => EntityDescription::TYPE_OFFER_LOGO_ID,
  437.             'Legal' => EntityDescription::TYPE_OFFER_LEGAL_ID,
  438.             'Description' => EntityDescription::TYPE_OFFER_DESCRIPTION_ID,
  439.             'WorkingHours' => EntityDescription::TYPE_OFFER_WORKING_HOURS_ID,
  440.             'VendorCondition' => EntityDescription::TYPE_VENDOR_CONDITION,
  441.             'BriefDeliveryCondition' => EntityDescription::TYPE_BRIEF_DELIVERY_CONDITION,
  442.         ];
  443.         foreach ($descriptionTypeIDList as $key => $descriptionTypeID) {
  444.             if ($descriptionTypeID == EntityDescription::TYPE_OFFER_DESCRIPTION_ID) {
  445.                 $descriptions $descriptionRepository->findBy(['entityID' => $ID'typeID' => $descriptionTypeID], ['ID' => 'ASC']);
  446.                 if (!$descriptions) {
  447.                     $descriptions = ['new'];
  448.                 }
  449.                 $result['offerDescriptions'] = $this->get('twig')->render('Slivki/admin/offers/offer_description_block.html.twig', ['descriptions' => $descriptions]);
  450.             } else {
  451.                 $description $descriptionRepository->findOneBy(['entityID' => $ID'typeID' => $descriptionTypeID]);
  452.                 $result["description$key"] = $description $description->getDescription() ? $description->getDescription() : '' '';
  453.             }
  454.         }
  455.         $result['geoLocations'] = $this->getGeoLocationList($offer);
  456.         $result['directors'] = $this->get('twig')->render('Slivki/admin/directors/list.html.twig', ['directors' => $offer->getDirectors()->toArray()]);
  457.         $result['antiTags'] = $this->get('twig')->render('Slivki/admin/tags/antitag_list.html.twig', ['tags' => $offer->getAntiTags()->toArray()]);
  458.         $result['codes'] = $offer->getLastActiveCodePool();
  459.         $data['managerList'] = $entityManager->getRepository(UserGroup::class)->findOneByName('MANAGER')->getUsers();
  460.         $data['currentManager'] = $offer->getManager();
  461.         $result['managerOptions'] = $this->get('twig')->render('Slivki/admin/managers/options_list.html.twig'$data);
  462.         $result['phoneNumberList'] = $this->get('twig')->render('Slivki/admin/offers/phone_number_list.html.twig', ['offer' => $offer'belarusPhoneCode' => self::BELARUS_PHONE_CODE]);
  463.         $productFastDeliveryList = [];
  464.         if (null !== $offer->getProductFastDelivery()) {
  465.             foreach ($offer->getProductFastDelivery() as $item) {
  466.                 $productFastDeliveryList[] = [
  467.                     'productFastDeliveryId' => $item->getProductId(),
  468.                     'productFastDeliveryProductId' => $item->getProductId(),
  469.                     'productFastDeliveryDeliveryTime' => $item->getDeliveryTime(),
  470.                     'productFastDeliveryIsActive' => $item->isActive(),
  471.                 ];
  472.             }
  473.         }
  474.         $result['productFastDelivery'] = $this->get('twig')->render('Slivki/admin/offers/product_fast_delivery_list.html.twig', ['offerId' => $offer->getID(), 'productFastDeliveryList' => $productFastDeliveryList]);
  475.         $result['deliveryZoneList'] = $this->renderView('Slivki/admin/offers/delivery_zone_list.html.twig', ['offerId' => $offer->getID(), 'deliveryZoneList' => $foodDeliveryZoneRepository->getByOfferId($offer->getID())]);
  476.         $hotFeed $entityManager->getRepository(HotFeed::class)->findBy(['entityTypeID' => Category::OFFER_CATEGORY_ID'entityID' => $offer->getID(), 'type' => HotFeed::TYPE_MAIN_PAGE]);
  477.         if ($hotFeed) {
  478.             $result['hotFeed'] = true;
  479.         }
  480.         $tourismHotFeed $entityManager->getRepository(HotFeed::class)->findBy(['entityTypeID' => Category::OFFER_CATEGORY_ID'entityID' => $offer->getID(), 'type' => HotFeed::TYPE_OFFER_TOURISM_PAGE]);
  481.         if ($tourismHotFeed) {
  482.             $result['tourismHotFeed'] = true;
  483.         }
  484.         $description $descriptionRepository->findOneBy(['entityID' => $ID'typeID' => EntityDescription::TYPE_FOOD_ORDER_DESCRIPTION_ID]);
  485.         if ($description) {
  486.             $result['foodOptionDescription'] = $description->getDescription();
  487.         }
  488.         if ($offer->getDeliveryPrice()) {
  489.             $result['foodOptionDeliveryPrice'] = $offer->getDeliveryPrice();
  490.         }
  491.         if ($offer->getSumForFreeDelivery()) {
  492.             $result['foodOptionLowerPrice'] = $offer->getSumForFreeDelivery();
  493.         }
  494.         $result['foodList'] = $this->renderView(
  495.             'Slivki/admin/offers/offer_food_list_table.html.twig',
  496.             ['offer' => $this->foodOfferExtensionDao->findAllFoodOfferExtensionsByOfferId($ID)],
  497.         );
  498.         $items $entityManager->getRepository(ItemOfferExtension::class)->findBy(['offer' => $ID]);
  499.         if ($items) {
  500.             $result['items'] = $this->renderView('Slivki/admin/offers/offer_items_table.html.twig', ['items' => $items]);
  501.         }
  502.         $entityOption $entityOptionRepository->findOneBy(['entityID' => $ID'entityTypeID' => EntityOption::OFFER_ENTITY_TYPE'name' => EntityOption::OPTION_ENDLESS_CODES]);
  503.         if ($entityOption) {
  504.             $result['isEndless'] = $entityOption->getValue();
  505.         }
  506.         $createdOn $offer->getCreatedOn()->setTime(00)->modify('+30 days');
  507.         $nowDate = new \DateTime();
  508.         if ($nowDate $createdOn && $user->hasRole(UserGroup::ROLE_MANAGER_ID)) {
  509.             $result['bannedAlias'] = true;
  510.         }
  511.         $bookedOption $entityOptionRepository->findOneBy(['entityID' => $ID'entityTypeID' => EntityOption::BOOKING_RESERVED_DATES'name' => EntityOption::OPTION_BOOKING_DATES]);
  512.         if ($bookedOption) {
  513.             $dateToFormat = [];
  514.             foreach (explode(","$bookedOption->getValue()) as $date) {
  515.                 $dateToFormat[] = date('d.m.Y'strtotime($date));
  516.             }
  517.             $result['bookedDates'] = implode(','$dateToFormat);
  518.         }
  519.         $onlineOrderSettings $offer->getOnlineOrderSettings();
  520.         if (!$onlineOrderSettings) {
  521.             $onlineOrderSettings = new OnlineOrderSettings();
  522.             $onlineOrderSettings->setOffer($offer);
  523.         }
  524.         $iikoUtil AbstractDelivery::instance($offer);
  525.         $result['onlineOrderSettingsBox'] = $this->renderView('Slivki/admin/offers/online_order_settings.html.twig', [
  526.             'onlineOrderSettings' => $onlineOrderSettings,
  527.             'allowedPaymentMethods' => $onlineOrderSettings->getAllowedPaymentMethods(),
  528.             'pickupLeadTime' => $onlineOrderSettings->getPickupLeadTime(),
  529.             'priceCodeDependsOnOrder' => $onlineOrderSettings->getPriceCodeDependsOnOrder(),
  530.             'pickupIntervalBetweenOrdersTime' => $iikoUtil::PICKUP_INTERVAL_BETWEEN_ORDERS_TIME,
  531.             'pickupNearlyEnabled' => $iikoUtil::PICKUP_NEARLY_ENABLED,
  532.             'pickupDisableTime' => $iikoUtil::PICKUP_DISABLE_TIME,
  533.             'deliverySchedules' => $deliveryScheduleRepository->findByOfferId($offer->getID()),
  534.             'deliveryWorkingTime' => $this->deliveryWorkingTimeService->getDeliveryWorkingTimeByOffer($offer),
  535.             'receivingOrdersSchedule' => $receivingOrdersScheduleService->getReceivingOrdersScheduleByOffer($offer),
  536.         ]);
  537.         $result['videoPackage'] = $this->videoPackageDtoGetter->getByOfferId($ID);
  538.         $result['offerNote'] = $offerNoteGetter->getOfferNote($ID);
  539.         $result['previewUrl'] = sprintf('%s?preview=true'$seoResourceService->getOfferUrlWithDomain($ID));
  540.         return new Response(json_encode($result));
  541.     }
  542.     /**
  543.      * @Route("/admin/offer/ajax_edit_comments")
  544.      */
  545.     public function ajaxGetComments(Request $request) {
  546.         if (!$request->isXmlHttpRequest()) {
  547.             return $this->redirect("/admin");
  548.         }
  549.         $ID $request->request->get('id');
  550.         $offer $this->getOfferRepository()->find($ID);
  551.         if (!$offer) {
  552.             return new Response('false');
  553.         }
  554.         $comments $this->getCommentRepository()->findBy(['entityID' => $ID'typeID' => Comment::TYPE_OFFER_COMMENT], ['createdOn' => 'DESC'], 50);
  555.         $loadedCommentsCount count($comments);
  556.         return new Response(json_encode(['html' => $this->get('twig')->render('Slivki/admin/offers/comments_list.html.twig', ['comments' => $comments'offer' => $offer]), 'loadedCommentsCount' => $loadedCommentsCount]));
  557.     }
  558.     /**
  559.      * @Route("/admin/offer/ajax_load_more_comments")
  560.      */
  561.     public function ajaxLoadMoreComments(Request $request) {
  562.         if (!$request->isXmlHttpRequest()) {
  563.             return $this->redirect("/admin");
  564.         }
  565.         $ID $request->request->get('id');
  566.         $offer $this->getOfferRepository()->find($ID);
  567.         if (!$offer) {
  568.             return new Response('false');
  569.         }
  570.         $lastCommentID $request->request->get('lastCommentID');
  571.         if (!$lastCommentID) {
  572.             $lastCommentID PHP_INT_MAX;
  573.         }
  574.         $dql "select comment from Slivki:Comment comment
  575.             where comment.entityID = :offerID
  576.               and comment.ID < :lastCommentID
  577.             order by comment.createdOn desc";
  578.         $query $this->getDoctrine()->getManager('admin')->createQuery($dql)
  579.             ->setParameter('offerID'$ID)
  580.             ->setParameter('lastCommentID'$lastCommentID);
  581.         $query->setMaxResults(50);
  582.         $comments $query->getResult();
  583.         $loadedCommentsCount count($comments);
  584.         return new Response(json_encode(['html' => $this->get('twig')->render('Slivki/admin/offers/comments_list.html.twig', ['comments' => $comments'offer' => $offer]), 'loadedCommentsCount' => $loadedCommentsCount]));
  585.     }
  586.     /**
  587.      * @Route("/admin/offer/ajax_get_category_tree_by_city")
  588.      */
  589.     public function ajaxGetCateoryTreeByCity(Request $request) {
  590.         $entityManager $this->getEntityManager();
  591.         $cityID $request->request->get('cityID');
  592.         $categoryRepository $entityManager->getRepository(Category::class);
  593.         $data['categories'] = $categoryRepository->getCategoryTree(Category::OFFER_CATEGORY_ID0$cityID);
  594.         $offerID $request->request->get('offerID');
  595.         $result['offerCategories'] = '';
  596.         if ($offerID) {
  597.             $offerCategoryIDList = [];
  598.             $offer $entityManager->getRepository(Offer::class)->find($offerID);
  599.             $offerCategoryList $offer->getCategoriesByCity($cityID)->toArray();
  600.             foreach ($offerCategoryList as $key => $offerCategory) {
  601.                 if ($offerCategory->getDomainObjectID() <= Category::SUPPLIER_CATEGORY_TYPE) {
  602.                     $offerCategoryIDList[] = $offerCategory->getID();
  603.                 } else {
  604.                     unset($offerCategoryList[$key]);
  605.                 }
  606.             }
  607.             $offerPaidCategoryList $entityManager->getRepository(OfferPayedCategory::class)->getPayedCategoriesByEntityID($offerIDCategory::OFFER_CATEGORY_ID);
  608.             $offerPaidCategoryIDList = [];
  609.             foreach ($offerPaidCategoryList as $offerPaidCategory) {
  610.                 $offerPaidCategoryIDList[] = $offerPaidCategory->getCategoryID();
  611.             }
  612.             $result['offerCategories'] = $this->get('twig')->render('Slivki/admin/offers/edit_offer_selected_categories.html.twig', [
  613.                 'offerCategoryList' => $offerCategoryList,
  614.                 'offerPaidCategoryIDList' => $offerPaidCategoryIDList,
  615.                 'defaultCategoryID' => $offer->getDefaultCategoryID(),
  616.                 'offerPaidCategoryMobile' => [],
  617.             ]);
  618.             $data['selectedCategoryIDList'] = $offerCategoryIDList;
  619.         }
  620.         $result['categories'] = $this->get('twig')->render('Slivki/admin/categories/recursive_category_with_checkboxes_macro.html.twig'$data);
  621.         return new JsonResponse($result);
  622.     }
  623.     /**
  624.      * @Route("/admin/offer/ajax_edit_offer")
  625.      */
  626.     public function ajaxEditOffer(
  627.         Request $request,
  628.         OfferCacheService $offerCacheService,
  629.         CacheService $cacheService,
  630.         ImageService $imageService,
  631.         KernelInterface $kernel,
  632.         CodePoolService $codePoolService,
  633.         Mailer $mailer,
  634.         CategoryBoxCacheService $categoryBoxCacheService
  635.     ) {
  636.         ini_set('memory_limit''4G');
  637.         if (!$request->isXmlHttpRequest()) {
  638.             return $this->redirect("/admin");
  639.         }
  640.         $result['message'] = $this->validateOfferForm($request);
  641.         if ($result['message'] !== true) {
  642.             return new Response(json_encode($result));
  643.         }
  644.         $result $this->saveOffer($request$offerCacheService$cacheService$imageService$kernel$codePoolService$mailer$categoryBoxCacheService);
  645.         return new Response(json_encode($result));
  646.     }
  647.     /**
  648.      * @Route("/admin/offer/ajax_get_category_tree", name="/admin/offer/ajax_get_category_tree")
  649.      */
  650.     public function ajaxGetCategoryTree(Request $request) {
  651.         if (!$request->isXmlHttpRequest()) {
  652.             return $this->redirect("/admin");
  653.         }
  654.         $categoryRepository $this->getDoctrine()->getRepository(Category::class);
  655.         $category $categoryRepository->find($request->request->get('categoryID'));
  656.         $data['categories'] = $categoryRepository->getCategoryTree(Category::OFFER_CATEGORY_ID0$category->getCity()->getID());
  657.         $result['categories'] = $this->get('twig')->render('Slivki/admin/categories/recursive_category_with_checkboxes_macro.html.twig'$data);
  658.         return new Response(json_encode($result));
  659.     }
  660.     /**
  661.      * @Route("/admin/offer/ajax_add_offer", name="/admin/offer/ajax_add_offer")
  662.      */
  663.     public function ajaxAddOffer(Request $requestOfferCacheService $offerCacheServiceCacheService $cacheServiceImageService $imageServiceKernelInterface $kernelCodePoolService $codePoolServiceMailer $mailerCategoryBoxCacheService $categoryBoxCacheService) {
  664.         if (!$request->isXmlHttpRequest()) {
  665.             return $this->redirect("/admin");
  666.         }
  667.         $result['message'] = $this->validateOfferForm($request);
  668.         if ($result['message'] !== true) {
  669.             return new Response(json_encode($result));
  670.         }
  671.         $result $this->saveOffer($request$offerCacheService$cacheService$imageService$kernel$codePoolService$mailer$categoryBoxCacheServicetrue);
  672.         return new Response(json_encode($result));
  673.     }
  674.     /**
  675.      * @Route("/admin/offer/ajax_upload_detail_images")
  676.      */
  677.     public function ajaxUploadDetailImages(Request $requestKernelInterface $kernel) {
  678.         if (!$request->isXmlHttpRequest()) {
  679.             return $this->redirect("/admin");
  680.         }
  681.         $result = array();
  682.         $uploadedFile $request->files->get('editOfferDetailsImagesUpload');
  683.         $fs = new Filesystem();
  684.         $logoPath $kernel->getProjectDir() . Offer::DETAIL_MEDIA_PATH;
  685.         $fileName $uploadedFile->getClientOriginalName();
  686.         $result['originalFileName'] = $fileName;
  687.         while ($fs->exists($logoPath $fileName)) {
  688.             $fileName time() . '_' $fileName;
  689.         }
  690.         $uploadedFile->move($logoPath$fileName);
  691.         $result['imageURL'] = str_replace('/public'''Offer::DETAIL_MEDIA_PATH) . $fileName;
  692.         $result['imageName'] = $fileName;
  693.         return new Response(json_encode($result));
  694.     }
  695.     /**
  696.      * @Route("/admin/offer/ajax_add_detail_medias")
  697.      */
  698.     public function ajaxAddDetailMedias(Request $request)
  699.     {
  700.         if (!$request->isXmlHttpRequest()) {
  701.             return $this->redirect("/admin");
  702.         }
  703.         $result = [];
  704.         $imageID $request->request->get('imageID');
  705.         $imageURL $request->request->get('imageURL');
  706.         $isVideo $request->request->getBoolean('video');
  707.         $result['offerDetailMedias'] = $this->get('twig')->render(
  708.             'Slivki/admin/offers/add_detail_medias.html.twig',
  709.             [
  710.                 'imageID' => $imageID,
  711.                 'imageURL' => $imageURL,
  712.                 'isVideo' => $isVideo,
  713.             ]
  714.         );
  715.         return new Response(json_encode($result));
  716.     }
  717.     /**
  718.      * @Route("/admin/offer/ajax_upload_shop_images", name="/admin/offer/ajax_upload_shop_images")
  719.      */
  720.     public function ajaxUploadShopImages(Request $requestKernelInterface $kernel) {
  721.         if (!$request->isXmlHttpRequest()) {
  722.             return $this->redirect("/admin");
  723.         }
  724.         $result = array();
  725.         $uploadedFile $request->files->get('edit-offer-upload-shop-images');
  726.         $fs = new Filesystem();
  727.         $logoPath $kernel->getProjectDir() . Offer::SHOP_MEDIA_PATH;
  728.         $fileName $uploadedFile->getClientOriginalName();
  729.         $result['originalFileName'] = $fileName;
  730.         while ($fs->exists($logoPath $fileName)) {
  731.             $fileName time() . '_' $fileName;
  732.         }
  733.         $uploadedFile->move($logoPath$fileName);
  734.         $result['imageURL'] = str_replace('/public'''Offer::SHOP_MEDIA_PATH) . $fileName;
  735.         $result['imageName'] = $fileName;
  736.         return new Response(json_encode($result));
  737.     }
  738.     /**
  739.      * @Route("/admin/offer/ajax_add_shop_medias", name="/admin/offer/ajax_add_shop_medias")
  740.      */
  741.     public function ajaxAddShopMedias(Request $request) {
  742.         if (!$request->isXmlHttpRequest()) {
  743.             return $this->redirect("/admin");
  744.         }
  745.         $result = array();
  746.         $imageID $request->request->get('imageID');
  747.         $imageURL $request->request->get('imageURL');
  748.         $imageName $request->request->get('imageName');
  749.         $result['offerShopMedias'] = $this->get('twig')->render('Slivki/admin/offers/add_shop_medias.html.twig', array('imageID' => $imageID'imageURL' => $imageURL'imageName' => $imageName));
  750.         return new Response(json_encode($result));
  751.     }
  752.     /**
  753.      * @Route("/admin/offer/ajax_add_teaser_medias", name="/admin/offer/ajax_add_teaser_medias")
  754.      */
  755.     public function ajaxAddTeaserMedias(Request $request) {
  756.         if (!$request->isXmlHttpRequest()) {
  757.             return $this->redirect("/admin");
  758.         }
  759.         $result = array();
  760.         $imageURL $request->request->get('imageURL');
  761.         $imageName $request->request->get('imageName');
  762.         $result['offerTeaserMedias'] = $this->get('twig')->render('Slivki/admin/offers/add_teaser_medias.html.twig', array('imageURL' => $imageURL'imageName' => $imageName));
  763.         return new Response(json_encode($result));
  764.     }
  765.     /**
  766.      * @Route("/admin/offer/ajax_remove_media", name="/admin/offer/ajax_remove_media")
  767.      */
  768.     public function ajaxRemoveMedia(Request $requestCacheService $cacheService) {
  769.         if (!$request->isXmlHttpRequest()) {
  770.             return $this->redirect("/admin");
  771.         }
  772.         $mediaID $request->request->get('mediaID');
  773.         $this->getEntityManager()->getConnection()->executeQuery('delete from media where id = ' $mediaID);
  774.         $cacheService->deleteMedia($mediaID);
  775.         return new Response('');
  776.     }
  777.     private function validateOfferForm(Request $request) {
  778.         $errorMessage '';
  779.         if ($request->request->get('edit-offer-title') == '') {
  780.             $errorMessage .= 'Введите имя акции!<br>';
  781.         }
  782.         if (!$request->request->get('editOfferAllCityCategoryIDList')) {
  783.             $this->log('error');
  784.             $errorMessage .= 'Выберите хотя бы одну категорию!<br>';
  785.         }
  786.         if ($errorMessage != '') {
  787.             $result = array(
  788.                 'title' => 'Ошибка!',
  789.                 'message' => $errorMessage,
  790.                 'type' => 'modal-danger'
  791.             );
  792.             return $result;
  793.         }
  794.         return true;
  795.     }
  796.     private function saveOffer(
  797.         Request $request,
  798.         OfferCacheService $offerCacheService,
  799.         CacheService $cacheService,
  800.         ImageService $imageService,
  801.         KernelInterface $kernel,
  802.         CodePoolService $codePoolService,
  803.         Mailer $mailer,
  804.         CategoryBoxCacheService $categoryBoxCacheService,
  805.         $new false
  806.     ) {
  807.         ini_set('max_execution_time'600);
  808.         $entityManager $this->getDoctrine()->getManager("admin");
  809.         $offerRepository $entityManager->getRepository(Offer::class);
  810.         $requestOfferID = (int)$request->request->get('edit-offer-id');
  811.         $session $request->getSession();
  812.         $offerPreviousActiveTill null;
  813.         $offerIsVisible false;
  814.         $debugLogger null;
  815.         /** @var $offer \Slivki\Entity\Offer */
  816.         if ($new) {
  817.             $offer = new Offer();
  818.             $debugLogger Logger::instance('saveOfferDebug-new-');
  819.             $defaultCity $this->cityRepository->getById($request->request->getInt('editOfferDefaultCityID'));
  820.             $offer->setDefaultCity($defaultCity);
  821.         } else {
  822.             $offer $offerRepository->find($requestOfferID);
  823.             $offerPreviousActiveTill $offer->getActiveTill();
  824.             $offerIsVisible $offer->isVisible();
  825.             $debugLogger Logger::instance('saveOfferDebug-' $offer->getID());
  826.         }
  827.         $debugLogger->info('start');
  828.         $offer->setVersion($offer->getVersion() + 1);
  829.         $meOnMapName trim($request->request->get('editOfferMeOnMapName'));
  830.         $offer->setMeOnMapName('' === $meOnMapName null $meOnMapName);
  831.         $offerTitle $request->request->get('edit-offer-title');
  832.         $requestActiveSearchPosition $request->request->get('edit-offer-active-search-position') ? true false;
  833.         $requestSearchPosition $request->request->get('edit-offer-search-position');
  834.         $categoryIDList explode(','$request->request->get('editOfferAllCityCategoryIDList'));
  835.         $priceCategoryID $request->request->get('priceCategoryDefault');
  836.         $tourismPriceCategoryID $request->request->get('priceCategoryTourism');
  837.         $transportType $request->request->get('transportType');
  838.         if ($priceCategoryID) {
  839.             $categoryIDList[] = $priceCategoryID;
  840.         }
  841.         if ($tourismPriceCategoryID) {
  842.             $categoryIDList[] = $tourismPriceCategoryID;
  843.         }
  844.         if ($transportType) {
  845.             $categoryIDList[] = $transportType;
  846.         }
  847.         $categoryIDList array_merge($categoryIDList$request->request->get('genderCategory', []));
  848.         $categoryIDList array_merge($categoryIDList$request->request->get('tourType', []));
  849.         $currentCityID $request->request->get('offerCategoryCitySelect');
  850.         $currentCategories $offer->getCategoriesByCity($currentCityID)->toArray();
  851.         foreach ($currentCategories as $currentCategory) {
  852.             if (in_array($currentCategory->getID(), $categoryIDList) === false) {
  853.                 $this->logOperatorAction($request$requestOfferID'remove category ' $currentCategory->getID(), OperatorActionLog::ADD_AND_REMOVE_FROM_CATEGORY_SALE_AND_OFFERS);
  854.                 $offer->removeCategory($currentCategory);
  855.                 $payedCategoryRepository $entityManager->getRepository(OfferPayedCategoryMobile::class);
  856.                 $payedCategory $payedCategoryRepository->findOneBy(['categoryID' => $currentCategory->getID(), 'entityID' => $offer->getID()]);
  857.                 if ($payedCategory) {
  858.                     $entityManager->remove($payedCategory);
  859.                 }
  860.             }
  861.         }
  862.         $categories $this->categoryRepository->findByIds(array_values($categoryIDList));
  863.         foreach ($categories as $currentCategory) {
  864.             if ($offer->addCategory($currentCategory)) {
  865.                 $this->logOperatorAction(
  866.                     $request,
  867.                     $requestOfferID,
  868.                     sprintf('add category %s',  $currentCategory->getID()),
  869.                     OperatorActionLog::ADD_AND_REMOVE_FROM_CATEGORY_SALE_AND_OFFERS,
  870.                 );
  871.             }
  872.         }
  873.         $price $request->request->get('edit-offer-price''');
  874.         if ($price != '') {
  875.             $price = (float)str_replace(',''.'$price);
  876.         } else {
  877.             $price null;
  878.         }
  879.         $offer->setPrice($price);
  880.         $oldPrice $request->request->get('editOfferOldPrice''');
  881.         if ($oldPrice != '') {
  882.             $oldPrice = (float)str_replace(',''.'$oldPrice);
  883.         } else {
  884.             $oldPrice null;
  885.         }
  886.         $offer->setOldPrice($oldPrice);
  887.         $offer->setHint($request->request->get('edit-offer-hint'));
  888.         if ($this->getUser()->hasRole(UserGroup::ROLE_ADMIN_ID)) {
  889.             $offer->setFree($request->request->get('edit-offer-free'));
  890.         }
  891.         $offer->setWithoutCodes($request->request->getBoolean('edit-offer-without-codes'));
  892.         $offer->setTitle($offerTitle);
  893.         $offer->setExplanationText($request->request->get('edit-offer-explanation-text'));
  894.         $offer->setOfferPrice($request->request->get('edit-offer-offer-price'));
  895.         $offer->setRegularPrice($request->request->get('edit-offer-regular-price'));
  896.         $offer->setDiscount($request->request->get('edit-offer-discount'));
  897.         $offer->setAdditionalPercents((int)$request->request->get('edit-offer-additional-percents'));
  898.         $offer->setAddress($request->request->get('edit-offer-address'));
  899.         $offer->setShowPriceInConditions($request->request->get('show-price-in-conditions'));
  900.         $offer->setHideFeatures($request->request->getBoolean('editOfferHideFeatures'));
  901.         $offer->setShowAltOffers($request->request->get('show-alt-offers'));
  902.         $offer->setCaptionName($request->request->get('edit-offer-caption-name'));
  903.         $offer->setCaptionColor($request->request->get('edit-offer-caption-color'));
  904.         $offer->setRegionalCaptionName($request->request->get('offerRegionalCaptionName'));
  905.         $offer->setRegionalCaptionColor($request->request->get('offerRegionalCaptionColor'));
  906.         $defaultCategoryId $request->request->getInt('defaultCategoryID');
  907.         if (!== $defaultCategoryId) {
  908.             $defaultCategory $this->categoryRepository->getById($defaultCategoryId);
  909.             $offer->setDefaultCategoryID($defaultCategoryId);
  910.             $offer->setDefaultCity($defaultCategory->getCity());
  911.         }
  912.         $offer->setLastModified(new \DateTime());
  913.         $offer->setActiveSearchPosition($requestActiveSearchPosition);
  914.         $offer->setSearchPosition(mb_strtolower($requestSearchPosition));
  915.         $offer->setCompanyName($request->request->get('companyName'));
  916.         $offer->setActiveCurrencyCalculator($request->request->get('edit-offer-active-currency-calculator'));
  917.         $offer->setTeaserLogoWidth($request->request->getInt('editOfferTeaserLogoWidth'0));
  918.         $offer->setTeaserLogoHeight($request->request->getInt('editOfferTeaserLogoHeight'0));
  919.         $offer->setBuyCodeButtonText($request->request->get('buyCodeButtonText'''));
  920.         $offer->setBuyItemsButtonText($request->request->get('buyItemsButtonText'''));
  921.         $offer->setAllowedBuyOnlyCode($request->request->getBoolean('allowedBuyOnlyCode'));
  922.         $offer->setTelegramBotShow($request->request->getBoolean('editOfferTelegramBotShow'));
  923.         $offer->setBuyCodeDisable($request->request->getBoolean('offerBuyCodeDisable'));
  924.         $offer->setHideInApp($request->request->getBoolean('offerHideInApp'));
  925.         $offer->setBrandboxEnabled($request->request->getBoolean('offerBrandboxEnabled'));
  926.         $offer->setDiscountDeliveryPopup(trim($request->request->get('discount-delivery-popup')) === '' null trim($request->request->get('discount-delivery-popup')));
  927.         $offer->setDiscountPickupPopup(trim($request->request->get('discount-pickup-popup')) === '' null trim($request->request->get('discount-pickup-popup')));
  928.         $offer->setExternalOfferLink(trim($request->request->get('external-offer-link')) === '' null trim($request->request->get('external-offer-link')));
  929.         $offer->setIsShowExternalOfferLink($request->request->getBoolean('is_show_external_offer_link'));
  930.         $offer->setDeliveryTimeTeaser($request->request->get('deliveryTimeTeaser'));
  931.         $offer->setFoodcourtInfoTeaser($request->request->get('foodcourtInfoTeaser'));
  932.         $offer->setFoodcourtInfoColorTeaser($request->request->get('foodcourtInfoColorTeaser'));
  933.         $offer->setTitleFontColor($request->request->get('titleFontColor'));
  934.         $offer->setIsIncludedInBeauty($request->request->getBoolean('isIncludedInBeauty'));
  935.         $offer->setQrCodes($request->request->getBoolean('isQrCodes'));
  936.         $offer->setRecurrentDisabled($request->request->getBoolean('recurrentDisabled'));
  937.         $offer->setAvailableOnFood($request->request->getBoolean('availableOnFood'));
  938.         $offer->setOnlineAutoOpened($request->request->getBoolean('onlineAutoOpened'));
  939.         $offer->setFoodcourtLogoEnabled($request->request->getBoolean('foodcourtLogoEnabled'));
  940.         $offer->setOnlineOrderGiftEnabled($request->request->getBoolean('onlineOrderGiftEnabled'));
  941.         $offer->setBuyCodeInAppOnly($request->request->getBoolean('buyCodeInAppOnly'));
  942.         $offer->setShowProductsInOfferDescription($request->request->getBoolean('showProductsInOfferDescription'));
  943.         $offer->setCheckAddressInOfferMenu($request->request->getBoolean('checkAddressInOfferMenu'));
  944.         $offer->setShowMapIconInApp($request->request->getBoolean('showMapIconInApp'));
  945.         $offer->setFestOffer($request->request->getBoolean('festOffer'));
  946.         $offer->setSeparateTabForCertificatesInApp($request->request->getBoolean('separateTabForCertificatesInApp'));
  947.         $offer->setUseUnusedCodes($request->request->getBoolean('useUnusedCodes'));
  948.         $offer->setYclientCompanyId($request->request->get('yclientCompanyId') ?: null);
  949.         $offer->setYclientAppKey($request->request->get('yclientAppKey') ?: null);
  950.         $allowedOnlineOrderTypes = \json_decode($request->request->get('allowedOnlineOrderTypes'), true);
  951.         $offer->setAllowedOnlineOrderTypes(
  952.             (null === $allowedOnlineOrderTypes || (=== \count($allowedOnlineOrderTypes['site']) && === \count($allowedOnlineOrderTypes['app'])))
  953.                 ? null
  954.                 $allowedOnlineOrderTypes
  955.         );
  956.         $offer->setOnlineOrderAllowedRemovedAt(null === $offer->getAllowedOnlineOrderTypes() ? new DateTimeImmutable() : null);
  957.         $allowedPaymentMethodsForCertificate json_decode($request->request->get('allowedPaymentMethodsForCertificate'), true);
  958.         $offer->setAllowedPaymentMethodsForCertificate($allowedPaymentMethodsForCertificate);
  959.         $offer->setPartnerOnlineRegistrationAllowed($request->request->getBoolean('partnerOnlineRegistrationAllowed'));
  960.         $partnerOnlineRegistrationLink trim($request->request->get('partnerOnlineRegistrationLink'));
  961.         $offer->setPartnerOnlineRegistrationLink(empty($partnerOnlineRegistrationLink) ? null $partnerOnlineRegistrationLink);
  962.         $purchaseKoeff $request->request->get('purchaseKoeff''');
  963.         if ($purchaseKoeff != '') {
  964.             $purchaseKoeff = (float)str_replace(',''.'$purchaseKoeff);
  965.         } else {
  966.             $purchaseKoeff null;
  967.         }
  968.         $offer->setPurchaseKoeff($purchaseKoeff);
  969.         if ($request->request->get('edit-offer-active-currency-calculator')) {
  970.             $bankCurrency $entityManager->getRepository(BankCurrency::class)->find($request->request->get('edit-offer-bank-currency-id'));
  971.             if ($bankCurrency) {
  972.                 $offer->setBankCurrency($bankCurrency);
  973.             }
  974.         }
  975.         $activeTill date_create_from_format('d.m.Y H:i:s'$request->request->get('edit-offer-active-till') . '00:00:00');
  976.         $currentTill $offer->getActiveTill();
  977.         $active $request->request->getBoolean('edit-offer-active');
  978.         $isActive $offer->isActive();
  979.         $showInHotFeed $request->request->get('hotFeed') == 'on';
  980.         $cityID City::DEFAULT_CITY_ID;
  981.         foreach ($offer->getCategories() as $categoryItem) {
  982.             if ($categoryItem->getCity() && $categoryItem->getCity()->getID() != City::DEFAULT_CITY_ID) {
  983.                 $cityID $categoryItem->getCity()->getID();
  984.                 break;
  985.             }
  986.         }
  987.         $hotFeed $entityManager->getRepository(HotFeed::class)->findBy(['entityTypeID' => Category::OFFER_CATEGORY_ID'entityID' => $offer->getID(), 'type' => HotFeed::TYPE_MAIN_PAGE]);
  988.         if (!$hotFeed && ($showInHotFeed || ($active && !$isActive) || ($active && date_format($activeTill'd') !== date_format($currentTill'd')))) {
  989.             $hotFeed = new HotFeed();
  990.             $hotFeed->setCreatedOn(new \DateTime());
  991.             $hotFeed->setEntityTypeID(Category::OFFER_CATEGORY_ID);
  992.             $hotFeed->setEntityID($offer->getID());
  993.             $hotFeed->setCityID($cityID);
  994.             $entityManager->persist($hotFeed);
  995.             $entityManager->flush($hotFeed);
  996.         } else if ($hotFeed && (!$showInHotFeed || !$active)) {
  997.             $entityManager->remove($hotFeed[0]);
  998.             $entityManager->flush($hotFeed);
  999.         }
  1000.         $showInTourismHotFeed $request->request->get('tourismHotFeed') == 'on';
  1001.         $hotFeed $entityManager->getRepository(HotFeed::class)->findBy(['entityTypeID' => Category::OFFER_CATEGORY_ID'entityID' => $offer->getID(), 'type' => HotFeed::TYPE_OFFER_TOURISM_PAGE]);
  1002.         if ($showInTourismHotFeed && !$hotFeed) {
  1003.             $hotFeed = new HotFeed();
  1004.             $hotFeed->setCreatedOn(new \DateTime());
  1005.             $hotFeed->setEntityTypeID(Category::OFFER_CATEGORY_ID);
  1006.             $hotFeed->setEntityID($offer->getID());
  1007.             $hotFeed->setType(HotFeed::TYPE_OFFER_TOURISM_PAGE);
  1008.             $hotFeed->setCityID($cityID);
  1009.             $entityManager->persist($hotFeed);
  1010.             $entityManager->flush($hotFeed);
  1011.         } else if (!$showInTourismHotFeed && $hotFeed) {
  1012.             $entityManager->remove($hotFeed[0]);
  1013.             $entityManager->flush($hotFeed);
  1014.         }
  1015.         $offer->setHideNoveltyLabel($request->request->has('hideNoveltyLabel'));
  1016.         $offer->setHideBannersInComments($request->request->has('hideBannersInComments'));
  1017.         $activeSince date_create_from_format('d.m.Y H:i:s'$request->request->get('edit-offer-active-since') . '00:00:00');
  1018.         $activeTill date_create_from_format('d.m.Y H:i:s'$request->request->get('edit-offer-active-till') . '00:00:00');
  1019.         $offer->setActiveSince($activeSince);
  1020.         $offer->setActiveTill($activeTill);
  1021.         $isHidden $offer->isHidden();
  1022.         $hidden $request->request->getBoolean('edit-offer-hidden');
  1023.         $offer->setHidden($hidden);
  1024.         $codeActiveTill date_create_from_format('d.m.Y H:i:s'$request->request->get('edit-offer-code-active-till') . '00:00:00');
  1025.         $offer->setCodeActiveTill($codeActiveTill);
  1026.         $user $entityManager->find(User::class, $this->getUser()->getID());
  1027.         $entityManager->persist($offer);
  1028.         if ($new) {
  1029.             if ($user) {
  1030.                 $user->addCreatedOffer($offer);
  1031.                 $entityManager->flush($user);
  1032.                 if ($user->hasRole(UserGroup::ROLE_JUNIOR)) {
  1033.                     $offer->setNeedReview(true);
  1034.                 }
  1035.             }
  1036.         }
  1037.         if (!$offer->isNeedReview() || $user->hasRole(UserGroup::ROLE_REVIEWER) || $user->hasRole(UserGroup::ROLE_ADMIN_ID)) {
  1038.             if ($active) {
  1039.                 $warningMessage = [];
  1040.                 $errorMessage = [];
  1041.                 if (count($request->request->get('edit-offer-detail-medias', [])) == 0) {
  1042.                     $errorMessage[] = "главное изображение";
  1043.                 }
  1044.                 if (!$offer->getTeaserMedia() && $request->request->get('editOfferTeaserImage') == '') {
  1045.                     $errorMessage[] = "тизер";
  1046.                 }
  1047.                 if (count($errorMessage) > 0) {
  1048.                     $result['errorMessage'] = 'Не введены следующие данные: ' implode(','$errorMessage);
  1049.                     return $result;
  1050.                 }
  1051.                 if (count($warningMessage) > 0) {
  1052.                     $result['warningMessage'] = 'Акция сохранена, проверте следующие данные: ' implode(','$warningMessage);
  1053.                 }
  1054.             }
  1055.             $offer->setActive($active);
  1056.             if (($offer->isNeedReview() || $offer->isOnReview()) && ($user->hasRole(UserGroup::ROLE_REVIEWER) || $user->hasRole(UserGroup::ROLE_ADMIN_ID))) {
  1057.                 $offer->setNeedReview(false);
  1058.                 $offer->setOnReview(false);
  1059.             }
  1060.             $entityManager->flush($offer);
  1061.             if (!$offerIsVisible && $offer->isVisible()) {
  1062.                 $offer->setRenewedOn(new \DateTime());
  1063.                 $entityManager->flush($offer);
  1064.             }
  1065.         } else {
  1066.             if ($request->request->get('sendOnReview') && $offer->isNeedReview()) {
  1067.                 $offer->setOnReview(true);
  1068.                 $entityManager->flush($offer);
  1069.                 $reviewers $entityManager->find(UserGroup::class, UserGroup::ROLE_REVIEWER)->getUsers();
  1070.                 if (!empty($reviewers)) {
  1071.                     foreach ($reviewers as $reviewer) {
  1072.                         $message $mailer->createMessage();
  1073.                         $message->setSubject('Новая акция на проверке')
  1074.                             ->setFrom("info@slivki.by"'Slivki.by')
  1075.                             ->setTo($reviewer->getEmail())
  1076.                             ->setBody("<b>Акция: </b>" $offer->getTitle(), 'text/html');
  1077.                         $mailer->send($message);
  1078.                     }
  1079.                 }
  1080.             }
  1081.         }
  1082.         $offerID $offer->getID();
  1083.         if (!$new && ($active != $isActive || $hidden != $isHidden)) {
  1084.             if ($active && !$hidden) {
  1085.                 $this->getCommentRepository()->updateCommentEntityHidden($offerIDComment::TYPE_OFFER_COMMENT'false');
  1086.             } else {
  1087.                 $this->getCommentRepository()->updateCommentEntityHidden($offerIDComment::TYPE_OFFER_COMMENT'true');
  1088.             }
  1089.         }
  1090.         $fastDelivery $request->request->get('fastDelivery');
  1091.         /** @var ProductFastDeliveryRepository $productFastDeliveryDql */
  1092.         $repositoryProductFastDelivery $this->getEntityManager()->getRepository(ProductFastDelivery::class);
  1093.         $repositoryProductFastDelivery->removeNotesByOffer($offer);
  1094.         if ($fastDelivery) {
  1095.             foreach ($fastDelivery as $itemFastDelivery) {
  1096.                 if (!$itemFastDelivery['productId']) {
  1097.                     continue;
  1098.                 }
  1099.                 $productFastDelivery = new ProductFastDelivery($offer$itemFastDelivery['productId'], $itemFastDelivery['deliveryTime'], isset($itemFastDelivery['isActive']));
  1100.                 $offer->addProductFastDelivery($productFastDelivery);
  1101.             }
  1102.         }
  1103.         $mediaRepository $entityManager->getRepository(Media::class);
  1104.         $mediaTypeRepository $entityManager->getRepository(MediaType::class);
  1105.         $shopMedias $request->request->get('edit-offer-shop-medias', []);
  1106.         foreach ($shopMedias as $key => $value) {
  1107.             $explodedValue explode('||'$value);
  1108.             $shopMediaID $explodedValue[0];
  1109.             $shopMediaFileName $explodedValue[1];
  1110.             if (strpos($shopMediaID'new-shop-media') !== false) {
  1111.                 $media = new Media();
  1112.                 $media->setEntityID($offerID);
  1113.                 $media->setMediaType($mediaTypeRepository->find(MediaType::TYPE_OFFER_SHOP_PHOTO_ID));
  1114.                 $media->setPath(MediaType::TYPE_OFFER_SHOP_PHOTO_PATH);
  1115.                 $media->setName($shopMediaFileName);
  1116.                 $entityManager->persist($media);
  1117.             } else {
  1118.                 $media $mediaRepository->find($shopMediaID);
  1119.             }
  1120.             $media->setPath(MediaType::TYPE_OFFER_SHOP_PHOTO_PATH);
  1121.             $media->setSortOrder($key);
  1122.             $entityManager->flush($media);
  1123.             $entityManager->detach($media);
  1124.         }
  1125.         $detailMedias $request->request->get('edit-offer-detail-medias', []);
  1126.         foreach ($detailMedias as $key => $value) {
  1127.             $explodedValue explode('||'$value);
  1128.             $detailMediaID $explodedValue[0];
  1129.             $detailMediaFileName $explodedValue[1];
  1130.             $isVideoDetail = isset($explodedValue[2]) ? (bool) $explodedValue[2] : false;
  1131.             $detailMediaFileName explode('/'$detailMediaFileName);
  1132.             if (strpos($detailMediaID'new-detail-media') !== false) {
  1133.                 $this->saveMedia(
  1134.                     $imageService,
  1135.                     $offerID,
  1136.                     MediaType::TYPE_OFFER_DETAIL_PHOTO_ID,
  1137.                     MediaType::TYPE_OFFER_DETAIL_PHOTO_PATH,
  1138.                     array_values(array_slice($detailMediaFileName, -1))[0],
  1139.                     $key 1,
  1140.                     true,
  1141.                     $isVideoDetail
  1142.                 );
  1143.             } else {
  1144.                 $media $mediaRepository->find($detailMediaID);
  1145.                 $media->setSortOrder($key 1);
  1146.                 $entityManager->flush($media);
  1147.                 $entityManager->detach($media);
  1148.             }
  1149.         }
  1150.         $teaserMediaFileName $request->request->get('editOfferTeaserImage');
  1151.         $offerTeaserMedia null;
  1152.         if ($teaserMediaFileName) {
  1153.             $editOfferDesktopTeaserImage $request->request->get('editOfferDesktopTeaserImage''');
  1154.             $editOfferMobileTeaserImage $request->request->get('editOfferMobileTeaserImage''');
  1155.             $editOfferAppTeaserImage $request->request->get('editOfferAppTeaserImage''');
  1156.             if ($editOfferDesktopTeaserImage != '') {
  1157.                 $offerTeaserMedia $this->setOfferTeaserMedia($cacheService$imageService$entityManagerMedia\OfferTeaserMedia::TYPE$offer$editOfferDesktopTeaserImage);
  1158.             }
  1159.             if ($editOfferMobileTeaserImage != '') {
  1160.                 $this->setOfferTeaserMedia($cacheService$imageService$entityManagerMedia\OfferMobileTeaserMedia::TYPE$offer$editOfferMobileTeaserImage);
  1161.             }
  1162.             if ($editOfferAppTeaserImage != '') {
  1163.                 $this->setOfferTeaserMedia($cacheService$imageService$entityManagerMedia\OfferAppTeaserMedia::TYPE$offer$editOfferAppTeaserImage);
  1164.             }
  1165.         }
  1166.         $editOfferTopBlockImage $request->request->get('editOfferTopBlockImage');
  1167.         if ($editOfferTopBlockImage) {
  1168.             foreach ($offer->getTopBlockMedias() as $mediaToRemove) {
  1169.                 $offer->removeTopBlockMedia($mediaToRemove);
  1170.                 $entityManager->remove($mediaToRemove);
  1171.                 $cacheService->deleteMedia($mediaToRemove->getID());
  1172.             }
  1173.             $offerTopBlockMedia = new Media\OfferTopBlockMedia();
  1174.             $offerTopBlockMedia->setName($editOfferTopBlockImage);
  1175.             $offerTopBlockMedia->setPath(MediaType::DEFAULT_IMAGE_PATH);
  1176.             $offer->addTopBlockMedia($offerTopBlockMedia);
  1177.         }
  1178.         $editOfferTopBlockMobileImage $request->request->get('editOfferTopBlockMobileImage');
  1179.         if ($editOfferTopBlockMobileImage) {
  1180.             foreach ($offer->getTopBlockMobileMedias() as $mediaToRemove) {
  1181.                 $offer->removeTopBlockMobileMedia($mediaToRemove);
  1182.                 $entityManager->remove($mediaToRemove);
  1183.                 $cacheService->deleteMedia($mediaToRemove->getID());
  1184.             }
  1185.             $offerTopBlockMobileMedia = new Media\OfferTopBlockMobileMedia();
  1186.             $offerTopBlockMobileMedia->setName($editOfferTopBlockMobileImage);
  1187.             $offerTopBlockMobileMedia->setPath(MediaType::DEFAULT_IMAGE_PATH);
  1188.             $offer->addTopBlockMobileMedia($offerTopBlockMobileMedia);
  1189.         }
  1190.         $editOfferOnlineOrderPopupLogoImage $request->request->get('editOfferOnlineOrderPopupLogoImage');
  1191.         if (null !== $editOfferOnlineOrderPopupLogoImage) {
  1192.             foreach ($offer->getOnlineOrderPopupLogoMedias() as $mediaToRemove) {
  1193.                 $offer->removeOnlineOrderPopupLogoMedia($mediaToRemove);
  1194.                 $entityManager->remove($mediaToRemove);
  1195.                 $cacheService->deleteMedia($mediaToRemove->getID());
  1196.             }
  1197.             $onlineOrderPopupLogoMedia = new OnlineOrderPopupLogoMedia();
  1198.             $onlineOrderPopupLogoMedia->setName($editOfferOnlineOrderPopupLogoImage);
  1199.             $onlineOrderPopupLogoMedia->setPath(MediaType::DEFAULT_IMAGE_PATH);
  1200.             $offer->addOnlineOrderPopupLogoMedia($onlineOrderPopupLogoMedia);
  1201.         }
  1202.         $editOfferCrtPdfBgImage $request->request->get('editOfferCrtPdfBgImage');
  1203.         if ($editOfferCrtPdfBgImage) {
  1204.             foreach ($offer->getGiftCertificatePdfBgMedias() as $mediaToRemove) {
  1205.                 $offer->removeGiftCertificatePdfBgMedia($mediaToRemove);
  1206.                 $entityManager->remove($mediaToRemove);
  1207.                 $cacheService->deleteMedia($mediaToRemove->getID());
  1208.             }
  1209.             $giftCertificatePdfBgMedia = new Media\GiftCertificatePdfBgMedia();
  1210.             $giftCertificatePdfBgMedia->setName($editOfferCrtPdfBgImage);
  1211.             $giftCertificatePdfBgMedia->setPath(MediaType::DEFAULT_IMAGE_PATH);
  1212.             $offer->addGiftCertificatePdfBgMedia($giftCertificatePdfBgMedia);
  1213.         }
  1214.         $mapLogoImage $request->request->get('editOfferMapLogoImage');
  1215.         if ($mapLogoImage) {
  1216.             foreach ($offer->getMapLogoMedias() as $mediaToRemove) {
  1217.                 $offer->removeMapLogoMedia($mediaToRemove);
  1218.                 $cacheService->deleteMedia($mediaToRemove->getID());
  1219.             }
  1220.             $offerMapLogoMedia = new OfferMapLogoMedia();
  1221.             $offerMapLogoMedia->setName($mapLogoImage);
  1222.             $offerMapLogoMedia->setPath(MediaType::DEFAULT_IMAGE_PATH);
  1223.             $offer->addMapLogoMedia($offerMapLogoMedia);
  1224.         }
  1225.         $deliveryZoneImage $request->request->get('editOfferDeliveryZoneImage');
  1226.         if (null !== $deliveryZoneImage) {
  1227.             foreach ($offer->getDeliveryZoneMedias() as $mediaToRemove) {
  1228.                 $offer->removeDeliveryZoneMedia($mediaToRemove);
  1229.                 $cacheService->deleteMedia($mediaToRemove->getID());
  1230.             }
  1231.             $offerDeliveryZoneMedia = new OfferDeliveryZoneMedia();
  1232.             $offerDeliveryZoneMedia->setName($deliveryZoneImage);
  1233.             $offerDeliveryZoneMedia->setPath(MediaType::DEFAULT_IMAGE_PATH);
  1234.             $offer->addDeliveryZoneMedia($offerDeliveryZoneMedia);
  1235.         }
  1236.         $additionalTeaserMediaFileName $request->request->get('editOfferAdditionalTeaserImage');
  1237.         if ($additionalTeaserMediaFileName) {
  1238.             $this->saveMedia($imageService$offerIDMediaType::TYPE_OFFER_ADDITIONAL_TEASER_IDMediaType::TYPE_OFFER_ADDITIONAL_TEASER_PATH$additionalTeaserMediaFileName);
  1239.         }
  1240.         $hotFeedfIconMediaFileName $request->request->get('editOfferHotFeedIcon');
  1241.         if ($hotFeedfIconMediaFileName) {
  1242.             $this->saveMedia($imageService$offerIDMediaType::TYPE_HOT_FEED_OFFER_ICON_IMAGE_IDMediaType::TYPE_HOT_FEED_ICON_IMAGE_PATH$hotFeedfIconMediaFileName);
  1243.         }
  1244.         $offerTeaserLogoFileName $request->request->get('editOfferTeaserLogo');
  1245.         if ($offerTeaserLogoFileName) {
  1246.             $this->saveMedia($imageService$offerIDMediaType::TYPE_OFFER_TEASER_LOGO_IDMediaType::TYPE_OFFER_TEASER_LOGO_PATH$offerTeaserLogoFileName);
  1247.         }
  1248.         $seoRepository $entityManager->getRepository(Seo::class);
  1249.         $requestAlias $request->request->get('edit-offer-alias');
  1250.         $createdOn $offer->getCreatedOn()->setTime(00)->modify('+30 days');
  1251.         $nowDate = new \DateTime();
  1252.         $entitySeo $seoRepository->getByEntity(SeoRepository::RESOURCE_URL_OFFER_DETAILS$offerID);
  1253.         $currentAlias $entitySeo $entitySeo->getMainAlias() : '';
  1254.         if (($requestAlias && $requestAlias != $currentAlias) && $nowDate $createdOn && $user->hasRole(UserGroup::ROLE_MANAGER_ID) && !$user->hasRole(UserGroup::ROLE_ADMIN_ID)) {
  1255.             $result['message'] = array(
  1256.                 'title' => 'Ошибка!',
  1257.                 'message' => 'В этой акции недоступно изменение ссылки, обратитесь к администратору',
  1258.                 'type' => 'modal-danger'
  1259.             );
  1260.             return $result;
  1261.         }
  1262.         $alias = new Seo();
  1263.         $alias->setMainAlias($requestAlias $requestAlias '');
  1264.         $alias->setEntityID($offerID);
  1265.         $alias->setActive(true);
  1266.         $alias->setMetaTitle($request->request->get('edit-offer-meta-title'));
  1267.         $alias->setMetaDescription($request->request->get('edit-offer-meta-description'));
  1268.         $alias->setMetaKeywords($request->request->get('edit-offer-meta-keywords'));
  1269.         $alias->setResourceURL('Slivki:Default:details');
  1270.         $offerCity $offerRepository->getOfferCity($offerID);
  1271.         if (null !== $offerCity) {
  1272.             $alias->setDomain($offerCity->getDomain());
  1273.         }
  1274.         if ($requestAlias && !$seoRepository->setAlias($alias)) {
  1275.             $result['message'] = array(
  1276.                 'title' => 'Ошибка!',
  1277.                 'message' => 'Алиас ' $requestAlias ' уже существует!',
  1278.                 'type' => 'modal-danger'
  1279.             );
  1280.             return $result;
  1281.         }
  1282.         $codeCostFromForm $request->request->get('edit-offer-code-cost');
  1283.         if (!empty($codeCostFromForm) && is_numeric($codeCostFromForm)) {
  1284.             $offer->setCodeCost($codeCostFromForm);
  1285.         } else {
  1286.             $siteSettings $entityManager->getRepository(SiteSettings::class)->find(1);
  1287.             if (null !== $offerCity && $new) {
  1288.                 if ($offerCity->getID() !== City::DEFAULT_CITY_ID) {
  1289.                     $codeCost $offerCity->getID() === City::TASHKENT_CITY_ID
  1290.                         SiteSettings::TASHKENT_CODE_COST
  1291.                         $siteSettings->getRegionsCodeCost();
  1292.                     $offer->setCodeCost($codeCost);
  1293.                 } else {
  1294.                     $offer->setCodeCost(null);
  1295.                 }
  1296.             }
  1297.         }
  1298.         $descriptionRepository $entityManager->getRepository(EntityDescription::class);
  1299.         $descriptions = [
  1300.             [
  1301.                 'repository' => $descriptionRepository->findOneBy(['entityID' => $offerID'typeID' => EntityDescription::TYPE_OFFER_CONDITIONS_ID]),
  1302.                 'request' => $request->request->get('description-condition'),
  1303.                 'type' => EntityDescription::TYPE_OFFER_CONDITIONS_ID
  1304.             ],
  1305.             [
  1306.                 'repository' => $descriptionRepository->findOneBy(['entityID' => $offerID'typeID' => EntityDescription::TYPE_OFFER_FEATURES_ID]),
  1307.                 'request' => $request->request->get('description-features'),
  1308.                 'type' => EntityDescription::TYPE_OFFER_FEATURES_ID
  1309.             ],
  1310.             [
  1311.                 'repository' => $descriptionRepository->findOneBy(['entityID' => $offerID'typeID' => EntityDescription::TYPE_OFFER_LOCATION_ID]),
  1312.                 'request' => $request->request->get('description-location'),
  1313.                 'type' => EntityDescription::TYPE_OFFER_LOCATION_ID
  1314.             ],
  1315.             [
  1316.                 'repository' => $descriptionRepository->findOneBy(['entityID' => $offerID'typeID' => EntityDescription::TYPE_OFFER_LOGO_ID]),
  1317.                 'request' => $request->request->get('description-logo'),
  1318.                 'type' => EntityDescription::TYPE_OFFER_LOGO_ID
  1319.             ],
  1320.             [
  1321.                 'repository' => $descriptionRepository->findOneBy(['entityID' => $offerID'typeID' => EntityDescription::TYPE_OFFER_LEGAL_ID]),
  1322.                 'request' => $request->request->get('description-legal'),
  1323.                 'type' => EntityDescription::TYPE_OFFER_LEGAL_ID
  1324.             ], [
  1325.                 'repository' => $descriptionRepository->findOneBy(['entityID' => $offerID'typeID' => EntityDescription::TYPE_OFFER_WORKING_HOURS_ID]),
  1326.                 'request' => strip_tags($request->request->get('edit-offer-common-working-hours'''), '<strong><em><span><br>'),
  1327.                 'type' => EntityDescription::TYPE_OFFER_WORKING_HOURS_ID
  1328.             ],
  1329.             [
  1330.                 'repository' => $descriptionRepository->findOneBy(['entityID' => $offerID'typeID' => EntityDescription::TYPE_VENDOR_CONDITION]),
  1331.                 'request' => $request->request->get('vendorCondition'),
  1332.                 'type' => EntityDescription::TYPE_VENDOR_CONDITION,
  1333.             ],
  1334.             [
  1335.                 'repository' => $descriptionRepository->findOneBy(['entityID' => $offerID'typeID' => EntityDescription::TYPE_BRIEF_DELIVERY_CONDITION]),
  1336.                 'request' => $request->request->get('briefDeliveryCondition'),
  1337.                 'type' => EntityDescription::TYPE_BRIEF_DELIVERY_CONDITION,
  1338.             ],
  1339.         ];
  1340.         foreach ($descriptions as $description) {
  1341.             if (mb_strpos($description['request'], 'WebKitFormBoundary') !== false) {
  1342.                 return ['errorMessage' => 'Произошла ошибка при сохранении описания! Данные не сохранены! Попробуйте еще раз!'];
  1343.             }
  1344.             if (!$description['repository']) {
  1345.                 $description['repository'] = new EntityDescription();
  1346.                 $description['repository']->setTypeID($description['type']);
  1347.                 $description['repository']->setOffer($offer);
  1348.                 $offer->addDescription($description['repository']);
  1349.                 $entityManager->persist($description['repository']);
  1350.             }
  1351.             $description['repository']->setDescription($this->deleteExtraLines(trim($description['request'])));
  1352.             $offer->setLuceneReindex(true);
  1353.             $entityManager->flush($description['repository']);
  1354.         }
  1355.         $editDescriptionList array_filter($request->request->all(), function ($key) {
  1356.             return strpos($key'editDescription') === 0;
  1357.         }, ARRAY_FILTER_USE_KEY);
  1358.         $result['addedDescriptionIDList'] = [];
  1359.         foreach ($editDescriptionList as $key => $description) {
  1360.             if (mb_strpos($description'WebKitFormBoundary') !== false) {
  1361.                 return ['errorMessage' => 'Произошла ошибка при сохранении описания! Данные не сохранены! Попробуйте еще раз!'];
  1362.             }
  1363.             $descriptionID str_replace('editDescription'''$key);
  1364.             $descriptionID explode('_'$descriptionID);
  1365.             $sortOrder $descriptionID[1];
  1366.             $descriptionID $descriptionID[0];
  1367.             if (strpos($descriptionID'new-') !== false) {
  1368.                 $offerDescription = new EntityDescription();
  1369.                 $offer->addDescription($offerDescription);
  1370.                 $offerDescription->setDescription($this->setImageRatio($kernel$description));
  1371.                 $offerDescription->setTypeID(EntityDescription::TYPE_OFFER_DESCRIPTION_ID);
  1372.                 $offerDescription->setOffer($offer);
  1373.                 $entityManager->persist($offerDescription);
  1374.                 $result['addedDescriptionIDList'][$descriptionID] = $offerDescription->getID();
  1375.             } else {
  1376.                 $offerDescription $entityManager->find(EntityDescription::class, $descriptionID);
  1377.             }
  1378.             if ($offerDescription) {
  1379.                 if (strip_tags($description) != "") {
  1380.                     $offerDescription->setDescription($this->setImageRatio($kernel$description));
  1381.                 }
  1382.                 $offerDescription->setSortOrder($sortOrder);
  1383.                 $entityManager->flush($offerDescription);
  1384.             }
  1385.         }
  1386.         $offerNote strip_tags($request->request->get('offerNote'''), '<strong><em><span><br>');
  1387.         $this->messageBus->dispatch(new EditOfferNoteCommand($offerID$offerNote));
  1388.         $result['addedDescriptionSliderImageIDList'] = [];
  1389.         $requestGalleryImageList $request->request->get('editOfferDescriptionGalery', []);
  1390.         foreach ($requestGalleryImageList as $key => $value) {
  1391.             $explodedValue explode('||'$value);
  1392.             $offerDescriptionSliderImageID $explodedValue[0];
  1393.             $offerDescriptionSliderImageUri EntityDescriptionSliderImage::IMAGE_PATH $explodedValue[1];
  1394.             if (strpos($offerDescriptionSliderImageID'newOfferDescriptionGaleryImage') !== false) {
  1395.                 $offerDescriptionSliderImageIDExploded explode('_'$offerDescriptionSliderImageID);
  1396.                 $offerDescriptionID $offerDescriptionSliderImageIDExploded[1];
  1397.                 if (strpos($offerDescriptionID'new') !== false) {
  1398.                     $offerDescriptionID $result['addedDescriptionIDList'][$offerDescriptionID];
  1399.                 }
  1400.                 $offerDescription $entityManager->find(EntityDescription::class, $offerDescriptionID);
  1401.                 $offerDescriptionSliderImage = new EntityDescriptionSliderImage();
  1402.                 $offerDescriptionSliderImage->setEntityDescription($offerDescription);
  1403.                 $offerDescriptionSliderImage->setImageUrl($offerDescriptionSliderImageUri);
  1404.                 $entityManager->persist($offerDescriptionSliderImage);
  1405.                 $result['addedDescriptionSliderImageIDList'][$offerDescriptionSliderImageID] = $offerDescriptionSliderImage->getID();
  1406.             } else {
  1407.                 $offerDescriptionSliderImage $entityManager->find(EntityDescriptionSliderImage::class, $offerDescriptionSliderImageID);
  1408.             }
  1409.             $offerDescriptionSliderImage->setSortOrder($key);
  1410.             $entityManager->flush($offerDescriptionSliderImage);
  1411.             $entityManager->detach($offerDescriptionSliderImage);
  1412.         }
  1413.         $geoLocationList $session->get('geoLocationList', []);
  1414.         $geoLocationRepository $entityManager->getRepository(GeoLocation::class);
  1415.         foreach ($geoLocationList as $geoLocationItem) {
  1416.             $geoLocation null;
  1417.             if (strpos($geoLocationItem['ID'], 'new-') === false) {
  1418.                 $geoLocation $geoLocationRepository->find($geoLocationItem['ID']);
  1419.             }
  1420.             if (!$geoLocation) {
  1421.                 $geoLocation = new GeoLocation();
  1422.                 $offer->addGeoLocation($geoLocation);
  1423.                 $entityManager->persist($geoLocation);
  1424.             }
  1425.             $geoLocation->setCity($geoLocationItem['city']);
  1426.             $geoLocation->setStreet($geoLocationItem['street']);
  1427.             $geoLocation->setHouse($geoLocationItem['house']);
  1428.             $geoLocation->setLatitude($geoLocationItem['latitude']);
  1429.             $geoLocation->setLongitude($geoLocationItem['longitude']);
  1430.             $geoLocation->setBigMapMarker($geoLocationItem['bigMapMarker']);
  1431.             if ($geoLocationItem['description'] == '') {
  1432.                 // parse supplier brand name
  1433.                 $descriptionLogo $request->request->get('description-logo''');
  1434.                 $descriptionLogo strip_tags($descriptionLogo);
  1435.                 preg_match('/"(.*?)"/'$descriptionLogo$match);
  1436.                 if (isset($match[0])) {
  1437.                     $geoLocationItem['description'] = $match[0];
  1438.                 }
  1439.             }
  1440.             $geoLocation->setDescription($geoLocationItem['description']);
  1441.             $geoLocation->setLabel($geoLocationItem['label']);
  1442.             $geoLocation->setWorkingHours($geoLocationItem['workingHours']);
  1443.             $geoLocation->setPickupPointPartnerID($geoLocationItem['pickupPointPartnerID']);
  1444.             $geoLocation->setPickupPointBelTransSatDepotID(empty($geoLocationItem['pickupPointBelTransSatDepotID']) ? null trim($geoLocationItem['pickupPointBelTransSatDepotID']));
  1445.             $geoLocation->setPickupPointSchedule($geoLocationItem['pickupPointSchedule']);
  1446.             $geoLocation->setBepaidCredentials(empty($geoLocationItem['bepaidCredentials']) ? null : \trim($geoLocationItem['bepaidCredentials']));
  1447.             $geoLocation->setCallbackChatId($geoLocationItem['callbackChatId']);
  1448.             if (!empty($geoLocationItem['latitude']) && !empty($geoLocationItem['longitude'])) {
  1449.                 $point = (new Factory())
  1450.                     ->createPoint(
  1451.                         Dimension::DIMENSION_2D,
  1452.                         [
  1453.                             'x' => (float) $geoLocationItem['latitude'],
  1454.                             'y' => (float) $geoLocationItem['longitude'],
  1455.                             'z' => null,
  1456.                             'm' => null,
  1457.                         ],
  1458.                         GeoLocation::SRID
  1459.                     );
  1460.                 $geoLocation->setPoint($point);
  1461.             }
  1462.             $cityArea $entityManager->getRepository(CityArea::class)->find($geoLocationItem['cityArea']);
  1463.             if ($cityArea) {
  1464.                 $cityArea->addGeoLocations($geoLocation);
  1465.                 $entityManager->flush($cityArea);
  1466.             } else {
  1467.                 $entityManager->flush($geoLocation);
  1468.             }
  1469.             $session->remove('geoLocationList');
  1470.         }
  1471.         $addressPosition $request->request->get('edit-offer-address-position');
  1472.         foreach (json_decode($addressPositiontrue) as $address) {
  1473.             if (strpos($address['addressID'], 'new-') === false) {
  1474.                 $geoLocation $geoLocationRepository->find($address['addressID']);
  1475.                 $geoLocation->setSortOrder($address['position']);
  1476.             }
  1477.         }
  1478.         $requestAntiTagIDList $request->request->get('admin-antitag-id') ? $request->request->get('admin-antitag-id') : [];
  1479.         foreach ($requestAntiTagIDList as $index => $tagID) {
  1480.             $tag $entityManager->getRepository(AntiTag::class)->find($tagID);
  1481.             if ($tag) {
  1482.                 if ($request->request->get('admin-antitag-deleted')[$index] == "true") {
  1483.                     $offer->deleteAntiTag($tag);
  1484.                 } else {
  1485.                     if ($tag->getTag() != $request->request->get('admin-antitag-tag')[$index]) {
  1486.                         $tag->setTag($request->request->get('admin-antitag-tag')[$index]);
  1487.                         $entityManager->flush($tag);
  1488.                     }
  1489.                     $offer->addAntiTag($tag);
  1490.                 }
  1491.             }
  1492.         }
  1493.         $offer->setTelegram($request->request->get('editTelegramInfo'));
  1494.         $offer->setViber($request->request->get('editViberInfo'));
  1495.         $offer->setMessengerCallBack(
  1496.             null !== $request->request->get('editMessengerCallBack')
  1497.             ? $this->serializer->serialize($request->request->get('editMessengerCallBack'), SerializerConfig::JSON)
  1498.             : null
  1499.         );
  1500.         $requestPhoneNumberList array_filter($request->request->all(), static function ($key) {
  1501.             return strpos($key'editOfferPhoneNumber_') === 0;
  1502.         }, ARRAY_FILTER_USE_KEY);
  1503.         foreach ($requestPhoneNumberList as $keyPhoneNumber => $phoneNumber) {
  1504.             $requestPhoneNumberList[$keyPhoneNumber] = self::BELARUS_PHONE_CODE $phoneNumber;
  1505.         }
  1506.         $previousPhoneNumberList $offer->getPhoneNumbers()->toArray();
  1507.         $requestPhoneNumberIDList = [];
  1508.         foreach ($requestPhoneNumberList as $key => $requestPhoneNumber) {
  1509.             $requestPhoneNumberID explode('_'$key);
  1510.             if (!isset($requestPhoneNumberID[1])) {
  1511.                 continue;
  1512.             }
  1513.             $requestPhoneNumberID $requestPhoneNumberID[1];
  1514.             $requestPhoneNumberIDList[] = $requestPhoneNumberID;
  1515.             $requestPhoneNumber trim($requestPhoneNumber);
  1516.             if (!strpos($key'new') === false) {
  1517.                 if ($requestPhoneNumber != '') {
  1518.                     $phoneNumber = new PhoneNumber();
  1519.                     $phoneNumber->setNumber($requestPhoneNumber);
  1520.                     $phoneNumber->setLink(CommonUtil::phoneNumber2Link($requestPhoneNumber));
  1521.                     $phoneNumber->setLabel($request->request->get('editOfferPhoneNumberLabel_' $requestPhoneNumberID));
  1522.                     $phoneNumberGeoLocationIDList $request->request->get('editOfferPhoneNumberAddress_' $requestPhoneNumberID, []);
  1523.                     foreach ($phoneNumberGeoLocationIDList as $phoneNumberGeoLocationID) {
  1524.                         $phoneNumberGeoLocation $entityManager->getRepository(GeoLocation::class)->find($phoneNumberGeoLocationID);
  1525.                         if ($phoneNumberGeoLocation) {
  1526.                             $phoneNumber->addGeoLocation($phoneNumberGeoLocation);
  1527.                         }
  1528.                     }
  1529.                     $offer->addPhoneNumber($phoneNumber);
  1530.                 }
  1531.             } else {
  1532.                 $phoneNumber $entityManager->getRepository(PhoneNumber::class)->find($requestPhoneNumberID);
  1533.                 if ($phoneNumber) {
  1534.                     $phoneNumber->setNumber($requestPhoneNumber);
  1535.                     $phoneNumber->setLink(CommonUtil::phoneNumber2Link($requestPhoneNumber));
  1536.                     $phoneNumber->setLabel($request->request->get('editOfferPhoneNumberLabel_' $requestPhoneNumberID));
  1537.                     $phoneNumberGeoLocationIDList $request->request->get('editOfferPhoneNumberAddress_' $requestPhoneNumberID, []);
  1538.                     foreach ($phoneNumberGeoLocationIDList as $phoneNumberGeoLocationID) {
  1539.                         $phoneNumberGeoLocation $entityManager->getRepository(GeoLocation::class)->find($phoneNumberGeoLocationID);
  1540.                         if ($phoneNumberGeoLocation) {
  1541.                             $phoneNumber->addGeoLocation($phoneNumberGeoLocation);
  1542.                         }
  1543.                     }
  1544.                     foreach ($phoneNumber->getGeoLocations() as $phoneNumberCurrentGeoLocation) {
  1545.                         if (!in_array($phoneNumberCurrentGeoLocation->getID(), $phoneNumberGeoLocationIDList)) {
  1546.                             $phoneNumber->removeGeoLocation($phoneNumberCurrentGeoLocation);
  1547.                         }
  1548.                     }
  1549.                     $entityManager->flush($phoneNumber);
  1550.                 }
  1551.             }
  1552.         }
  1553.         foreach ($previousPhoneNumberList as $currentPhoneNumber) {
  1554.             if (!in_array($currentPhoneNumber->getID(), $requestPhoneNumberIDList)) {
  1555.                 $offer->removePhoneNumberByID($currentPhoneNumber->getID());
  1556.                 $offerCacheService->deletePhoneNumber($currentPhoneNumber->getID());
  1557.                 $entityManager->remove($currentPhoneNumber);
  1558.                 $entityManager->flush($currentPhoneNumber);
  1559.             }
  1560.         }
  1561.         $offer->setLuceneReindex(true);
  1562.         $entityManager->flush($offer);
  1563.         $offerMailingTeaserMedia $offer->getMailingTeaserMedia();
  1564.         if ($offer->hasNotDefaultCityCategory()) {
  1565.             if (!$offer->getCaptionName()) {
  1566.                 foreach ($offer->getMailingTeaserMedias() as $mediaToRemove) {
  1567.                     $offer->removeMailingTeaserMedia($mediaToRemove);
  1568.                     $entityManager->remove($mediaToRemove);
  1569.                     $cacheService->deleteMedia($mediaToRemove->getID());
  1570.                 }
  1571.                 $entityManager->flush();
  1572.             } else {
  1573.                 $imageName $imageService->saveMailingTeaserImage($offer);
  1574.                 if ($imageName) {
  1575.                     foreach ($offer->getMailingTeaserMedias() as $mediaToRemove) {
  1576.                         $offer->removeMailingTeaserMedia($mediaToRemove);
  1577.                         $entityManager->remove($mediaToRemove);
  1578.                         $cacheService->deleteMedia($mediaToRemove->getID());
  1579.                     }
  1580.                     if (!$offerMailingTeaserMedia) {
  1581.                         $offerMailingTeaserMedia = new Media\OfferMailingTeaserMedia();
  1582.                     }
  1583.                     $offerMailingTeaserMedia->setName($imageName);
  1584.                     $offerMailingTeaserMedia->setPath($offer->getTeaserMedia()->getPath());
  1585.                     $offer->addMailingTeaserMedia($offerMailingTeaserMedia);
  1586.                     $entityManager->flush();
  1587.                     foreach ($offerMailingTeaserMedia->getSizes() as $mediasSize) {
  1588.                         $imageService->resizeImage($offerMailingTeaserMedia$mediasSize->getWidth(), $mediasSize->getHeight());
  1589.                     }
  1590.                 }
  1591.             }
  1592.         } else if ($offerMailingTeaserMedia) {
  1593.             foreach ($offer->getMailingTeaserMedias() as $mediaToRemove) {
  1594.                 $offer->removeMailingTeaserMedia($mediaToRemove);
  1595.                 $entityManager->remove($mediaToRemove);
  1596.                 $cacheService->deleteMedia($mediaToRemove->getID());
  1597.             }
  1598.             $entityManager->flush();
  1599.         }
  1600.         $offerShopMedias $mediaRepository->getOfferShopMedias($offerID);
  1601.         $result['offerShopMedias'] = $this->renderView('Slivki/admin/offers/shop_medias.html.twig', [
  1602.             'images' => $offerShopMedias,
  1603.             'interiorGalleryMediaIds' => $this->interiorGalleryDao->getByOfferId($offerID),
  1604.         ]);
  1605.         $offerDetailMedias $mediaRepository->getOfferDetailMedias($offerID);
  1606.         $result['offerDetailMedias'] = $this->get('twig')->render('Slivki/admin/offers/detail_medias.html.twig', array('images' => $offerDetailMedias));
  1607.         $manager null;
  1608.         $requestDirectorIDList $request->request->get('admin-director-id', []);
  1609.         foreach ($requestDirectorIDList as $index => $directorID) {
  1610.             $director $entityManager->getRepository(Director::class)->find($directorID);
  1611.             if ($director) {
  1612.                 if ($request->request->get('admin-director-deleted')[$index] == "true") {
  1613.                     $director->removeOffer($offer);
  1614.                 } else if (!$offer->getDirectors()->contains($director)) {
  1615.                     $director->addOffer($offer);
  1616.                     $manager $director->getManager();
  1617.                     if ($manager) {
  1618.                         $manager->addOffer($offer);
  1619.                     }
  1620.                 }
  1621.                 $entityManager->flush($director);
  1622.             }
  1623.         }
  1624.         if (!$manager) {
  1625.             $offerManagerID $request->request->get('offerManager'0);
  1626.             if ($offerManagerID 0) {
  1627.                 $offerManager $entityManager->find(User::class, $offerManagerID);
  1628.                 if ($offerManager) {
  1629.                     $offerManager->addOffer($offer);
  1630.                 }
  1631.             }
  1632.         }
  1633.         // Set Paid Categories and refresh positions
  1634.         $offerPayedCategoryRepository $entityManager->getRepository(OfferPayedCategory::class);
  1635.         $offerCategoryPositionRepository $entityManager->getRepository(OfferCategoryPosition::class);
  1636.         if ($offer->isActive() && $offer->isInActivePeriod()) {
  1637.             $categoriesToRefreshIDList = [];
  1638.             $requestOfferPayedCategoryIDList $request->request->get('payedCategories') ? $request->request->get('payedCategories') : [];
  1639.             $offerPayedCategories $offerPayedCategoryRepository->getPayedCategoriesByEntityID($offerIDCategory::OFFER_CATEGORY_ID);
  1640.             /** * @var OfferPayedCategory $offerPayedCategory */
  1641.             foreach ($offerPayedCategories as $offerPayedCategory) {
  1642.                 $requestOfferPayedCategoryIDListKey array_search($offerPayedCategory->getCategoryID(), $requestOfferPayedCategoryIDList);
  1643.                 if ($requestOfferPayedCategoryIDListKey === false) {
  1644.                     $entityManager->remove($offerPayedCategory);
  1645.                     $categoriesToRefreshIDList[] = $offerPayedCategory->getCategoryID();
  1646.                     $this->logOperatorAction($request$requestOfferID"remove paid category " $offerPayedCategory->getCategoryID(), OperatorActionLog::SET_PAID_OFFER_CATEGORY);
  1647.                 } else {
  1648.                     unset($requestOfferPayedCategoryIDList[$requestOfferPayedCategoryIDListKey]);
  1649.                 }
  1650.             }
  1651.             $entityManager->flush();
  1652.             foreach ($requestOfferPayedCategoryIDList as $categoryID) {
  1653.                 $offerPayedCategory = new OfferPayedCategory();
  1654.                 $offerPayedCategory->setEntityID($offerID);
  1655.                 $offerPayedCategory->setCategoryID($categoryID);
  1656.                 $offerPayedCategory->setPosition($offerPayedCategoryRepository->getNextOfferPayedCategoryPosition($categoryID));
  1657.                 $entityManager->persist($offerPayedCategory);
  1658.                 $entityManager->flush();
  1659.                 $categoriesToRefreshIDList[] = $categoryID;
  1660.                 $this->logOperatorAction($request$requestOfferID"add paid category " $offerPayedCategory->getCategoryID(), OperatorActionLog::SET_PAID_OFFER_CATEGORY);
  1661.             }
  1662.             $offerCategoryPositionList $offerCategoryPositionRepository->getOfferCategoryPositionByEntityID($offerIDCategory::OFFER_CATEGORY_ID);
  1663.             foreach ($offerCategoryPositionList as $offerCategoryPosition) {
  1664.                 if (!in_array($offerCategoryPosition->getCategoryID(), $categoryIDList)) {
  1665.                     $entityManager->remove($offerCategoryPosition);
  1666.                 }
  1667.             }
  1668.             $entityManager->flush();
  1669.             $unlimitedCodes $request->request->get('edit-offer-unlimited-codes') == 'on';
  1670.             $entityOption $entityManager->getRepository(EntityOption::class)->findOneBy([
  1671.                 'entityID' => $offerID,
  1672.                 'entityTypeID' => EntityOption::OFFER_ENTITY_TYPE,
  1673.                 'name' => EntityOption::OPTION_CODES_UNLIMITED,
  1674.             ]);
  1675.             if ($unlimitedCodes) {
  1676.                 if (!$entityOption) {
  1677.                     $entityOption = new EntityOption();
  1678.                     $entityManager->persist($entityOption);
  1679.                     $entityOption->setEntityID($offerID);
  1680.                     $entityOption->setEntityTypeID(EntityOption::OFFER_ENTITY_TYPE);
  1681.                     $entityOption->setName(EntityOption::OPTION_CODES_UNLIMITED);
  1682.                     $entityManager->flush();
  1683.                 }
  1684.             } else {
  1685.                 if ($entityOption) {
  1686.                     $entityManager->remove($entityOption);
  1687.                     $entityManager->flush();
  1688.                 }
  1689.             }
  1690.             foreach ($categoryIDList as $categoryID) {
  1691.                 $offerCategoryPosition $offerCategoryPositionRepository->findOneBy(['entityID' => $offerID'categoryID' => $categoryID]);
  1692.                 if (!$offerCategoryPosition) {
  1693.                     $position 99999;
  1694.                     if ($categoryID == Category::NEW_OFFER_CATEGORY_ID) {
  1695.                         $position 25;
  1696.                     }
  1697.                     $offerCategoryPosition = new OfferCategoryPosition();
  1698.                     $offerCategoryPosition->setEntityID($offerID);
  1699.                     $offerCategoryPosition->setCategoryID($categoryID);
  1700.                     $offerCategoryPosition->setPosition($position);
  1701.                     $entityManager->persist($offerCategoryPosition);
  1702.                     $entityManager->flush();
  1703.                     if ($categoryID == Category::NEW_OFFER_CATEGORY_ID) {
  1704.                         $sql 'update offer_category_position set position = position + 1 
  1705.                           where category_id = ' Category::NEW_OFFER_CATEGORY_ID ' and position >= ' $position ' and entity_id <> ' $offerID;
  1706.                         $entityManager->getConnection()->executeQuery($sql);
  1707.                     }
  1708.                 }
  1709.             }
  1710.             foreach (array_unique($categoriesToRefreshIDList) as $categoryID) {
  1711.                 $this->refreshOfferCategoriesPosition($kernel$categoryIDfalse);
  1712.             }
  1713.         } else {
  1714.             $offerCategoryPositionList $offerCategoryPositionRepository->getOfferCategoryPositionByEntityID($offerIDCategory::OFFER_CATEGORY_ID);
  1715.             foreach ($offerCategoryPositionList as $offerCategoryPosition) {
  1716.                 $entityManager->remove($offerCategoryPosition);
  1717.             }
  1718.             $offerPayedCategoryList $offerPayedCategoryRepository->getPayedCategoriesByEntityID($offerIDCategory::OFFER_CATEGORY_ID);
  1719.             foreach ($offerPayedCategoryList as $offerPayedCategory) {
  1720.                 $entityManager->remove($offerPayedCategory);
  1721.             }
  1722.             $entityManager->flush();
  1723.         }
  1724.         if ($offerPreviousActiveTill && $offerPreviousActiveTill $offer->getActiveTill()) {
  1725.             $renewedOffer $entityManager->getRepository(RenewedOffer::class)->findBy([
  1726.                 'offer' => $offer,
  1727.                 'sentUserNotification' => false
  1728.             ]);
  1729.             if (!$renewedOffer) {
  1730.                 $renewedOffer = new RenewedOffer();
  1731.                 $renewedOffer->setOffer($offer);
  1732.                 $renewedOffer->setOfferPreviousActiveTill($offerPreviousActiveTill);
  1733.                 $entityManager->persist($renewedOffer);
  1734.                 $entityManager->flush();
  1735.             }
  1736.         }
  1737.         $descriptionRepository $entityManager->getRepository(EntityDescription::class);
  1738.         $description $descriptionRepository->findOneBy(['entityID' => $offerID'typeID' => EntityDescription::TYPE_FOOD_ORDER_DESCRIPTION_ID]);
  1739.         $requestDescription trim($request->request->get('edit-offer-food-delivery-description'''));
  1740.         if (!$description) {
  1741.             $description = new EntityDescription();
  1742.             $description->setOffer($offer);
  1743.             $description->setTypeID(EntityDescription::TYPE_FOOD_ORDER_DESCRIPTION_ID);
  1744.             $entityManager->persist($description);
  1745.         }
  1746.         $description->setDescription($requestDescription);
  1747.         $offer->setDeliveryPrice((double)str_replace(',''.'$request->request->get('edit-offer-food-delivery-price')));
  1748.         $offer->setSumForFreeDelivery((double)str_replace(",""."$request->request->get('edit-offer-food-lower-delivery-price')));
  1749.         $requestOfferItems json_decode($request->request->get('offerItems'), true);
  1750.         $offerItems $offer->getItems();
  1751.         if (is_array($requestOfferItems)) {
  1752.             foreach ($offerItems as $offerItem) {
  1753.                 $deleteItem true;
  1754.                 foreach ($requestOfferItems as $requestOfferItem) {
  1755.                     if ($requestOfferItem['id'] == $offerItem->getID()) {
  1756.                         $deleteItem false;
  1757.                         break;
  1758.                     }
  1759.                 }
  1760.                 if ($deleteItem) {
  1761.                     $offerCacheService->deleteExtension($offerItem->getID());
  1762.                     $entityManager->remove($offerItem);
  1763.                 }
  1764.             }
  1765.             foreach ($requestOfferItems as $requestOfferItem) {
  1766.                 $requestOfferItemID $requestOfferItem['id'];
  1767.                 if (strpos($requestOfferItemID'new') !== false) {
  1768.                     $offerItem = new ItemOfferExtension();
  1769.                     $offerItem->setOffer($offer);
  1770.                     $entityManager->persist($offerItem);
  1771.                 } else {
  1772.                     $offerItem $entityManager->find(ItemOfferExtension::class, $requestOfferItemID);
  1773.                 }
  1774.                 $offerItem->setName($requestOfferItem['name']);
  1775.                 $offerItem->setPrice((float)str_replace(',''.'$requestOfferItem['price']));
  1776.                 $offerItem->setOfferPrice((float)str_replace(',''.'$requestOfferItem['offerPrice']));
  1777.                 if (trim($requestOfferItem['codePrice']) == '') {
  1778.                     $offerItem->setCodePrice(null);
  1779.                 } else {
  1780.                     $offerItem->setCodePrice((float)str_replace(',''.'$requestOfferItem['codePrice']));
  1781.                 }
  1782.                 $offerItem->setDescription($requestOfferItem['description']);
  1783.                 $offerItem->setCodePrefix($requestOfferItem['prefix']);
  1784.             }
  1785.         }
  1786.         $bookedDates $request->request->get('edit-offer-booked-dates');
  1787.         if ($bookedDates != '') {
  1788.             $bookedDates explode(','trim($bookedDates));
  1789.             usort($bookedDates, function ($a$b) {
  1790.                 return strtotime($a) - strtotime($b);
  1791.             });
  1792.             $bookedDates implode(","$bookedDates);
  1793.             $entityOption $entityManager->getRepository(EntityOption::class)->findOneBy([
  1794.                 "entityID" => $offerID,
  1795.                 "entityTypeID" => EntityOption::BOOKING_RESERVED_DATES,
  1796.                 "name" => EntityOption::OPTION_BOOKING_DATES
  1797.             ]);
  1798.             if (!$entityOption) {
  1799.                 $entityOption = new EntityOption();
  1800.                 $entityOption->setEntityID($offer->getID());
  1801.                 $entityOption->setCreatedOn(new \DateTime());
  1802.                 $entityManager->persist($entityOption);
  1803.             }
  1804.             $entityOption->setEntityTypeID(EntityOption::BOOKING_RESERVED_DATES);
  1805.             $entityOption->setLastModified(new \DateTime());
  1806.             $entityOption->setName(EntityOption::OPTION_BOOKING_DATES);
  1807.             $entityOption->setValue($bookedDates);
  1808.         }
  1809.         $entityManager->flush();
  1810.         $offerForSlivkiDelivery $request->request->getBoolean('offerForSlivkiDelivery');
  1811.         $slivkiDeliveryOption $entityManager->getRepository(EntityOption::class)->findBy([
  1812.             'entityID' => $offerID,
  1813.             'name' => EntityOption::OPTION_SLIVKI_DELIVERY
  1814.         ]);
  1815.         $slivkiDeliveryOptionCount count($slivkiDeliveryOption);
  1816.         if ($offerForSlivkiDelivery && $slivkiDeliveryOptionCount == 0) {
  1817.             $slivkiDeliveryOption = new EntityOption();
  1818.             $slivkiDeliveryOption->setName(EntityOption::OPTION_SLIVKI_DELIVERY);
  1819.             $slivkiDeliveryOption->setEntityID($offerID);
  1820.             $slivkiDeliveryOption->setEntityTypeID(EntityOption::OFFER_ENTITY_TYPE);
  1821.             $entityManager->persist($slivkiDeliveryOption);
  1822.         } elseif (!$offerForSlivkiDelivery and $slivkiDeliveryOptionCount 0) {
  1823.             foreach ($slivkiDeliveryOption as $option) {
  1824.                 $entityManager->remove($option);
  1825.             }
  1826.         }
  1827.         $this->videoPackageSaver->save(
  1828.             $offerID,
  1829.             $request->request->get('videoPackageTitle'),
  1830.             $request->request->get('videoPackagePicturePath')
  1831.         );
  1832.         $this->offerFoodDeliveryZoneSaver->save($offer$request->request->get('foodDeliveryZone', []));
  1833.         $entityManager->flush();
  1834.         $offerItems $entityManager->getRepository(ItemOfferExtension::class)->findBy(['offer' => $offerID]);
  1835.         if ($offerItems) {
  1836.             $result['items'] = $this->renderView('Slivki/admin/offers/offer_items_table.html.twig', ['items' => $offerItems]);
  1837.         }
  1838.         $result['lastModified'] = $offer->getLastModified()->format('Y-m-d H:i:s');
  1839.         $result['message'] = array(
  1840.             'title' => 'Успех!',
  1841.             'message' => 'Акция успешно сохранена!',
  1842.             'type' => 'modal-success'
  1843.         );
  1844.         $sql 'select id from offer_extension where offer_id = ' $offerID;
  1845.         $extensionIDList $entityManager->getConnection()->executeQuery($sql)->fetchAll(\PDO::FETCH_COLUMN);
  1846.         foreach ($offerCacheService->getExtensions($offerID) as $extensionCached) {
  1847.             if (!in_array($extensionCached->getID(), $extensionIDList)) {
  1848.                 $offerCacheService->deleteExtension($extensionCached->getID());
  1849.             }
  1850.         }
  1851.         $debugLogger->info('1000');
  1852.         $this->messageBus->dispatch(new CreateOfferStatusLogCommand($offerID$offer->getStatus()->getValue(), $this->getUser()->getID()));
  1853.         $this->logOperatorAction($request$offerID"save offer"OperatorActionLog::SAVE_SALE_OR_OFFER);
  1854.         $debugLogger->info('1500');
  1855.         $offerCacheService->reloadOfferCache($offerID);
  1856.         $debugLogger->info('2000');
  1857.         $categoryBoxCacheService->setTeaser($offer);
  1858.         $debugLogger->info('3000');
  1859.         $this->offerResponseCacheService->reloadByOfferId($offerID);
  1860.         return $result;
  1861.     }
  1862.     private function deleteExtraLines($description$needSpace false) {
  1863.         $newLine '<p>&nbsp;</p>';
  1864.         $countSymbols strlen($newLine);
  1865.         $completed false;
  1866.         $spaceDeleted false;
  1867.         while (!$completed) {
  1868.             $description trim($description);
  1869.             if (substr($description, -$countSymbols) == $newLine) {
  1870.                 $spaceDeleted true;
  1871.                 $description substr($description0, -$countSymbols);
  1872.             } else {
  1873.                 $completed true;
  1874.             }
  1875.         }
  1876.         if ($spaceDeleted and $needSpace) {
  1877.             $description .= $newLine;
  1878.         }
  1879.         return $description;
  1880.     }
  1881.     /**
  1882.      * @Route("/admin/offer/crop_teaser_image")
  1883.      */
  1884.     public function cropTeaserImage(Request $requestKernelInterface $kernel) {
  1885.         $imagePath $request->request->get('imagePath');
  1886.         $selection $request->request->get('selection');
  1887.         if (!$imagePath || !$selection) {
  1888.             return new Response();
  1889.         }
  1890.         $teaserMediaFileName basename($imagePath);
  1891.         $realPath $kernel->getProjectDir() . '/public';
  1892.         $selection json_decode($selection);
  1893.         $x $selection->$selection->0;
  1894.         $y $selection->$selection->0;
  1895.         $imagine = new Imagine();
  1896.         $image $imagine->open($realPath $imagePath);
  1897.         $image->crop(new Point($x$y), new Box($selection->width$selection->height));
  1898.         $fileName time() . "_" $teaserMediaFileName;
  1899.         $fileSystem = new Filesystem();
  1900.         while ($fileSystem->exists($realPath ImageService::MEDIA_ROOT ImageService::INITIAL_PATH MediaType::TYPE_OFFER_TEASER_PATH $fileName)) {
  1901.             $fileName time() . '_' $fileName;
  1902.         }
  1903.         $newFilePath ImageService::MEDIA_ROOT ImageService::INITIAL_PATH MediaType::TYPE_OFFER_TEASER_PATH $fileName;
  1904.         $image->save($realPath $newFilePath);
  1905.         return new Response($newFilePath);
  1906.     }
  1907.     private function setOfferTeaserMedia(
  1908.         CacheService $cacheService,
  1909.         ImageService $imageService,
  1910.         EntityManager $entityManager,
  1911.         $mediaTypeID,
  1912.         Offer $offer,
  1913.         $teaserMediaFileName
  1914.     ) {
  1915.         $fileName basename($teaserMediaFileName);
  1916.         switch ($mediaTypeID) {
  1917.             case Media\OfferAppTeaserMedia::TYPE:
  1918.                 $offerTeaserMedia = new Media\OfferAppTeaserMedia();
  1919.                 break;
  1920.             case Media\OfferMobileTeaserMedia::TYPE:
  1921.                 $offerTeaserMedia = new Media\OfferMobileTeaserMedia();
  1922.                 break;
  1923.             default:
  1924.                 $offerTeaserMedia = new Media\OfferTeaserMedia();
  1925.         }
  1926.         $offerTeaserMedia->setName($fileName);
  1927.         $offerTeaserMedia->setPath(MediaType::TYPE_OFFER_TEASER_PATH);
  1928.         switch ($mediaTypeID) {
  1929.             case Media\OfferAppTeaserMedia::TYPE:
  1930.                 foreach ($offer->getAppTeaserMedias() as $mediaToRemove) {
  1931.                     $offer->removeAppTeaserMedia($mediaToRemove);
  1932.                     $entityManager->remove($mediaToRemove);
  1933.                     $cacheService->deleteMedia($mediaToRemove->getID());
  1934.                 }
  1935.                 $offer->addAppTeaserMedia($offerTeaserMedia);
  1936.                 $imageService->getImageURLCached($offerTeaserMediaImageService::OFFER_APP_TEASER_WIDTHImageService::OFFER_APP_TEASER_HEIGHT);
  1937.                 break;
  1938.             case Media\OfferMobileTeaserMedia::TYPE:
  1939.                 foreach ($offer->getMobileTeaserMedias() as $mediaToRemove) {
  1940.                     $offer->removeMobileTeaserMedia($mediaToRemove);
  1941.                     $entityManager->remove($mediaToRemove);
  1942.                     $cacheService->deleteMedia($mediaToRemove->getID());
  1943.                 }
  1944.                 $offer->addMobileTeaserMedia($offerTeaserMedia);
  1945.                 $imageService->getImageURLCached($offerTeaserMediaImageService::OFFER_MOBILE_TEASER_WIDTHImageService::OFFER_MOBILE_TEASER_HEIGHT);
  1946.                 break;
  1947.             default:
  1948.                 foreach ($offer->getTeaserMedias() as $mediaToRemove) {
  1949.                     $offer->removeTeaserMedia($mediaToRemove);
  1950.                     $entityManager->remove($mediaToRemove);
  1951.                     $cacheService->deleteMedia($mediaToRemove->getID());
  1952.                 }
  1953.                 $offer->addTeaserMedia($offerTeaserMedia);
  1954.                 $imageService->getImageURLCached($offerTeaserMediaImageService::OFFER_TEASER_WIDTHImageService::OFFER_TEASER_HEIGHT);
  1955.         }
  1956.         return $offerTeaserMedia;
  1957.     }
  1958.     /**
  1959.      * @Route("/admin/offer/ajax_upload_description_images", name="/admin/offer/ajax_upload_description_images")
  1960.      */
  1961.     public function ajaxUploadDescriptionImages(Request $requestKernelInterface $kernel) {
  1962.         $imageFolder $kernel->getProjectDir() . Offer::DESCRIPTION_IMAGES_PATH;
  1963.         $uploadedFile $request->files->get('file');
  1964.         if ($uploadedFile) {
  1965.             $fs = new Filesystem();
  1966.             $newFileName time() . '_' $uploadedFile->getClientOriginalName();
  1967.             while ($fs->exists($imageFolder $newFileName)) {
  1968.                 $newFileName time() . '_' $newFileName;
  1969.             }
  1970.             $imagine = new Imagine();
  1971.             $image $imagine->open($uploadedFile->getRealPath());
  1972.             $imageSize $image->getSize();
  1973.             $returnFileName $newFileName;
  1974.             if ($imageSize->getWidth() > 1100) {
  1975.                 $returnFileName OfferRepository::RESIZED_IMAGE_PREFIX $newFileName;
  1976.                 $newImageSize $imageSize->widen(1100);
  1977.                 $image->resize($newImageSize);
  1978.                 $image->save($imageFolder $returnFileName);
  1979.             }
  1980.             $uploadedFile->move($imageFolder$newFileName);
  1981.             return new Response(json_encode(array('location' => $returnFileName)));
  1982.         } else {
  1983.             // Notify editor that the upload failed
  1984.             header("HTTP/1.0 500 Server Error");
  1985.         }
  1986.     }
  1987.     /**
  1988.      * @Route("/admin/ajax/get_order_by_code")
  1989.      */
  1990.     public function ajaxGetOrderByCode(Request $request) {
  1991.         if (!$request->isXmlHttpRequest()) {
  1992.             return $this->redirect("/admin");
  1993.         }
  1994.         $result = [];
  1995.         $code $request->request->get("orderCode");
  1996.         $offerID $request->request->get("offerID");
  1997.         $offer $this->getOfferRepository()->find($offerID);
  1998.         if ($offer) {
  1999.             if ($offerID != Offer::PETROL_OFFER_ID) {
  2000.                 $dql "select orderDetail from Slivki:OfferOrderDetails orderDetail join orderDetail.offerOrder offerOrder where offerOrder.offerID = :offerID and orderDetail.code = :code";
  2001.                 $orderDetail $this->getDoctrine()->getManager()->createQuery($dql)->setParameters(["offerID" => $offerID"code" => $code])->setMaxResults(1)->getResult();
  2002.             } else {
  2003.                 $dql "select orderDetail, codeOption from Slivki:OfferOrderDetails orderDetail 
  2004.                   join orderDetail.offerOrder offerOrder 
  2005.                   join Slivki:EntityOption codeOption with orderDetail.ID = codeOption.entityID
  2006.                   where offerOrder.offerID = :offerID and orderDetail.code = :code";
  2007.                 $orderDetailsWithOption $this->getDoctrine()->getManager()->createQuery($dql)
  2008.                     ->setParameters(["offerID" => $offerID"code" => $code])
  2009.                     ->getResult();
  2010.                 $orderDetail = [];
  2011.                 $orderDetailOption = [];
  2012.                 foreach ($orderDetailsWithOption as $item) {
  2013.                     if ($item instanceof OfferOrderDetails) {
  2014.                         $orderDetail[] = $item;
  2015.                     } else {
  2016.                         $orderDetailOption[count($orderDetail) - 1][$item->getName()] = $item->getValue();
  2017.                     }
  2018.                 }
  2019.             }
  2020.             if ($orderDetail) {
  2021.                 $offerOrder $orderDetail[0]->getOfferOrder();
  2022.             } else {
  2023.                 $result['result'] = "fail";
  2024.                 return new Response(json_encode($result));
  2025.             }
  2026.             if ($offerOrder) {
  2027.                 $date $offerOrder->getCreatedOn();
  2028.                 $result['date'] = $date->format('d.m.Y H:m');
  2029.                 $result['email'] = $offerOrder->getUser()->getEmail();
  2030.                 $result['result'] = "success";
  2031.                 if ($offerID == Offer::PETROL_OFFER_ID) {
  2032.                     $result['car_number'] = '';
  2033.                     $result['phone_number'] = '';
  2034.                     if (isset($orderDetailOption[0]['car_number'])) {
  2035.                         $result['car_number'] = $orderDetailOption[0]['car_number'];
  2036.                     }
  2037.                     if (isset($orderDetailOption[0]['phone_number'])) {
  2038.                         $result['phone_number'] = $orderDetailOption[0]['phone_number'];
  2039.                     }
  2040.                 }
  2041.                 $orderDetails $offerOrder->getOfferOrderDetails()->toArray();
  2042.                 $codes = [];
  2043.                 for ($j 0$j count($orderDetails); $j++) {
  2044.                     array_push($codes$orderDetails[$j]->getCode());
  2045.                 }
  2046.                 $currentPhone $offerOrder->getUser()->getCurrentPhone();
  2047.                 $result['currentPhone'] = $currentPhone $currentPhone->getPhoneNumber() . ' ' '';
  2048.                 $result['code'] = $codes;
  2049.                 return new Response(json_encode($result));
  2050.             } else {
  2051.                 $result['result'] = "fail";
  2052.                 return new Response(json_encode($result));
  2053.             }
  2054.         } else {
  2055.             $result['result'] = "fail";
  2056.             return new Response(json_encode($result));
  2057.         }
  2058.     }
  2059.     /**
  2060.      * @Route("/admin/ajax_get_codes")
  2061.      */
  2062.     public function ajaxGetCodes(Request $request) {
  2063.         if (!$request->isXmlHttpRequest()) {
  2064.             return $this->redirect("/admin");
  2065.         }
  2066.         $result = [];
  2067.         $offerID $request->request->get('offerID');
  2068.         $offer $this->getOfferRepository()->find($offerID);
  2069.         $user $this->getUser();
  2070.         $manager $offer->getManager();
  2071.         if ($offer) {
  2072.             if ($offer->getID() == Offer::BOOKING_OFFER_ID && (!$user->hasRole(UserGroup::ROLE_ADMIN_ID) && $manager->getID() != $user->getID() && $user->getEmail() != 'volga@slivki.by')) {
  2073.                 $result['data'] = array([=> 'недоступно'=> 'недоступно'=> 'недоступно']);
  2074.                 return new Response(json_encode($result));
  2075.             }
  2076.             $start $request->request->get('start');
  2077.             $length $request->request->get('length');
  2078.             $orders $request->request->get('order');
  2079.             foreach ($orders as $order) {
  2080.                 if ($order['column'] == 0) {
  2081.                     $dir $order['dir'];
  2082.                     if ($offerID != Offer::PETROL_OFFER_ID) {
  2083.                         $offerOrders $this->getOfferOrderRepository()->findBy(array('offerID' => $offerID'status' => [OfferOrder::STATUS_CONFIRMOfferOrder::STATUS_CONFIRM_FREE_IMPLICITLY]), ['createdOn' => $dir], $length$start);
  2084.                     } else {
  2085.                         $dql "select offerOrder, codeOption from Slivki:OfferOrder offerOrder
  2086.                           join offerOrder.offerOrderDetails offerOrderDetails
  2087.                           join offerOrder.offer offer
  2088.                           join Slivki:EntityOption codeOption with offerOrderDetails.ID = codeOption.entityID 
  2089.                           where offer.ID = :offerID
  2090.                           order by offerOrderDetails.createdOn $dir";
  2091.                         $offerOrdersWithOptions $this->getDoctrine()->getManager()->createQuery($dql)
  2092.                             ->setParameter('offerID'$offerID)
  2093.                             ->setFirstResult($start)
  2094.                             ->setMaxResults($length)
  2095.                             ->getResult();
  2096.                         $offerOrders = [];
  2097.                         $offerOrdersOptions = [];
  2098.                         foreach ($offerOrdersWithOptions as $item) {
  2099.                             if ($item instanceof OfferOrder) {
  2100.                                 $offerOrders[] = $item;
  2101.                             } else {
  2102.                                 $offerOrdersOptions[count($offerOrders) - 1][$item->getName()] = $item->getValue();
  2103.                             }
  2104.                         }
  2105.                     }
  2106.                 }
  2107.             }
  2108.             $orders = [];
  2109.             if (!$user->hasRole(UserGroup::ROLE_ADMIN_ID) && $offerID == 137760) {
  2110.                 $isHideCode true;
  2111.             } else {
  2112.                 $isHideCode false;
  2113.             }
  2114.             for ($i 0$i count($offerOrders); $i++) {
  2115.                 $order = [];
  2116.                 $codes = [];
  2117.                 $user $offerOrders[$i]->getUser();
  2118.                 $order[1] = $user->getCurrentPhone() ? $user->getCurrentPhone()->getPhoneNumber() . ' ' $user->getEmail() : $user->getEmail();
  2119.                 $date $offerOrders[$i]->getCreatedOn();
  2120.                 $order[0] = $date->format('d.m.Y H:i:s');
  2121.                 $orderDetails $offerOrders[$i]->getOfferOrderDetails()->toArray();
  2122.                 for ($j 0$j count($orderDetails); $j++) {
  2123.                     $offerExtension $orderDetails[0]->getOfferExtension();
  2124.                     if ($offerExtension instanceof ItemOfferExtension && !$user->hasRole(UserGroup::ROLE_ADMIN_ID)) {
  2125.                         array_push($codes"****-****");
  2126.                     } else {
  2127.                         if ($isHideCode) {
  2128.                             array_push($codes$orderDetails[$j]->getCode(true));
  2129.                         } else {
  2130.                             array_push($codes$orderDetails[$j]->getCode());
  2131.                         }
  2132.                     }
  2133.                 }
  2134.                 if (count($codes) == 0) {
  2135.                     $length++;
  2136.                     continue;
  2137.                 }
  2138.                 $order[2] = $codes;
  2139.                 if ($offerID == Offer::PETROL_OFFER_ID) {
  2140.                     $order[3] = '';
  2141.                     $order[4] = '';
  2142.                     if (isset($offerOrdersOptions[$i]['car_number'])) {
  2143.                         $order[3] = $offerOrdersOptions[$i]['car_number'];
  2144.                     }
  2145.                     if (isset($offerOrdersOptions[$i]['phone_number'])) {
  2146.                         $order[4] = $offerOrdersOptions[$i]['phone_number'];
  2147.                     }
  2148.                 }
  2149.                 array_push($orders$order);
  2150.             }
  2151.             $result['data'] = $orders;
  2152.             return new Response(json_encode($result));
  2153.         } else {
  2154.             return new Response("");
  2155.         }
  2156.     }
  2157.     /**
  2158.      * @Route("/admin/offer/ajax_generate_codes_pool")
  2159.      */
  2160.     public function ajaxGenerateCodesPool(Request $request) {
  2161.         if (!$request->isXmlHttpRequest()) {
  2162.             return $this->redirect("/admin");
  2163.         }
  2164.         $result = array();
  2165.         $generatedCoupons = array();
  2166.         $offerID $request->request->get('offerID');
  2167.         $codePoolGeneratorAmount $request->request->get('codePoolGeneratorAmount');
  2168.         $offerCodePool null;
  2169.         if ($offerID && $request->request->get('newPool') != '1') {
  2170.             $entityManager $this->getDoctrine()->getManager("admin");
  2171.             $offerRepository $entityManager->getRepository(Offer::class);
  2172.             $offer $offerRepository->find($offerID);
  2173.             $offerCodePool $offer->getLastActiveCodePool();
  2174.         }
  2175.         if ($request->request->get('isRandomCodes') == 'true') {
  2176.             $codeNumberList '';
  2177.             if ($offerCodePool) {
  2178.                 $codeNumberList $offerCodePool->getCodesUsed() . $offerCodePool->getCodesFree() . $offerCodePool->getCodesReserved();
  2179.             }
  2180.             do {
  2181.                 $codeNumber mt_rand(0009999) . '-' mt_rand(100999);
  2182.                 if ($offerID == Offer::BOOKING_OFFER_ID) {
  2183.                     $codeNumber 'BOOK-' $codeNumber;
  2184.                 }
  2185.                 if (strpos($codeNumberList$codeNumber) !== false) {
  2186.                     continue;
  2187.                 }
  2188.                 $codeNumberList .= $codeNumber;
  2189.                 $generatedCoupons[] = $codeNumber;
  2190.             } while (count($generatedCoupons) < $codePoolGeneratorAmount);
  2191.         } else {
  2192.             if ($offerCodePool != null) {
  2193.                 $generatedCoupons $offerCodePool->getNewFreeCodes($codePoolGeneratorAmount9999$offerID == Offer::BOOKING_OFFER_ID 'BOOK-' '');
  2194.             } else {
  2195.                 $tempOfferCodePool = new OfferCodePool;
  2196.                 $generatedCoupons $tempOfferCodePool->getNewFreeCodes($codePoolGeneratorAmount9999$offerID == Offer::BOOKING_OFFER_ID 'BOOK-' '');
  2197.             }
  2198.         }
  2199.         $result['generatedCoupons'] = $generatedCoupons;
  2200.         return new Response(json_encode($result));
  2201.     }
  2202.     private function getRandomCode($exception) {
  2203.     }
  2204.     /**
  2205.      * @Route("/admin/offer/ajax_get_geo_location")
  2206.      */
  2207.     public function ajaxGetGeoLocation(Request $request) {
  2208.         if (!$request->isXmlHttpRequest()) {
  2209.             return $this->redirect("/admin");
  2210.         }
  2211.         $result = array();
  2212.         $geoLocationID $request->request->get('geoLocationID');
  2213.         $geoLocation $request->getSession()->get('geoLocationList', array());
  2214.         if (isset($geoLocation[$geoLocationID])) {
  2215.             $geoLocation $geoLocation[$geoLocationID];
  2216.         } else {
  2217.             $entityManager $this->getDoctrine()->getManager("admin");
  2218.             $entityName $request->request->get('entity''GeoLocation');
  2219.             $entityClassName GeoLocation::class;
  2220.             if ($entityName === 'MallGeoLocation') {
  2221.                 $entityClassName MallGeoLocation::class;
  2222.             }
  2223.             $geoLocationRepository $entityManager->getRepository($entityClassName);
  2224.             $geoLocation $geoLocationRepository->find($geoLocationID);
  2225.         }
  2226.         $result['geoLocation'] = $geoLocation;
  2227.         return new Response(json_encode($result));
  2228.     }
  2229.     /**
  2230.      * @Route("/admin/offer/ajax_edit_geo_location")
  2231.      */
  2232.     public function ajaxEditGeoLocation(Request $request) {
  2233.         if (!$request->isXmlHttpRequest()) {
  2234.             return $this->redirect("/admin");
  2235.         }
  2236.         $result['message'] = $this->validateGeoLocationForm($request);
  2237.         if ($result['message'] !== true) {
  2238.             return new Response(json_encode($result));
  2239.         }
  2240.         $result $this->saveSessionGeoLocation($request);
  2241.         return new Response(json_encode($result));
  2242.     }
  2243.     /**
  2244.      * @Route("/admin/offer/ajax_add_geo_location")
  2245.      */
  2246.     public function ajaxAddGeoLocation(Request $request) {
  2247.         if (!$request->isXmlHttpRequest()) {
  2248.             return $this->redirect("/admin");
  2249.         }
  2250.         $result['message'] = $this->validateGeoLocationForm($request);
  2251.         if ($result['message'] !== true) {
  2252.             return new Response(json_encode($result));
  2253.         }
  2254.         $result $this->saveSessionGeoLocation($request);
  2255.         return new Response(json_encode($result));
  2256.     }
  2257.     /**
  2258.      * @Route("/admin/offer/ajax_remove_geo_location")
  2259.      */
  2260.     public function ajaxRemoveGeoLocation(Request $requestCacheService $cacheService) {
  2261.         if (!$request->isXmlHttpRequest()) {
  2262.             return $this->redirect("/admin");
  2263.         }
  2264.         $result = [];
  2265.         $entityManager $this->getEntityManager();
  2266.         $geoLocationID $request->request->get('geoLocationID');
  2267.         $entityName $request->request->get('entityName''GeoLocation');
  2268.         if (strpos($geoLocationID'new') === false) {
  2269.             $entityClassName GeoLocation::class;
  2270.             if ($entityName === 'MallGeoLocation') {
  2271.                 $entityClassName MallGeoLocation::class;
  2272.             }
  2273.             $geoLocation $entityManager->getRepository($entityClassName)->find($geoLocationID);
  2274.             if ($geoLocation) {
  2275.                 $entityManager->remove($geoLocation);
  2276.                 $entityManager->flush();
  2277.             }
  2278.         }
  2279.         $cacheService->deleteGeoLocation($geoLocationID);
  2280.         $session $request->getSession();
  2281.         $geoLocationList $session->get('geoLocationList', []);
  2282.         if (isset($geoLocationList[$geoLocationID])) {
  2283.             unset($geoLocationList[$geoLocationID]);
  2284.             $session->set('geoLocationList'$geoLocationList);
  2285.         }
  2286.         return new Response(json_encode($result));
  2287.     }
  2288.     /**
  2289.      * @Route("/admin/offer/ajax_get_geo_location_list")
  2290.      */
  2291.     public function ajaxGetGeoLocationList(Request $request) {
  2292.         if (!$request->isXmlHttpRequest()) {
  2293.             return $this->redirect("/admin");
  2294.         }
  2295.         $result = array();
  2296.         $result['geoLocations'] = '';
  2297.         $offerID $request->request->getInt('offerID');
  2298.         if ($offerID 0) {
  2299.             $offer $this->getOfferRepository()->find($offerID);
  2300.             if ($offer) {
  2301.                 $result['geoLocations'] = $this->getGeoLocationList($offer);
  2302.             }
  2303.         }
  2304.         return new Response(json_encode($result));
  2305.     }
  2306.     /**
  2307.      * @Route("/admin/offer/ajax_refresh_geo_location_list")
  2308.      */
  2309.     public function ajaxRefreshGeoLocationList(Request $request) {
  2310.         if (!$request->isXmlHttpRequest()) {
  2311.             return $this->redirect("/admin");
  2312.         }
  2313.         $result = array();
  2314.         $geoLocationID $request->request->get('geoLocationID');
  2315.         if ($request->request->get('entityType') == 'mall') {
  2316.             $result $this->getDoctrine()->getManager('admin')->find(MallGeoLocation::class, $geoLocationID);
  2317.         } else {
  2318.             $sessionGeoLocationList $request->getSession()->get('geoLocationList');
  2319.             if (isset($sessionGeoLocationList[$geoLocationID])) {
  2320.                 $result $sessionGeoLocationList[$geoLocationID];
  2321.             }
  2322.         }
  2323.         return new Response(json_encode($result));
  2324.     }
  2325.     /**
  2326.      * @Route("/admin/directors/list")
  2327.      */
  2328.     public function directorsListAction(Request $request) {
  2329.         ini_set('memory_limit''256m');
  2330.         if (!$request->isXmlHttpRequest()) {
  2331.             return $this->redirect("/admin");
  2332.         }
  2333.         $directors $this->getDoctrine()->getRepository(Director::class)->findAll();
  2334.         return $this->render('Slivki/admin/directors/list.html.twig', ['directors' => $directors]);
  2335.     }
  2336.     /**
  2337.      * @Route("/admin/directors/add")
  2338.      */
  2339.     public function addDirectorAction(Request $requestMailer $mailer) {
  2340.         if (!$request->isXmlHttpRequest()) {
  2341.             return $this->redirect("/admin");
  2342.         }
  2343.         $entityManager $this->getDoctrine()->getManager('admin');
  2344.         $directorEmail mb_strtolower(trim($request->request->get('edit-director-email')));
  2345.         $dql 'select director from Slivki:Director director where LOWER(director.email) = :email';
  2346.         $director $entityManager->createQuery($dql)->setParameter('email'$directorEmail)->getResult();
  2347.         if (!$director) {
  2348.             $director = new Director();
  2349.             $director->setName($request->request->get('editDirectorName'));
  2350.             $director->setReceiveLetters($request->request->getBoolean('edit-director-letters'));
  2351.             $director->setLegalEntity($request->request->get('edit-director-legal'));
  2352.             $director->setEmail($directorEmail);
  2353.             $director->setStatus(Director::STATUS_ACTIVE);
  2354.             $director->setTaxID($request->request->get('edit-director-taxID'));
  2355.             $entityManager->persist($director);
  2356.             $this->getUserRepository()->addDirectorGroupToUserByDirectorEmail($directorEmail);
  2357.             $entityManager->flush();
  2358.             $directorID $director->getID();
  2359.             $seoRepository $entityManager->getRepository(Seo::class);
  2360.             $seo $seoRepository->findBy(['entityID' => $directorID'resourceURL' => SeoRepository::RESOURCE_URL_DIRECTOR_DETAILS], ['ID' => 'DESC'], 1);
  2361.             $requestMainAlias $request->request->get('editDirectorAlias''');
  2362.             $user $this->getUserRepository()->findBy(['email' => $directorEmail]);
  2363.             if (!$user) {
  2364.                 $password random_int(111111999999);
  2365.                 $user = new User();
  2366.                 $user->setEmail($directorEmail);
  2367.                 $user->encryptPassword($password);
  2368.                 $directorUserGroup $entityManager->getRepository(UserGroup::class)->find(UserGroup::ROLE_SUPPLIER_ID);
  2369.                 $user->addUserGroup($directorUserGroup);
  2370.                 $user->setStatus(User::STATUS_CONFIRMED);
  2371.                 $entityManager->persist($user);
  2372.                 $entityManager->flush();
  2373.                 $user->setToken(\uniqid($user->getID(), true));
  2374.                 $entityManager->persist($user);
  2375.                 $entityManager->flush($user);
  2376.                 $message $mailer->createMessage();
  2377.                 $message->setSubject("Регистрация на Slivki.by")
  2378.                     ->setFrom("info@slivki.by"'Slivki.by')
  2379.                     ->setTo($directorEmail)
  2380.                     ->setBody(
  2381.                         $this->renderView('Slivki/emails/lost_password.html.twig', [
  2382.                             'password' => $password
  2383.                         ]),
  2384.                         'text/html'
  2385.                     );
  2386.                 $mailer->send($message);
  2387.             }
  2388.             if ($requestMainAlias == '' and $seo) {
  2389.                 $entityManager->remove($seo);
  2390.                 $entityManager->flush();
  2391.             } elseif ($requestMainAlias != '') {
  2392.                 $seo = new Seo();
  2393.                 $seo->setResourceURL(SeoRepository::RESOURCE_URL_DIRECTOR_DETAILS);
  2394.                 $seo->setEntityID($directorID);
  2395.                 $seo->setMainAlias($requestMainAlias);
  2396.                 $seo->setActive(true);
  2397.                 $seo->setMetaTitle($request->request->get('editDirectorMetaTitle'''));
  2398.                 $seo->setMetaDescription($request->request->get('editDirectorMetaDescription'''));
  2399.                 $seo->setMetaKeywords($request->request->get('editDirectorMetaKeywords'), '');
  2400.                 if (!$seoRepository->setAlias($seo)) {
  2401.                     $result['message'] = [
  2402.                         'title' => 'Ошибка!',
  2403.                         'message' => 'Алиас ' $requestMainAlias ' уже существует!',
  2404.                         'type' => 'modal-danger'
  2405.                     ];
  2406.                     return new JsonResponse($result);
  2407.                 }
  2408.             }
  2409.         } else {
  2410.             $director $director[0];
  2411.         }
  2412.         return $this->render('Slivki/admin/directors/list.html.twig', ['directors' => [$director]]);
  2413.     }
  2414.     /**
  2415.      * @Route("/admin/director/offers/list/{directorID}")
  2416.      */
  2417.     public function directorOfferListAction($directorID) {
  2418.         $director $this->getDoctrine()->getRepository(Director::class)->find($directorID);
  2419.         if (!$director) {
  2420.             return new Response("");
  2421.         }
  2422.         $pageOffer $director->getPageOffer();
  2423.         return $this->render('Slivki/admin/directors/offers_list.html.twig', [
  2424.             'offers' => $director->getOffers(),
  2425.             'pageOfferID' => $pageOffer $pageOffer->getID() : -1
  2426.         ]);
  2427.     }
  2428.     /**
  2429.      * @Route("/admin/offer/comment/edit")
  2430.      */
  2431.     public function editCommentAction(Request $request) {
  2432.         if (!$request->isXmlHttpRequest()) {
  2433.             return $this->redirect("/admin");
  2434.         }
  2435.         if (!$this->isGranted('ROLE_ADMIN') && !$this->isGranted('ROLE_MANAGER_COMMENT')) {
  2436.             return new Response();
  2437.         }
  2438.         $entityManager $this->getDoctrine()->getManager("admin");
  2439.         $commentRepository $entityManager->getRepository(Comment::class);
  2440.         $comment $commentRepository->find($request->request->get('edit-offer-comment-id'));
  2441.         if (!$comment) {
  2442.             return new Response();
  2443.         }
  2444.         $comment->setComment($request->request->get('edit-offer-comment-comment'));
  2445.         $comment->setAdminComment($request->request->get('edit-offer-comment-answer'));
  2446.         $comment->setChecked((bool)$request->request->get('edit-offer-comment-checked'));
  2447.         $comment->setHidden(!(bool)$request->request->get('edit-offer-comment-hidden'));
  2448.         $comment->setRating($request->request->get('edit-offer-comment-rating'));
  2449.         $entityManager->flush();
  2450.         $this->resetCommentsCache($comment->getEntityID(), $comment->getTypeID());
  2451.         return new Response(json_encode($comment));
  2452.     }
  2453.     /**
  2454.      * @Route("/admin/offer/comment/check")
  2455.      */
  2456.     public function checkCommentAction(Request $requestMailer $mailerValidatorInterface $validator) {
  2457.         if (!$request->isXmlHttpRequest()) {
  2458.             return $this->redirect("/admin");
  2459.         }
  2460.         if (!$this->isGranted('ROLE_ADMIN') && !$this->isGranted('ROLE_MANAGER_COMMENT')) {
  2461.             return new Response();
  2462.         }
  2463.         $entityManager $this->getDoctrine()->getManager("admin");
  2464.         $commentRepository $entityManager->getRepository(Comment::class);
  2465.         $comment $commentRepository->find($request->request->get('commentID'));
  2466.         if (!$comment) {
  2467.             return new Response();
  2468.         }
  2469.         $isChecked = (bool)$request->request->get('value');
  2470.         $comment->setChecked($isChecked);
  2471.         $entityManager->flush();
  2472.         $offerRepository $this->getOfferRepository();
  2473.         if ($isChecked) {
  2474.             $offer $offerRepository->find($comment->getEntityID());
  2475.             $userRepository $this->getUserRepository();
  2476.             if ($userRepository->addCommentBonus($comment$offer)) {
  2477.                 $this->sendCommentBonusMessage($mailer$validator$comment);
  2478.             }
  2479.         }
  2480.         return new Response();
  2481.     }
  2482.     /**
  2483.      * @Route("/admin/offer/comment/hide")
  2484.      */
  2485.     public function hideCommentAction(Request $request) {
  2486.         if (!$request->isXmlHttpRequest()) {
  2487.             return $this->redirect("/admin");
  2488.         }
  2489.         if (!$this->isGranted('ROLE_ADMIN') && !$this->isGranted('ROLE_MANAGER_COMMENT')) {
  2490.             return new Response();
  2491.         }
  2492.         $entityManager $this->getDoctrine()->getManager("admin");
  2493.         $commentRepository $entityManager->getRepository(Comment::class);
  2494.         $comment $commentRepository->find($request->request->get('commentID'));
  2495.         if (!$comment) {
  2496.             return new Response();
  2497.         }
  2498.         $isHidden = !(bool)$request->request->get('value');
  2499.         $comment->setHidden($isHidden);
  2500.         $entityManager->flush();
  2501.         $this->resetCommentsCache($comment->getEntityID(), $comment->getTypeID());
  2502.         $userRepository $this->getUserRepository();
  2503.         $offer $this->getOfferRepository()->find($comment->getEntityID());
  2504.         if ($isHidden) {
  2505.             $userRepository->removeCommentBonus($comment$offer);
  2506.         } else {
  2507.             $userRepository->addCommentBonus($comment$offer);
  2508.         }
  2509.         return new Response();
  2510.     }
  2511.     private function validateGeoLocationForm(Request $request) {
  2512.         $errorMessage '';
  2513.         if ($request->request->get('edit-offer-address-street') == '') {
  2514.             $errorMessage .= 'Введите улицу!<br>';
  2515.         }
  2516.         if ($request->request->get('edit-offer-address-building') == '') {
  2517.             $errorMessage .= 'Введите дом!<br>';
  2518.         }
  2519.         if ($request->request->get('edit-offer-latitude') == '' || $request->request->get('edit-offer-longitude') == '') {
  2520.             $errorMessage .= 'Введите координаты!<br>';
  2521.         }
  2522.         if ($errorMessage != '') {
  2523.             $result = array(
  2524.                 'title' => 'Ошибка!',
  2525.                 'message' => $errorMessage,
  2526.                 'type' => 'modal-danger'
  2527.             );
  2528.             return $result;
  2529.         }
  2530.         return true;
  2531.     }
  2532.     private function saveSessionGeoLocation(Request $request) {
  2533.         $session $request->getSession();
  2534.         $geoLocationList $session->get('geoLocationList', array());
  2535.         $requestGeoLocationID $request->request->get('geo-location-id');
  2536.         $geoLocation['ID'] = $requestGeoLocationID;
  2537.         $geoLocation['city'] = $request->request->get('edit-offer-address-city');
  2538.         $geoLocation['cityArea'] = $request->request->get('edit-offer-address-area'0);
  2539.         $geoLocation['street'] = $request->request->get('edit-offer-address-street');
  2540.         $geoLocation['house'] = $request->request->get('edit-offer-address-building');
  2541.         $geoLocation['latitude'] = $request->request->get('edit-offer-latitude');
  2542.         $geoLocation['longitude'] = $request->request->get('edit-offer-longitude');
  2543.         $geoLocation['description'] = $request->request->get('edit-offer-address-description');
  2544.         $geoLocation['label'] = $request->request->get('edit-offer-address-label');
  2545.         $geoLocation['workingHours'] = $request->request->get('edit-offer-address-working-hours');
  2546.         $geoLocation['bigMapMarker'] = $request->request->has('bigMapMarker');
  2547.         $geoLocation['pickupPointPartnerID'] = $request->request->get('editOfferAddressPickupPointPartnerID');
  2548.         $geoLocation['pickupPointSchedule'] = $request->request->get('editOfferAddressPickupPointSchedule');
  2549.         $geoLocation['pickupPointBelTransSatDepotID'] = $request->request->get('editOfferAddressPickupPointBelTransSatDepotID');
  2550.         $geoLocation['bepaidCredentials'] = $request->request->get('locationBePaidCredentials');
  2551.         $geoLocation['callbackChatId'] = $request->request->get('callbackChatId');
  2552.         $geoLocationList[$requestGeoLocationID] = $geoLocation;
  2553.         $session->set('geoLocationList'$geoLocationList);
  2554.         $result['message'] = array(
  2555.             'title' => 'Успех!',
  2556.             'message' => 'Адрес успешно сохранен!',
  2557.             'type' => 'modal-success'
  2558.         );
  2559.         return $result;
  2560.     }
  2561.     /**
  2562.      * @Route("/admin/offer/set_paid_offer_position")
  2563.      */
  2564.     public function setPaidOfferPosition(Request $requestKernelInterface $kernel) {
  2565.         if (!$request->isXmlHttpRequest()) {
  2566.             return $this->redirect("/admin");
  2567.         }
  2568.         $categoryID $request->request->getInt('categoryID');
  2569.         if ($categoryID == Category::NEW_OFFER_CATEGORY_ID && !$this->getUser()->hasRole(UserGroup::ROLE_NEW_CATEGORY_MANAGER)) {
  2570.             return $this->redirect("/admin");
  2571.         }
  2572.         $offerPositionList $request->request->get('offerPositionList');
  2573.         $previousPaidOffersPosition $request->request->get('previousPaidOffersPosition');
  2574.         $draggedOfferID $request->request->get('draggedOfferID');
  2575.         $result = [];
  2576.         $entityManager $this->getDoctrine()->getManager("admin");
  2577.         $categoryRepository $entityManager->getRepository(Category::class);
  2578.         $currentPaidOffersPosition json_encode($categoryRepository->getPayedOffersByCategoryID($categoryID));
  2579.         if ($previousPaidOffersPosition != $currentPaidOffersPosition) {
  2580.             $result = array(
  2581.                 'title' => 'Внимание!',
  2582.                 'message' => 'Позиции редактировались другим оператором, список обновлен!',
  2583.                 'type' => 'modal-warning'
  2584.             );
  2585.             return new Response(json_encode($result));
  2586.         }
  2587.         $currentPaidOffersPosition json_decode($currentPaidOffersPositiontrue);
  2588.         $oldPosition null;
  2589.         if (isset($currentPaidOffersPosition[$draggedOfferID])) {
  2590.             $oldPosition $currentPaidOffersPosition[$draggedOfferID]['position'];
  2591.         }
  2592.         $offerPositionList json_decode($offerPositionListtrue);
  2593.         $newPosition $offerPositionList[$draggedOfferID];
  2594.         $offerPayedCategoryRepository $entityManager->getRepository(OfferPayedCategory::class);
  2595.         foreach ($offerPositionList as $offerID => $position) {
  2596.             $offerPayedCategory $offerPayedCategoryRepository->findOneBy(['entityID' => $offerID'categoryID' => $categoryID]);
  2597.             if (!$offerPayedCategory) {
  2598.                 if ($offerID == $draggedOfferID) {
  2599.                     $offerPayedCategory = new OfferPayedCategory();
  2600.                     $offerPayedCategory->setCategoryID($categoryID);
  2601.                     $offerPayedCategory->setEntityID($offerID);
  2602.                     $offerPayedCategory->setPosition($position);
  2603.                     $entityManager->persist($offerPayedCategory);
  2604.                 }
  2605.                 continue;
  2606.             }
  2607.             $offerPayedCategory->setPosition($position);
  2608.         }
  2609.         $entityManager->flush();
  2610.         $this->saveOfferCategoryPositionsSQL($categoryID);
  2611.         $this->logOperatorAction($request$draggedOfferID"$oldPosition -> $newPosition"OperatorActionLog::CHANGE_PAID_OFFER_POSITION);
  2612.         $result['paidOfferPosition'] = json_encode($categoryRepository->getPayedOffersByCategoryID($categoryID));
  2613.         return new Response(json_encode($result));
  2614.     }
  2615.     /**
  2616.      * @Route("/admin/offer/paid_position/remove")
  2617.      */
  2618.     public function removePaidOfferPosition(Request $requestKernelInterface $kernel) {
  2619.         $categoryID $request->request->getInt('categoryID');
  2620.         $offerID $request->request->getInt('offerID');
  2621.         $entityManager $this->getDoctrine()->getManager("admin");
  2622.         $offerPayedCategoryRepository $entityManager->getRepository(OfferPayedCategory::class);
  2623.         $offerPayedCategory $offerPayedCategoryRepository->findOneBy(['entityID' => $offerID'categoryID' => $categoryID]);
  2624.         if ($offerPayedCategory) {
  2625.             $entityManager->remove($offerPayedCategory);
  2626.             $entityManager->flush();
  2627.         }
  2628.         $categoryRepository $entityManager->getRepository(Category::class);
  2629.         $result['paidOfferPosition'] = json_encode($categoryRepository->getPayedOffersByCategoryID($categoryID));
  2630.         $this->refreshOfferCategoriesPosition($kernel$categoryID);
  2631.         return new Response(json_encode($result));
  2632.     }
  2633.     private function saveOfferCategoryPositionsSQL($categoryID) {
  2634.         $entityManager $this->getEntityManager();
  2635.         $categoryRepository $entityManager->getRepository(Category::class);
  2636.         $offerRepository $entityManager->getRepository(Offer::class);
  2637.         $activeCategoryList = [];
  2638.         if ($categoryID) {
  2639.             $activeCategoryList[] = $categoryRepository->find($categoryID);
  2640.         } else {
  2641.             $activeCategoryList $categoryRepository->getActiveCategoriesNotCached(Category::OFFER_CATEGORY_ID);
  2642.         }
  2643.         foreach ($activeCategoryList as $category) {
  2644.             $categoryID $category->getID();
  2645.             if ($categoryID == SavePurchaseCountCommand::POPULAR_CATEGORY_ID) {
  2646.                 continue;
  2647.             }
  2648.             $offerListSortedByPopularity $offerRepository->getOffersByCategorySortedByPopularity($category);
  2649.             if (!$offerListSortedByPopularity) {
  2650.                 continue;
  2651.             }
  2652.             $dql "select offerCategoryPosition
  2653.                 from Slivki:OfferCategoryPosition offerCategoryPosition index by offerCategoryPosition.entityID
  2654.                 where offerCategoryPosition.categoryID = :categoryID";
  2655.             $query $entityManager->createQuery($dql);
  2656.             $query->setParameter('categoryID'$categoryID);
  2657.             $offerCategoryPositionList $query->getResult();
  2658.             $position 1;
  2659.             $dbConnection $entityManager->getConnection();
  2660.             foreach ($offerListSortedByPopularity as $item) {
  2661.                 $offerID $item->getID();
  2662.                 if (isset($offerCategoryPositionList[$offerID])) {
  2663.                     $offerCategoryPosition $offerCategoryPositionList[$offerID];
  2664.                     if ($position != $offerCategoryPosition->getPosition()) {
  2665.                         $sql "update offer_category_position set position=$position where id=" $offerCategoryPosition->getID();
  2666.                         $dbConnection->executeQuery($sql);
  2667.                     }
  2668.                     unset($offerCategoryPositionList[$offerID]);
  2669.                 } else {
  2670.                     $sql "insert into offer_category_position (entity_id, category_id, position)values($offerID$categoryID$position)";
  2671.                     $dbConnection->executeQuery($sql);
  2672.                 }
  2673.                 $position++;
  2674.             }
  2675.             $removeIDList = [];
  2676.             foreach ($offerCategoryPositionList as $item) {
  2677.                 $removeIDList[] = $item->getID();
  2678.             }
  2679.             if (count($removeIDList) > 0) {
  2680.                 $sql "delete from offer_category_position where id in (" implode(', '$removeIDList) . ")";
  2681.                 $dbConnection->executeQuery($sql);
  2682.             }
  2683.         }
  2684.     }
  2685.     private function refreshOfferCategoriesPosition(KernelInterface $kernel$categoryID$background true) {
  2686.         $category $this->getCategoryRepository()->find($categoryID);
  2687.         if (!$category) {
  2688.             return;
  2689.         }
  2690.         $command 'php ' $kernel->getProjectDir() . '/bin/console purchase-count:save onlyPositions ' $categoryID;
  2691.         if ($category->getCode() == 'top') {
  2692.             $command 'php ' $kernel->getProjectDir() . '/bin/console purchase-count:save onlyPositions --buildPopularOffersCategory=yes';
  2693.         }
  2694.         if ($background) {
  2695.             $command .= ' > /dev/null &';
  2696.         }
  2697.         exec("$command");
  2698.     }
  2699.     /**
  2700.      * @Route("/admin/ajax_get_offer_proposals")
  2701.      */
  2702.     public function ajaxGetOfferProposals(Request $request) {
  2703.         if (!$request->isXmlHttpRequest()) {
  2704.             return $this->redirect("/admin");
  2705.         }
  2706.         $entityManager $this->getDoctrine()->getManager('admin');
  2707.         $offerProposals $entityManager->getRepository(OfferProposal::class)->findBy(['type' => (int)$request->request->get('type')], ['ID' => 'DESC']);
  2708.         return $this->render('Slivki/admin/offer_proposal/index.html.twig', ['proposals' => $offerProposals]);
  2709.     }
  2710.     /**
  2711.      * @Route("/admin/get_offer_proposal")
  2712.      */
  2713.     public function ajaxGetOfferProposal(Request $request) {
  2714.         if (!$request->isXmlHttpRequest()) {
  2715.             return $this->redirect("/admin");
  2716.         }
  2717.         $entityManager $this->getDoctrine()->getManager('admin');
  2718.         $id $request->request->get('id');
  2719.         $offerProposal $entityManager->getRepository(OfferProposal::class)->find($id);
  2720.         if (!$offerProposal) {
  2721.             $message['success'] = "false";
  2722.             $message['message'] = "Не удалось получить заявку";
  2723.             $message['modal'] = "modal-danger";
  2724.             return new Response(json_encode($message));
  2725.         }
  2726.         $isJustCheck $request->request->get('justCheck');
  2727.         $message['success'] = "true";
  2728.         if ($isJustCheck == "true") {
  2729.             $checked $offerProposal->isProcessed() ? false true;
  2730.             $offerProposal->setProcessed($checked);
  2731.             if ($checked) {
  2732.                 $user $this->getUserRepository()->find($this->getUser()->getID());
  2733.                 $offerProposal->setOperator($user);
  2734.                 $message['email'] = $this->getUser()->getEmail();
  2735.                 $message['status'] = "true";
  2736.             } else {
  2737.                 $message['email'] = "<i class=\"fa fa-eye-slash\">";
  2738.             }
  2739.             $entityManager->flush($offerProposal);
  2740.             $status $checked "\"обработана\"" "\"ожидает обработки\"";
  2741.             $message['message'] = "Статус заявки [ID = " $id "] " "изменен на " $status;
  2742.             $message['modal'] = "modal-success";
  2743.             return new Response(json_encode($message));
  2744.         }
  2745.         return $this->render('Slivki/admin/offer_proposal/offer_proposal_popup.html.twig', ['offerProposal' => $offerProposal]);
  2746.     }
  2747.     /**
  2748.      * @Route("/admin/edit_offer_proposal")
  2749.      */
  2750.     public function ajaxEditOfferProposal(Request $request) {
  2751.         if (!$request->isXmlHttpRequest()) {
  2752.             return $this->redirect("/admin");
  2753.         }
  2754.         $message = [];
  2755.         $entityManager $this->getDoctrine()->getManager('admin');
  2756.         $offerProposal $entityManager->getRepository(OfferProposal::class)->find($request->request->get('offer-proposal-id'));
  2757.         $contactPerson $request->request->get('contact-person');
  2758.         if ($offerProposal->getContactPerson() != $contactPerson) {
  2759.             $message['name'] = $contactPerson;
  2760.         }
  2761.         $offerProposal->setOrganizationName($request->request->get('organization'));
  2762.         $offerProposal->setLegalAddress($request->request->get('legal-address'));
  2763.         $offerProposal->setRequisites($request->request->get('requisites'));
  2764.         $offerProposal->setContactPerson($contactPerson);
  2765.         $offerProposal->setEmail($request->request->get('email'));
  2766.         $offerProposal->setOfferName($request->request->get('offer-name'));
  2767.         $offerProposal->setOfferPrice($request->request->get('offer-price'));
  2768.         $offerProposal->setDiscount($request->request->get('discount'));
  2769.         $offerProposal->setPriceWithDiscount($request->request->get('price-with-discount'));
  2770.         $offerProposal->setOfferConditions($request->request->get('conditions'));
  2771.         $offerProposal->setAdditionalInformation($request->request->get('additional-information'));
  2772.         $offerProposal->setPhone($request->request->get('phone'));
  2773.         $offerProposal->setAddress($request->request->get('address'));
  2774.         $offerProposal->setWebsite($request->request->get('website'));
  2775.         $checkStatus '';
  2776.         if ($request->request->get('is-processed') == "on") {
  2777.             $operator $this->getUserRepository()->find($this->getUser()->getID());
  2778.             $offerProposal->setOperator($operator);
  2779.             $checkStatus "true";
  2780.             $offerProposal->setProcessed(true);
  2781.         } else {
  2782.             $offerProposal->setProcessed(false);
  2783.         }
  2784.         $entityManager->flush($offerProposal);
  2785.         $message['success'] = "true";
  2786.         $message['message'] = "Заявка успешно обработана!";
  2787.         $message['modal'] = "modal-success";
  2788.         $message['status'] = $checkStatus;
  2789.         return new Response(json_encode($message));
  2790.     }
  2791.     /**
  2792.      * @Route("/admin/get_sale_proposals")
  2793.      */
  2794.     public function ajaxGetSaleProposals(Request $request) {
  2795.         if (!$request->isXmlHttpRequest()) {
  2796.             return $this->redirect("/admin");
  2797.         }
  2798.     }
  2799.     /** @Route("/admin/offer/certificate/save") */
  2800.     public function saveGiftCertificateAction(Request $requestImageService $imageService) {
  2801.         $entityManager $this->getEntityManager();
  2802.         $certificateteID $request->request->get('certificateID');
  2803.         $geoLocationListIDs $request->request->get('giftCertificateLocation');
  2804.         $certificate null;
  2805.         if ($certificateteID) {
  2806.             $certificate $entityManager->getRepository(GiftCertificate::class)->find($certificateteID);
  2807.         }
  2808.         if (!$certificate) {
  2809.             $certificate = new GiftCertificate();
  2810.             $offer $entityManager->getRepository(Offer::class)->find($request->request->get('offerID'));
  2811.             $offer->addGiftCertificate($certificate);
  2812.         }
  2813.         $certificate->setName($request->request->get('name'));
  2814.         $certificate->setPriceRegular(str_replace(',''.'$request->request->get('price'0)));
  2815.         $certificate->setPriceOffer(str_replace(',''.'$request->request->get('offerPrice'0)));
  2816.         $pricePartnerPurchase trim($request->request->get('pricePartnerPurchase'));
  2817.         $certificate->setPricePartnerPurchase($pricePartnerPurchase === ''  null  $pricePartnerPurchase);
  2818.         $certificate->setDescription($request->request->get('description'));
  2819.         $certificate->setActive($request->request->has('active'));
  2820.         $certificate->setHidden($request->request->has('hidden'));
  2821.         $certificate->setSpecial123($request->request->getBoolean('special123'));
  2822.         $certificate->setBuyOnlyCode($request->request->getBoolean('buyOnlyCode'));
  2823.         $certificate->setCodesPerItem($request->request->get('codesPerItem'));
  2824.         $certificate->setActiveDays($request->request->getInt('edit-certificate-active-days'));
  2825.         $certificate->setBadgeLabel($request->request->get('badgeLabel'));
  2826.         $certificate->setBadgeBgColor($request->request->get('badgeBgColor'));
  2827.         $certificate->setBadgeTextColor($request->request->get('badgeTextColor'));
  2828.         // if we want to change the suffix, then we will create a new certificate with a new suffix, and simply turn off the current one
  2829.         $certificate->setCodeSuffix($request->request->get('edit-certificate-suffix'));
  2830.         $certificate->setBundlePromoCount($request->request->getInt('bundlePromoCount'));
  2831.         $certificate->setIsSubscription($request->request->getBoolean('isSubscription'));
  2832.         $certificate->setIsRefund($request->request->getBoolean('isRefund'));
  2833.         $certificate->setRefundCommission($request->request->getInt('refundCommission'));
  2834.         $multiUseCodePeriod $request->request->getInt('multiUseCodePeriod') ?: null;
  2835.         $multiUseCodePerPeriod $request->request->getInt('multiUseCodePerPeriod') ?: null;
  2836.         $certificate->setMultiUseCodePeriod($multiUseCodePeriod);
  2837.         $certificate->setMultiUseCodePerPeriod($multiUseCodePerPeriod);
  2838.         $image $request->request->get('certificateImage');
  2839.         if ($image) {
  2840.             $media $certificate->getMedia();
  2841.             if ($media) {
  2842.                 $entityManager->remove($media);
  2843.             }
  2844.             $media = new Media\GiftCertificateMedia();
  2845.             $media->setName($image);
  2846.             $media->setPath(MediaType::TYPE_OFFER_TEASER_PATH);
  2847.             $certificate->setMedia($media);
  2848.         }
  2849.         if (is_array($geoLocationListIDs)) {
  2850.             foreach ($geoLocationListIDs as $geoLocationID) {
  2851.                 $geoLocation $entityManager->find(GeoLocation::class, $geoLocationID);
  2852.                 if ($geoLocation) {
  2853.                     $certificate->addGeoLocation($geoLocation);
  2854.                 }
  2855.             }
  2856.         } else {
  2857.             $geoLocationListIDs = [];
  2858.         }
  2859.         $currentGeoLocationsIDs = [];
  2860.         $geoLocations $certificate->getGeoLocations();
  2861.         foreach ($geoLocations as $location) {
  2862.             $currentGeoLocationsIDs[] = $location->getID();
  2863.         }
  2864.         $geoLocationOnDelete array_diff($currentGeoLocationsIDs$geoLocationListIDs);
  2865.         foreach ($geoLocationOnDelete as $locationID) {
  2866.             $geoLocation $entityManager->find(GeoLocation::class, $locationID);
  2867.             $certificate->removeGeoLocation($geoLocation);
  2868.         }
  2869.         $currentLocationsList = [];
  2870.         $currentLocations $certificate->getGeoLocations();
  2871.         foreach ($currentLocations as $location) {
  2872.             $currentLocationsList[] = $location->getID();
  2873.         }
  2874.         $requestTagIDList $request->request->get('admin-certificate-tag-id') ? $request->request->get('admin-certificate-tag-id') : [];
  2875.         foreach ($requestTagIDList as $index => $tagID) {
  2876.             $tag $entityManager->getRepository(GiftCertificateTag::class)->find($tagID);
  2877.             if ($tag) {
  2878.                 if ($request->request->get('admin-certificate-tag-deleted')[$index] == "true") {
  2879.                     $certificate->deleteTag($tag);
  2880.                 } else {
  2881.                     $certificate->addTag($tag);
  2882.                     $this->logOperatorAction($request$certificate->getID(), 'add certificate tag ' $tag->getTag(), OperatorActionLog::ADD_TAG);
  2883.                 }
  2884.             }
  2885.         }
  2886.         $giftCertificateCategoryIds array_map(
  2887.             static fn (string $id): int => (int) $id,
  2888.             $request->request->get('giftCertificateCategorySelect', []),
  2889.         );
  2890.         $giftCertificateCategories $this->giftCertificateCategoryRepository->findByIds($giftCertificateCategoryIds);
  2891.         foreach ($giftCertificateCategories as $giftCertificateCategory) {
  2892.             $giftCertificateCategory->addGiftCertificate($certificate);
  2893.         }
  2894.         foreach ($certificate->getCategories() as $giftCertificateCategory) {
  2895.             if (!in_array($giftCertificateCategory->getID(), $giftCertificateCategoryIdstrue)) {
  2896.                 $giftCertificateCategory->removeGiftCertificate($certificate);
  2897.             }
  2898.         }
  2899.         $giftCertificateGiftCategoryIds array_map(
  2900.             static fn (string $id): int => (int) $id,
  2901.             $request->request->get('giftCertificateGiftCategorySelect', []),
  2902.         );
  2903.         $giftCertificateGiftCategories $this->giftCertificateGiftCategoryRepository->findByIds($giftCertificateGiftCategoryIds);
  2904.         foreach ($giftCertificateGiftCategories as $giftCertificateGiftCategory) {
  2905.             $giftCertificateGiftCategory->addGiftCertificate($certificate);
  2906.         }
  2907.         foreach ($certificate->getGiftCategories() as $giftCertificateGiftCategory) {
  2908.             if (!in_array($giftCertificateGiftCategory->getID(), $giftCertificateGiftCategoryIdstrue)) {
  2909.                 $giftCertificateGiftCategory->removeGiftCertificate($certificate);
  2910.             }
  2911.         }
  2912.         $giftCertificateGroupIds array_map(
  2913.             static fn (string $id): int => (int) $id,
  2914.             (array) $request->request->get('giftCertificateGroupSelect', []),
  2915.         );
  2916.         $giftCertificateGroups $this->giftCertificateGroupRepository->findByIds($giftCertificateGroupIds);
  2917.         foreach ($giftCertificateGroups as $giftCertificateGroup) {
  2918.             $giftCertificateGroup->addGiftCertificate($certificate);
  2919.         }
  2920.         foreach ($certificate->getGroups() as $giftCertificateGroup) {
  2921.             if (!in_array($giftCertificateGroup->getId(), $giftCertificateGroupIdstrue)) {
  2922.                 $giftCertificateGroup->removeGiftCertificate($certificate);
  2923.             }
  2924.         }
  2925.         $entityManager->flush();
  2926.         $result['categories'] = \implode(
  2927.             ',',
  2928.             array_map(
  2929.                 static fn (GiftCertificateCategory $giftCertificateCategory): int => $giftCertificateCategory->getID(),
  2930.                 $certificate->getCategories()->getValues(),
  2931.             ),
  2932.         );
  2933.         $result['giftCategories'] = \implode(
  2934.             ',',
  2935.             array_map(
  2936.                 static fn (GiftCertificateGiftCategory $giftCertificateGiftCategory): int => $giftCertificateGiftCategory->getID(),
  2937.                 $certificate->getGiftCategories()->getValues(),
  2938.             ),
  2939.         );
  2940.         $result['active'] = $certificate->isActive();
  2941.         $result['locations'] = implode(','$currentLocationsList);
  2942.         $result['certificateID'] = $certificate->getID();
  2943.         if ($certificate->getMedia()) {
  2944.             $result['imageURL'] = $imageService->getImageURLCached($certificate->getMedia(), 2000);
  2945.         } else {
  2946.             $result['imageURL'] = '';
  2947.         }
  2948.         $result['activeDays'] = $certificate->getActiveDays();
  2949.         $result['suffix'] = $certificate->getCodeSuffix();
  2950.         $result['bundlePromoCount'] = $certificate->getBundlePromoCount();
  2951.         return new JsonResponse($result);
  2952.     }
  2953.     /**
  2954.      * @Route("/admin/offer/remove_teaser_logo/{offerID}")
  2955.      */
  2956.     public function removeTeaserLogoAction($offerID) {
  2957.         $entityManager $this->getEntityManager();
  2958.         $result '';
  2959.         $media $entityManager->getRepository(Media::class)->getOfferTeaserLogo($offerID);
  2960.         if (!$media) {
  2961.             return new Response($result);
  2962.         }
  2963.         $entityManager->remove($media);
  2964.         $entityManager->flush();
  2965.         return new Response($result);
  2966.     }
  2967.     /**
  2968.      * @Route("/admin/offer/get_empty_description_block")
  2969.      */
  2970.     public function getDescriptionsAction(Request $request) {
  2971.         if (!$request->isXmlHttpRequest()) {
  2972.             return $this->redirect("/admin");
  2973.         }
  2974.         $data['descriptions'] = ['new'];
  2975.         $data['slider'] = $request->request->get('slider');
  2976.         return $this->render('Slivki/admin/offers/offer_description_block.html.twig'$data);
  2977.     }
  2978.     /**
  2979.      * @Route("/admin/offer/ajax_add_description_slider_image")
  2980.      */
  2981.     public function ajaxAddDescriptionSliderImage(Request $request) {
  2982.         if (!$request->isXmlHttpRequest()) {
  2983.             return $this->redirect("/admin");
  2984.         }
  2985.         $result['descriptionSliderImages'] = $this->get('twig')->render(
  2986.             'Slivki/admin/offers/add_offer_description_slider_image.html.twig', [
  2987.             'imageID' => $request->request->get('imageID'),
  2988.             'imageURL' => $request->request->get('imageURL'),
  2989.             'imageName' => $request->request->get('imageName')
  2990.         ]);
  2991.         return new Response(json_encode($result));
  2992.     }
  2993.     /**
  2994.      * @Route("/admin/offer/remove_offer_description/{offerDescriptionID}")
  2995.      */
  2996.     public function removeOfferDescription(CacheService $cacheServiceKernelInterface $kernel$offerDescriptionID) {
  2997.         $entityManager $this->getEntityManager();
  2998.         $offerDescription $entityManager->find(EntityDescription::class, $offerDescriptionID);
  2999.         if (!$offerDescription) {
  3000.             return new Response();
  3001.         }
  3002.         $offerDescriptionSliderImages $offerDescription->getEntityDescriptionSliderImages();
  3003.         $fs = new Filesystem();
  3004.         /** @var EntityDescriptionSliderImage $offerDescriptionSliderImage */
  3005.         foreach ($offerDescriptionSliderImages as $offerDescriptionSliderImage) {
  3006.             $fullPathToImage $kernel->getProjectDir() . '/public' $offerDescriptionSliderImage->getImageUrl();
  3007.             if ($fs->exists($fullPathToImage)) {
  3008.                 $fs->remove($fullPathToImage);
  3009.             }
  3010.             $entityManager->remove($offerDescriptionSliderImage);
  3011.         }
  3012.         $offerDescription->getOffer()->setLuceneReindex(true);
  3013.         $entityManager->remove($offerDescription);
  3014.         $entityManager->flush();
  3015.         $cacheService->deleteEntityDescription($offerDescriptionID);
  3016.         return new Response();
  3017.     }
  3018.     /**
  3019.      * @Route("/admin/offer/remove_offer_description_slider_image/{offerDescriptionSliderImageID}")
  3020.      */
  3021.     public function removeSaleDescriptionGalleryImage($offerDescriptionSliderImageID) {
  3022.         $entityManager $this->getEntityManager();
  3023.         $saleDescriptionGalleryImage $entityManager->find(EntityDescriptionSliderImage::class, $offerDescriptionSliderImageID);
  3024.         if ($saleDescriptionGalleryImage) {
  3025.             $entityManager->remove($saleDescriptionGalleryImage);
  3026.             $entityManager->flush();
  3027.         }
  3028.         return new Response();
  3029.     }
  3030.     /**
  3031.      * @Route("/admin/offer/ajax_upload_images")
  3032.      */
  3033.     public function ajaxUploadImages(Request $requestKernelInterface $kernel) {
  3034.         $imageFolder $kernel->getProjectDir() . Offer::DESCRIPTION_IMAGES_PATH;
  3035.         $uploadedFile $request->files->get('file');
  3036.         if ($uploadedFile) {
  3037.             $fs = new Filesystem();
  3038.             $originalName $uploadedFile->getClientOriginalName();
  3039.             $newFileName time() . '_' $originalName;
  3040.             while ($fs->exists($imageFolder $newFileName)) {
  3041.                 $newFileName time() . '_' $newFileName;
  3042.             }
  3043.             $imagine = new Imagine();
  3044.             $image $imagine->open($uploadedFile->getRealPath());
  3045.             $imageSize $image->getSize();
  3046.             $returnImageName $newFileName;
  3047.             $bigImage false;
  3048.             if ($imageSize->getWidth() > 100 && $imageSize->getHeight() > 100) {
  3049.                 $limitImageWidth 1100;
  3050.                 $returnImageName SaleRepository::HASWM_IMAGE_PREFIX $newFileName;
  3051.                 $image->save($imageFolder $returnImageName);
  3052.                 $image $this->createImageWithWatermark($image$imagine);
  3053.                 if ($image) {
  3054.                     $image->save($imageFolder SaleRepository::WITHWM_IMAGE_PREFIX $newFileName);
  3055.                     unset($imagine$image);
  3056.                 }
  3057.                 if ($imageSize->getWidth() > $limitImageWidth) {
  3058.                     unlink($imageFolder $returnImageName);
  3059.                     $bigImage true;
  3060.                     $imagine = new Imagine();
  3061.                     $image $imagine->open($uploadedFile->getRealPath());
  3062.                     $newFileName SaleRepository::RESIZED_IMAGE_PREFIX $newFileName;
  3063.                     $returnImageName SaleRepository::HASWM_IMAGE_PREFIX $newFileName;
  3064.                     $newImageSize $imageSize->widen($limitImageWidth);
  3065.                     $image->resize($newImageSize);
  3066.                     $image->save($imageFolder $returnImageName);
  3067.                     $image $this->createImageWithWatermark($image$imagine);
  3068.                     if ($image) {
  3069.                         $image->save($imageFolder SaleRepository::WITHWM_IMAGE_PREFIX $newFileName);
  3070.                     }
  3071.                 }
  3072.                 unlink($uploadedFile->getRealPath());
  3073.             } else {
  3074.                 $uploadedFile->move($imageFolder$returnImageName);
  3075.             }
  3076.             return new Response(json_encode(array('location' => $returnImageName'bigImage' => $bigImage)));
  3077.         } else {
  3078.             // Notify editor that the upload failed
  3079.             header("HTTP/1.0 500 Server Error");
  3080.         }
  3081.     }
  3082.     /** @Route("/admin/offer/suggest/{cityID}") */
  3083.     public function suggestAction(Request $request$cityID) {
  3084.         $sql "select id, title as text from offer where offer.active and now() between offer.active_since and offer.active_till 
  3085.             and title ilike '%" pg_escape_string($request->query->get('q')) . "%' 
  3086.             and id in (select entity_id from category2entity inner join category on category2entity.category_id = category.id and category.city_id = " . (int)$cityID ")";
  3087.         $offerList $this->getDoctrine()->getManager()->getConnection()->executeQuery($sql)->fetchAll(\PDO::FETCH_ASSOC);
  3088.         return new Response(json_encode($offerList));
  3089.     }
  3090.     /** @Route("/admin/offer/codes/used/get/{offerID}") */
  3091.     public function getUsedCodesAction($offerID) {
  3092.         $offer $this->getEntityManager()->find(Offer::class, $offerID);
  3093.         if (!$offer) {
  3094.             $content '';
  3095.         } else {
  3096.             $content $offer->getLastActiveCodePool()->getCodesUsed();
  3097.         }
  3098.         $response = new StreamedResponse(function () use ($content) {
  3099.             $handle fopen('php://output''r+');
  3100.             fputs($handlestr_replace("\n""\r\n"$content));
  3101.             fclose($handle);
  3102.         });
  3103.         $response->setStatusCode(200);
  3104.         $response->headers->set('Content-Type''text/plain');
  3105.         $response->headers->set('Content-Disposition''attachment; filename="used-codes-' $offerID '.txt"');
  3106.         return $response;
  3107.     }
  3108.     /** @Route("/admin/offer/show_in_telegram_bot/set") */
  3109.     public function setShowInTelegramBot(Request $request) {
  3110.         $offerID $request->request->getInt('offerID');
  3111.         if (!$offerID) {
  3112.             return new Response();
  3113.         }
  3114.         $entityManager $this->getEntityManager();
  3115.         $offer $entityManager->find(Offer::class, $offerID);
  3116.         if (!$offer) {
  3117.             return new Response();
  3118.         }
  3119.         $offer->setTelegramBotShow($request->request->getBoolean('show'));
  3120.         $entityManager->flush();
  3121.         return new  Response();
  3122.     }
  3123.     /** @Route("/admin/offer/certificate/position/save") */
  3124.     public function setCertificatePosition(Request $request) {
  3125.         $certificateListID $request->request->get('certificatePositionList');
  3126.         $entityManager $this->getEntityManager();
  3127.         foreach ($certificateListID as $id => $position) {
  3128.             $certificate $entityManager->find(GiftCertificate::class, $id);
  3129.             $certificate->setPosition($position);
  3130.         }
  3131.         $entityManager->flush();
  3132.         return new Response();
  3133.     }
  3134.     /** @Route("/admin/offer/food_extension/get/{foodOfferExtensionID}") */
  3135.     public function getOfferExtensionAction(
  3136.         $foodOfferExtensionID,
  3137.         OfferExtensionOnlineCategoryRepositoryInterface $offerExtensionOnlineCategoryRepository,
  3138.         QueryBusInterface $queryBus
  3139.     ): Response {
  3140.         $foodOfferExtensionID = (int)$foodOfferExtensionID;
  3141.         $entityManager $this->getDoctrine()->getManager('admin');
  3142.         $foodOfferExtension $entityManager->find(FoodOfferExtension::class, $foodOfferExtensionID);
  3143.         if (!$foodOfferExtension) {
  3144.             $foodOfferExtension = new FoodOfferExtension();
  3145.         }
  3146.         return $this->render('Slivki/admin/offers/edit_food_extension_form.html.twig', [
  3147.             'foodOfferExtension' => $foodOfferExtension,
  3148.             'offerExtensionCategoryList' => $entityManager
  3149.                 ->getRepository(OfferExtensionCategory::class)
  3150.                 ->findAll(),
  3151.             'offerExtensionOnlineCategoryList' => $offerExtensionOnlineCategoryRepository->findAll(),
  3152.             'visibilities' => $queryBus->handle(new GetOfferExtensionVisibilitiesQuery($foodOfferExtensionID)),
  3153.         ]);
  3154.     }
  3155.     /** @Route("/admin/offer/food_extension/save/{offerID}") */
  3156.     public function saveOfferExtensionAction(
  3157.         $offerID,
  3158.         Request $request,
  3159.         OfferExtensionOnlineCategoryRepositoryInterface $offerExtensionOnlineCategoryRepository,
  3160.         MessageBusInterface $commandBus
  3161.     ): JsonResponse {
  3162.         $foodOfferExtensionID $request->request->getInt('editFoodID');
  3163.         $entityManager $this->getDoctrine()->getManager('admin');
  3164.         $foodOfferExtension $entityManager->find(FoodOfferExtension::class, $foodOfferExtensionID);
  3165.         $oldID 0;
  3166.         if (!$foodOfferExtension) {
  3167.             $foodOfferExtension $request->request->get('editOfferFoodType') === 'FoodOfferOptionExtension'
  3168.                 ? new FoodOfferOptionExtension()
  3169.                 : new FoodOfferExtension();
  3170.             $entityManager->find(Offer::class, $offerID)->addExtension($foodOfferExtension);
  3171.         }
  3172.         $foodOfferExtension->setName($request->request->get('editFoodName'));
  3173.         $foodOfferExtension->setShortDescription($request->request->get('editFoodShortDescription'));
  3174.         $foodOfferExtension->setDescription($request->request->get('editFoodDescription'));
  3175.         $foodOfferExtension->setPriceDescription($request->request->get('editFoodPriceDescription'));
  3176.         $foodOfferExtension->setPartnerItemID($request->request->get('editFoodPartnerID'));
  3177.         $foodOfferExtension->setPrice((float)str_replace(',''.'$request->request->get('editFoodRegularPrice')));
  3178.         $foodOfferExtension->setDishDeliveryPrice((float)str_replace(',''.'$request->request->get('editOfferDishDeliveryPrice')));
  3179.         $foodOfferExtension->setPickupPrice((float)str_replace(',''.'$request->request->get('editOfferDishPickupPrice')));
  3180.         $foodOfferExtension->setIsDelivery($request->request->getBoolean('switchOnDelivery'));
  3181.         $foodOfferExtension->setIsPickup($request->request->getBoolean('switchOnPickup'));
  3182.         $foodOfferExtension->setPriceDeliveryType($request->request->get('priceDeliveryTypeOffer'));
  3183.         $foodOfferExtension->setProductsPerCode($request->request->getInt('editFoodProductsPerCode'));
  3184.         $foodOfferExtension->setActive(true);
  3185.         $foodOfferExtension->setSauceNeed($request->request->getBoolean('switchOnSauceNeed'));
  3186.         $foodOfferExtension->setSpecial123($request->request->getBoolean('special123'));
  3187.         $foodOfferExtension->setBadgeLabel($request->request->get('badgeLabel'));
  3188.         $foodOfferExtension->setBadgeBgColor($request->request->get('badgeBgColor'));
  3189.         $foodOfferExtension->setBadgeTextColor($request->request->get('badgeTextColor'));
  3190.         $weight $request->request->get('editFoodWeight');
  3191.         $foodOfferExtension->setWeight($weight ? (float)str_replace(',''.'$weight) : null);
  3192.         $componentsCount $request->request->getInt('editFoodСomponentsСount');
  3193.         $foodOfferExtension->setComponentsCount($componentsCount ?: null);
  3194.         $foodImage $request->request->get('editOfferFoodImage');
  3195.         if ($foodImage) {
  3196.             $foodExtensionMedia $foodOfferExtension->getMedia();
  3197.             if ($foodExtensionMedia) {
  3198.                 $entityManager->remove($foodExtensionMedia);
  3199.             }
  3200.             $foodExtensionMedia = new Media\OfferExtensionMedia();
  3201.             $foodExtensionMedia->setName($foodImage);
  3202.             $foodExtensionMedia->setPath(MediaType::DEFAULT_IMAGE_PATH);
  3203.             $entityManager->persist($foodExtensionMedia);
  3204.             $foodOfferExtension->setMedia($foodExtensionMedia);
  3205.         }
  3206.         $priceByTimePrice $request->request->get('foodPriceByTimePrice', []);
  3207.         $priceByTimeHoursFrom $request->request->get('foodPriceByTimeHoursFrom', []);
  3208.         $priceByTimeHoursTo $request->request->get('foodPriceByTimeHoursTo', []);
  3209.         $priceByTime = [];
  3210.         foreach ($priceByTimePrice as $key => $item) {
  3211.             $priceByTime[] = [$priceByTimeHoursFrom[$key], $priceByTimeHoursTo[$key], $item];
  3212.         }
  3213.         $foodOfferExtension->setPriceByTime(json_encode($priceByTime));
  3214.         $offerExtensionCategoryIDList = (array) $request->request->get('editOfferFoodCategorySelect', []);
  3215.         foreach ($offerExtensionCategoryIDList as $offerExtensionCategoryID) {
  3216.             $offerExtensionCategory $entityManager->find(
  3217.                 OfferExtensionCategory::class,
  3218.                 $offerExtensionCategoryID
  3219.             );
  3220.             if ($offerExtensionCategory) {
  3221.                 $offerExtensionCategory->addOfferExtension($foodOfferExtension);
  3222.                 if ($request->request->getBoolean('addSauceNeed')) {
  3223.                     foreach ($offerExtensionCategory->getOfferExtensions() as $extension) {
  3224.                         if ($extension->getOffer()->getID() === $offerID) {
  3225.                             $extension->setSauceNeed(true);
  3226.                         }
  3227.                     }
  3228.                 } elseif ($request->request->getBoolean('deleteSauceNeed')) {
  3229.                     foreach ($offerExtensionCategory->getOfferExtensions() as $extension) {
  3230.                         if ($extension->getOffer()->getID() === $offerID) {
  3231.                             $extension->setSauceNeed(false);
  3232.                         }
  3233.                     }
  3234.                 }
  3235.             }
  3236.         }
  3237.         /** @var OfferExtensionCategory $offerExtensionCategory */
  3238.         foreach ($foodOfferExtension->getCategories()->toArray() as $offerExtensionCategory) {
  3239.             if (!in_array($offerExtensionCategory->getID(), $offerExtensionCategoryIDList)) {
  3240.                 $offerExtensionCategory->removeOfferExtension($foodOfferExtension);
  3241.             }
  3242.         }
  3243.         $offerExtensionOnlineCategoryIdList = (array) $request->request->get('editOfferFoodOnlineCategorySelect', []);
  3244.         foreach ($offerExtensionOnlineCategoryIdList as $offerExtensionOnlineCategoryId) {
  3245.             $offerExtensionOnlineCategory $offerExtensionOnlineCategoryRepository->findById($offerExtensionOnlineCategoryId);
  3246.             if (!$offerExtensionOnlineCategory instanceof OfferExtensionOnlineCategory) {
  3247.                 continue;
  3248.             }
  3249.             $offerExtensionOnlineCategory->addOfferExtension($foodOfferExtension);
  3250.         }
  3251.         foreach ($foodOfferExtension->getOnlineCategories() as $offerExtensionOnlineCategory) {
  3252.             if (!in_array($offerExtensionOnlineCategory->getID(), $offerExtensionOnlineCategoryIdList)) {
  3253.                 $offerExtensionOnlineCategory->removeOfferExtension($foodOfferExtension);
  3254.             }
  3255.         }
  3256.         $entityManager->flush();
  3257.         $commandBus->dispatch(new SaveOfferExtensionOnlineCategoryOfferRelationsCommand($offerID));
  3258.         return new JsonResponse([
  3259.             'id' => $foodOfferExtension->getID(),
  3260.             'name' => $foodOfferExtension->getName(),
  3261.             'old' => $oldID,
  3262.         ]);
  3263.     }
  3264.     /** @Route("/admin/offer/food_extension/remove/{foodOfferExtensionID}") */
  3265.     public function removeOfferExtensionAction(OfferCacheService $offerCacheService$foodOfferExtensionID): Response
  3266.     {
  3267.         $foodOfferExtensionID = (int)$foodOfferExtensionID;
  3268.         $entityManager $this->getDoctrine()->getManager('admin');
  3269.         $foodOfferExtension $entityManager->find(FoodOfferExtension::class, $foodOfferExtensionID);
  3270.         if ($foodOfferExtension) {
  3271.             $entityManager->remove($foodOfferExtension);
  3272.             $entityManager->flush();
  3273.             $offerCacheService->deleteExtension($foodOfferExtensionID);
  3274.         }
  3275.         return new Response();
  3276.     }
  3277.     /** @Route("/admin/offer/online-settings/save", methods={"POST"}) */
  3278.     public function saveOfferOnlineOrderSettingsAction(Request $request): JsonResponse
  3279.     {
  3280.         $offerID $request->request->getInt('offerID');
  3281.         if (!$offerID) {
  3282.             return new JsonResponse(['status' => 'error''message' => 'ID оффера не было передано в параметрах'], Response::HTTP_OK);
  3283.         }
  3284.         if ($offerID == 253544) {
  3285.             Logger::instance('SLIVKIPAYDEBUG')->info($this->getUser()->getEmail());
  3286.         }
  3287.         $entityManager $this->getEntityManager();
  3288.         $offer $entityManager->find(Offer::class, $offerID);
  3289.         if (!$offer) {
  3290.             return new JsonResponse(['status' => 'error''message' => 'Оффер не найден'], Response::HTTP_OK);
  3291.         }
  3292.         $onlineOrderSettings $offer->getOnlineOrderSettings();
  3293.         if (!$onlineOrderSettings) {
  3294.             $onlineOrderSettings = new OnlineOrderSettings();
  3295.         }
  3296.         $minDeliverySum $request->request->get('minDeliverySum');
  3297.         $processedMinDeliverySum = ($minDeliverySum || $minDeliverySum === "0") ? str_replace(',''.'$minDeliverySum) : null;
  3298.         $onlineOrderSettings->setMinDeliverySum($processedMinDeliverySum);
  3299.         $minSumForFreeDelivery $request->request->get('minSumForFreeDelivery');
  3300.         $processedMinSumForFreeDelivery = ($minSumForFreeDelivery || $minSumForFreeDelivery === "0") ? str_replace(',''.'$minSumForFreeDelivery) : null;
  3301.         $onlineOrderSettings->setMinSumForFreeDelivery($processedMinSumForFreeDelivery);
  3302.         $deliveryPrice $request->request->get('deliveryPrice');
  3303.         $processedDeliveryPrice = ($deliveryPrice || $deliveryPrice === "0") ? str_replace(',''.'$deliveryPrice) : null;
  3304.         $onlineOrderSettings->setDeliveryPrice($processedDeliveryPrice);
  3305.         $orderPeriodInDays $request->request->get('orderPeriodInDays');
  3306.         $processedDeliveryPrice = ($orderPeriodInDays || $orderPeriodInDays === "0") ? intval($orderPeriodInDays) : null;
  3307.         $onlineOrderSettings->setOrderPeriodInDays($processedDeliveryPrice);
  3308.         $onlineOrderSettings->setAllowedPaymentMethods($request->request->get('allowedPaymentMethods'));
  3309.         $onlineOrderSettings->setPickupEnabled($request->request->getBoolean('pickupEnabled'));
  3310.         $onlineOrderSettings->setDefaultPickup($request->request->getBoolean('defaultPickup'));
  3311.         $onlineOrderSettings->setDeliveryEnabled($request->request->getBoolean('deliveryEnabled'));
  3312.         $onlineOrderSettings->setEmail($request->request->get('email'));
  3313.         $onlineOrderSettings->setDeliveryTimeFrom($request->request->get('deliveryTimeFrom'));
  3314.         $onlineOrderSettings->setDeliveryTimeTill($request->request->get('deliveryTimeTill'));
  3315.         $onlineOrderSettings->setDeliveryPriceInfo($request->request->get('deliveryPriceInfo') ?: null);
  3316.         $deliverySchedule $request->request->get('deliverySchedule');
  3317.         $onlineOrderSettings->setDeliverySchedule(empty($deliverySchedule) ? null $deliverySchedule);
  3318.         $onlineOrderSettings->setDeliveryLeadType($request->request->get('deliveryLeadType'));
  3319.         $deliveryLeadTime $request->request->get('deliveryLeadTime');
  3320.         $onlineOrderSettings->setDeliveryLeadTime($deliveryLeadTime === '' null $deliveryLeadTime);
  3321.         $onlineOrderSettings->setDeliveryIntervalBetweenOrdersType($request->request->get('deliveryIntervalBetweenOrdersType'));
  3322.         $deliveryIntervalBetweenOrdersTime $request->request->get('deliveryIntervalBetweenOrdersTime');
  3323.         $onlineOrderSettings->setDeliveryIntervalBetweenOrdersTime($deliveryIntervalBetweenOrdersTime === '' null $deliveryIntervalBetweenOrdersTime);
  3324.         $onlineOrderSettings->setDeliveryDisableType($request->request->get('deliveryDisableType'));
  3325.         $deliveryDisableTime $request->request->get('deliveryDisableTime');
  3326.         $onlineOrderSettings->setDeliveryDisableTime($deliveryDisableTime === '' null $deliveryDisableTime);
  3327.         $onlineOrderSettings->setDeliveryNearlyEnabled($request->request->getBoolean('deliveryNearlyEnabled'));
  3328.         $pickupLeadTime $request->request->get('pickupLeadTime');
  3329.         $onlineOrderSettings->setPickupLeadTime($pickupLeadTime === '' null : (int) $pickupLeadTime);
  3330.         $onlineOrderSettings->setPriceCodeDependsOnOrder($request->request->get('priceCodeDependsOnOrder' ?: null));
  3331.         $hasDeliveryWorkingTime false;
  3332.         $deliveryWorkingTime = [];
  3333.         foreach ($request->request->get('deliveryWorkingTime') as $item) {
  3334.             $deliveryOneDayWorkingTime $this->serializer->deserialize($itemDeliveryOneDayWorkingTimeDto::class, SerializerConfig::JSON);
  3335.             if (!$deliveryOneDayWorkingTime->isDayOff()) {
  3336.                 $hasDeliveryWorkingTime true;
  3337.             }
  3338.             $deliveryWorkingTime[] = $deliveryOneDayWorkingTime;
  3339.         }
  3340.         $onlineOrderSettings->setDeliveryWorkingTime($hasDeliveryWorkingTime $this->serializer->serialize($deliveryWorkingTimeSerializerConfig::JSON) : null);
  3341.         $pickupCookingTime $request->request->get('pickupCookingTime');
  3342.         $onlineOrderSettings->setPickupCookingTime('' === $pickupCookingTime null $pickupCookingTime);
  3343.         $onlineOrderSettings->setPendingOrderAllowed($request->request->getBoolean('pendingOrderAllowed'));
  3344.         $receivingOrdersSchedule $request->request->get('receivingOrdersSchedule');
  3345.         $onlineOrderSettings->setReceivingOrdersSchedule(
  3346.             null === $receivingOrdersSchedule
  3347.                 null
  3348.                 json_decode($receivingOrdersScheduletrue512JSON_THROW_ON_ERROR)
  3349.         );
  3350.         $offer->setOnlineOrderSettings($onlineOrderSettings);
  3351.         $entityManager->flush();
  3352.         return new JsonResponse(['status' => 'success''message' => 'Настройки сохранены'], Response::HTTP_OK);
  3353.     }
  3354.     /** @Route("/admin/offer/set/api/payed-category") */
  3355.     public function setApiPayedCategoryAction(Request $request) {
  3356.         $categoryID $request->request->getInt('categoryID');
  3357.         $offerID $request->request->getInt('offerID');
  3358.         $position $request->request->getInt('position');
  3359.         $entityManager $this->getDoctrine()->getManager('admin');
  3360.         $payedCategoryRepository $entityManager->getRepository(OfferPayedCategoryMobile::class);
  3361.         $payedCategory $payedCategoryRepository->findOneBy(['categoryID' => $categoryID'entityID' => $offerID]);
  3362.         if (!$payedCategory) {
  3363.             $payedCategory = new OfferPayedCategoryMobile();
  3364.             $payedCategory->setCategoryID($categoryID);
  3365.             $payedCategory->setEntityID($offerID);
  3366.             $entityManager->persist($payedCategory);
  3367.         }
  3368.         if(!$position) {
  3369.             $entityManager->remove($payedCategory);
  3370.         } else {
  3371.             $isExist $payedCategoryRepository->findOneBy(['categoryID' => $categoryID'position' => $position]);
  3372.             if ($isExist) {
  3373.                 $offer $entityManager->find(Offer::class, $isExist->getEntityID());
  3374.                 $hasCategory $offer->hasCategory($categoryID);
  3375.                 if ($isExist && $hasCategory) {
  3376.                     return new JsonResponse(['error' => true'msg' => 'Позиция уже занята']);
  3377.                 }
  3378.             }
  3379.             if ($isExist && !$hasCategory) {
  3380.                 $entityManager->remove($isExist);
  3381.             }
  3382.             $payedCategory->setPosition($position);
  3383.         }
  3384.         $entityManager->flush();
  3385.         return new JsonResponse(['categoryID' => $categoryID'offerID' => $offerID'position' => $position]);
  3386.     }
  3387.     /** @Route("/admin/offer/certificate/get/tags/{certificateID}") */
  3388.     public function getGiftCertificateTagsAction(Request $request$certificateID) {
  3389.         $entityManager $this->getEntityManager();
  3390.         $certificate $entityManager->getRepository(GiftCertificate::class)->find($certificateID);
  3391.         if (!$certificate) {
  3392.             return new Response();
  3393.         }
  3394.         $result['html'] = $this->get('twig')->render('Slivki/admin/tags/gift_certificate_list.html.twig', ['tags' => $certificate->getTags()]);
  3395.         return new JsonResponse($result);
  3396.     }
  3397.     /** @Route("/admin/offer_extension/position/update") */
  3398.     public function updateOfferExtensionPosition(Request $request): JsonResponse
  3399.     {
  3400.         $em $this->getDoctrine()->getManager('admin');
  3401.         $foodPositions $request->request->get('position');
  3402.         if ($foodPositions) {
  3403.             foreach ($foodPositions as $foodId => $position) {
  3404.                 /** @var OfferExtension|null $foodExtension */
  3405.                 $foodExtension $em->find(OfferExtension::class, (int) $foodId);
  3406.                 if (null === $foodExtension) {
  3407.                     continue;
  3408.                 }
  3409.                 $foodExtension->setPosition((int) $position);
  3410.             }
  3411.             $em->flush();
  3412.         }
  3413.         return new JsonResponse();
  3414.     }
  3415. }