src/Controller/ProductController.php line 340

  1. <?php 
  2. namespace App\Controller;
  3. use App\Entity\AttributeItems;
  4. use App\Entity\Attributes;
  5. use App\Entity\Products;
  6. use App\Entity\Category;
  7. use App\Entity\Options;
  8. use App\Entity\MeasurmentUnit;
  9. use App\Entity\SiteProductsMedia;
  10. use App\Entity\MediaObject;
  11. use Doctrine\ORM\EntityManagerInterface;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\Routing\Annotation\Route;
  15. use Symfony\Component\HttpKernel\Attribute\AsController;
  16. use Symfony\Component\HttpFoundation\JsonResponse;
  17. use App\Repository\ProductsRepository;
  18. use App\Repository\SiteProductsRepository;
  19. use App\Repository\ProductBalanceInStorageRepository;
  20. use App\Repository\MediaObjectsRepository;
  21. use Symfony\Component\HttpFoundation\StreamedResponse;
  22. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  23. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  24. use PhpOffice\PhpSpreadsheet\IOFactory;
  25. use App\Service\Translit;
  26. use Intervention\Image\ImageManager;
  27. use Symfony\Component\HttpKernel\KernelInterface
  28. use App\Service\ImageResize;
  29. #[AsController]
  30. class ProductController
  31. {
  32.     private $ProductsRepository;
  33.     private $entityManager;
  34.     private $kernel;
  35.     public function __construct(EntityManagerInterface $entityManagerProductsRepository $ProductsRepositoryKernelInterface $kernel  )
  36.     {
  37.         $this->entityManager $entityManager;
  38.         $this->ProductsRepository $ProductsRepository;
  39.         $this->kernel $kernel;
  40.     }
  41.     #[Route(
  42.         name'product_filter'
  43.         path'/api/products/filter',
  44.         methods: ['GET'],
  45.     )]
  46.     public function __invoke(Request $request): Response
  47.     {
  48.         $_get $request->query->all();
  49.         $query =$_get['search']; // Отримуємо параметр "query" з URL.
  50.         $t $_get['type']; // Отримуємо параметр "query" з URL.
  51.         if($t == '1'){
  52.             $data explode(' '$query );
  53.             $products $this->ProductsRepository->searchByNameSpecefycal($data$query);
  54.         }else{
  55.             $products $this->ProductsRepository->searchByNameOrBarcode($query);
  56.         }
  57.         if (empty($products)) {
  58.             return new JsonResponse([]);
  59.         }
  60.         return new JsonResponse($products200);
  61.     }
  62.     #[Route(
  63.         name'get_wp_product_cat'
  64.         path'/wp-get-cat',
  65.         methods: ['GET'],
  66.     )]
  67.     public function get_wp_product_cat(Request $request): Response
  68.     {
  69.         $cats json_decodefile_get_contents('https://kramar-shop.com/importAsd.php'), true );
  70.         // echo "<pre>";
  71.         // print_r($cats); 
  72.         // die;
  73.         foreach($cats as $cat){
  74.             $category $this->entityManager->getRepository(Category::class)->findOneBy(['slug' => $cat['slug']]);
  75.             if(is_null($category)){
  76.                 $category = new Category();
  77.                 $category->setName($cat['name']);
  78.                 $category->setSlug($cat['slug']);
  79.                 $category->setSlug($cat['slug']);
  80.                 foreach($cat['items'] as $item){
  81.                     $prodcut_find $this->entityManager->getRepository(Products::class)->findOneBy(['code1c' => "WP-{$item}"]);
  82.                     if($prodcut_find){
  83.                         $category->addProduct($prodcut_find);
  84.                     }
  85.                 }
  86.             }else{
  87.                 // $category->setType('category');
  88.                 // $category->setMain(true);
  89.                 foreach($cat['items'] as $item){
  90.                     $prodcut_find $this->entityManager->getRepository(Products::class)->findOneBy(['code1c' => "WP-{$item}"]);
  91.                     if($prodcut_find){
  92.                         echo 11;
  93.                         $prodcut_find->addCategory($category);
  94.                         $this->entityManager->persist($prodcut_find);
  95.                         $this->entityManager->flush();
  96.                     }
  97.                 }
  98.             }
  99.             
  100.         }
  101.         die;
  102.         return new JsonResponse('test'200);
  103.     }
  104.     #[Route(
  105.         name'get_wp_product'
  106.         path'/wp-get-product',
  107.         methods: ['GET'],
  108.     )]
  109.     public function get_wp_product(Request $request): Response
  110.     {
  111.         // $prod =  file_get_contents('https://kramar-shop.com/wc-api/wc/v3/products');
  112.         // echo  $prod;
  113.         // die;
  114.         $prod =  json_decodefile_get_contents('https://kramar-shop.com/wp-api.php') );
  115.         // echo '<pre>';
  116.         // print_r($prod);die;
  117.         $measurmentUnitObjs $this->entityManager->getRepository(MeasurmentUnit::class)->findAll();
  118.         $measurmentUnit= [];
  119.         foreach($measurmentUnitObjs as $mu){
  120.             if($mu->getShortName() == 'пак.')
  121.                 $measurmentUnit['уп.'] = $mu;
  122.             else
  123.                 $measurmentUnit[$mu->getShortName()] = $mu;
  124.         }
  125.         foreach($prod as $p){
  126.            
  127.             $find $this->entityManager->getRepository(Products::class)->findOneBy(['code1c' => "WP-{$p->id}"]);
  128.             
  129.             if(is_null$find )){
  130.                 $product = new Products();
  131.                 $product->setName($p->name);
  132.                 $product->setDescription($p->description);
  133.                 $product->setMeasurementUnit$measurmentUnit[$p->custom_weight]);
  134.                 $product->setShow( ($p->custom_weight == 'publish')? truefalse);
  135.                 $product->setCode1c("WP-{$p->id}");
  136.                 $product->setPrice($p->price);
  137.                 $this->entityManager->persist($product);
  138.             }else{
  139.                 $find->setPrice($p->price);
  140.                 $this->entityManager->persist($find);
  141.                 
  142.             }
  143.             $this->entityManager->flush();
  144.         }
  145.         die;
  146.     }
  147.     #[Route(
  148.         name'set_show_products'
  149.         path'/set-show-products',
  150.     )]
  151.     public function set_show_products(ProductBalanceInStorageRepository $ProductBalanceInStorageRepositoryRequest $request): Response
  152.     {
  153.         die;
  154.         $productsBlance $ProductBalanceInStorageRepository->findAll();
  155.         if($productsBlance){
  156.             echo count($productsBlance) . "<br>";
  157.         }
  158.         $sumBalance = [];
  159.         foreach($productsBlance as $pb){
  160.             $id $pb->getProduct()->getId();
  161.             if(!isset($sumBalance[$id]))
  162.                 $sumBalance[$id] = ['sum' => 0'product' => $pb->getProduct()];
  163.                 $sumBalance[$id]['sum'] += $pb->getCount();
  164.         }
  165.         $c 0;
  166.         foreach($sumBalance as $sb){
  167.             
  168.             if($sb['sum'] >= 300){
  169.                $c++; 
  170.                $sb['product']->setShow(true);
  171.             }else{
  172.                 $sb['product']->setShow(false);
  173.             }
  174.             $this->entityManager->persist$sb['product'] );
  175.         }
  176.         $this->entityManager->flush();
  177.         echo count($sumBalance) . "<br>";
  178.         echo $c;
  179.         
  180.         die;
  181.     }
  182.     #[Route(
  183.         name'set_site_product_img'
  184.         path'/set-site-product-img',
  185.     )]
  186.     public function set_site_product_img(SiteProductsRepository $SiteProductsRepositoryRequest $request): Response
  187.     {
  188.         $productsSite $SiteProductsRepository->findAll();
  189.         foreach ( $productsSite as $ps){
  190.             $isMedia false;
  191.             // echo '<pre>';
  192.             // echo count($ps->getSiteProductsMedia());
  193.             //print_r($ps->getSiteProductsMedia()); 
  194.             // die;
  195.             if(count($ps->getSiteProductsMedia()) == 0){
  196.                 if($ps->getProducts() != null){
  197.                     foreach($ps->getProducts() as $p){
  198.                         if( !$isMedia AND $p->getMedia() != null AND count($p->getMedia()) > 0){
  199.                             
  200.                             foreach($p->getMedia() as $m){
  201.                                 $spm = new SiteProductsMedia();
  202.                                 $spm->setSiteProduct($ps);
  203.                                 $spm->setMedia($m);
  204.                                 $spm->setMain($m->isMain());
  205.                                 $this->entityManager->persist($spm);
  206.                                 // $this->entityManager->flush();
  207.                                 if($p->getMainMedia() != null){
  208.                                     if($p->getMainMedia()->getId() == $m->getId()){
  209.                                         $ps->setMainSiteProductMedia($spm);
  210.                                         $this->entityManager->persist($spm);
  211.                                     }
  212.                                 }
  213.                                 $isMedia true;
  214.                                 // $this->entityManager->flush();
  215.                             }
  216.                         }
  217.                     }
  218.                         
  219.                 }
  220.                 // var_dump($ps->getMainSiteProductMedia());
  221.             }
  222.         }
  223.         $this->entityManager->flush();
  224.         die;
  225.     }
  226.     #[Route(
  227.         name'get_product'
  228.         path'/get-product',
  229.     )]
  230.     public function get_product(SiteProductsRepository $SiteProductsRepositoryRequest $request): Response
  231.     {
  232.         die;
  233.         $find $this->entityManager->getRepository(Products::class)->findAll();
  234.         foreach($find as $p){
  235.             if(empty($p->getPriceIncome()))
  236.                 continue;
  237.             $arr = [
  238.                 'gurt_1' => round($p->getPriceIncome() + ($p->getPriceIncome() * 0.05), 2),
  239.                 'gurt_2' => round($p->getPriceIncome() + ($p->getPriceIncome() * 0.07), 2),
  240.                 'gurt_3' => round($p->getPriceIncome() + ($p->getPriceIncome() * 0.09), 2),
  241.                 'gurt_4' => round($p->getPriceIncome() + ($p->getPriceIncome() * 0.1), 2),
  242.             ];
  243.             echo $p->getPriceIncome(). '---'.json_encode($arr).'<br>';
  244.             $p->setPriceCategory($arr);
  245.             $this->entityManager->persist($p);
  246.         }
  247.         $this->entityManager->flush();
  248.         return new JsonResponse('test'200);
  249.         // echo count( $find);
  250.         die;
  251.     }
  252.     #[Route(
  253.         name'export_form'
  254.         path'/api/export_csv',
  255.         methods: ['GET']
  256.     )]
  257.     public function export_csvEntityManagerInterface $entityManagerRequest $request): StreamedResponse
  258.     {
  259.             $products $entityManager->getRepository(Products::class)->findAll();
  260.             $attributes $entityManager->getRepository(Attributes::class)->findAll();
  261.             // echo count($products); die;
  262.             if( $products ){
  263.                 $header = [
  264.                     'name',
  265.                     'site_name',
  266.                     'article',
  267.                     'code',
  268.                     'all_category',
  269.                     'last_category',
  270.                     // 'attributes',
  271.                 ];
  272.                 $arrAttr = [];
  273.                 foreach($attributes as $attr){
  274.                     $arrAttr[$attr->getId()] = '';
  275.                     $header[] = $attr->getName();
  276.                 }
  277.                
  278.                 $response = new StreamedResponse(function () use ($arrAttr$header$products) {
  279.                     $csv fopen('php://output''w+');
  280.                     fprintf($csv"\xEF\xBB\xBF");
  281.                     fputcsv($csv$header';');
  282.                     foreach($products as $prod){
  283.                         if(count($prod->getCategory()) > OR count($prod->getAttributeItems()) > 0){
  284.                             $prodAttr $arrAttr;
  285.                             $arr = [];
  286.                             $arr[] = $prod->getName();
  287.                             $siteName '';
  288.                             if($prod->getSiteProduct())
  289.                                 $siteName $prod->getSiteProduct()->getName();
  290.                             $arr[] = $siteName;
  291.                             $arr[] = $prod->getArticle();
  292.                             $arr[] = $prod->getCode1c();
  293.                             
  294.                             $category '';
  295.                             foreach($prod->getCategory() as $cat){
  296.                                 // file_put_contents('Category.log', strpos($category, $cat->getName()) . "\n", FILE_APPEND);
  297.                                 // if($cat->isMain()){
  298.                                 
  299.                                 // }
  300.                                 if($cat->getParent()){
  301.                                     
  302.                                     if($cat->getParent()->getParent()){
  303.                                         $p $cat->getParent()->getParent();
  304.                                         // if($p->isMain()){
  305.                                             if(!str_contains($category$p->getName()."|"))
  306.                                                 $category .= $p->getName()."|";
  307.                                         // }
  308.                                     }
  309.                                     // if($cat->getParent()->isMain()){
  310.                                         if(!str_contains($category$cat->getParent()->getName()."|"))
  311.                                             $category .= $cat->getParent()->getName()."|";
  312.                                     // }
  313.                                 }
  314.                                 if(!str_contains($category$cat->getName()."|"))
  315.                                         $category .= $cat->getName()."|";
  316.                             }
  317.                             $arr[] = $category;
  318.                             $lastCategory '';
  319.                             foreach($prod->getCategory() as $cat){
  320.                                 // if(count($prod->getCategory()) > 0)
  321.                                 $lastCategory .= $cat->getName(). " | ";
  322.                             }
  323.                             $arr[] = $lastCategory;
  324.                             if(count($prod->getAttributeItems()) > 0){
  325.                                 foreach($prod->getAttributeItems() as $attrItem){
  326.                                     if($attrItem->getAttribute() !=null)
  327.                                         $prodAttr[$attrItem->getAttribute()->getId()] = $attrItem->getName();
  328.                                 }
  329.                                 foreach($prodAttr as $v){
  330.                                 
  331.                                     $arr[] = $v;
  332.                                 }
  333.                             }
  334.                             
  335.                             fputcsv($csv$arr';');
  336.                         }
  337.                     }
  338.  
  339.                     fclose($csv);
  340.                 });
  341.                 
  342.                 $response->headers->set('Content-Type''application/csv');
  343.                 $response->headers->set('Content-Encoding''UTF-8');
  344.                 $response->headers->set('Content-Disposition''attachment; filename="file.csv"');
  345.                 $response->headers->set('Cache-Control''no-store');
  346.             }
  347.         
  348.         return $response;
  349.     }
  350.     #[Route(
  351.         name'setMainImage'
  352.         path'/set-main-mage',
  353.     )]
  354.     public function setMainImage(Request $request): Response
  355.     {
  356.         // die;
  357.         $find $this->entityManager->getRepository(Products::class)->findAll();
  358.         $i 0;
  359.         foreach($find as $product){
  360.             if(count($product->getMedia()) > && $product->getMainMedia() == null){
  361.                 $i++;
  362.                 // $product->setMainMedia($product->getMedia()[0]);
  363.                 // $this->entityManager->persist($product);
  364.             }
  365.             if($product->getSiteProduct() != null){
  366.                 // $product->setName($product->getSiteProduct()->getName());
  367.                 // $this->entityManager->persist($product);
  368.             }
  369.         }
  370.         $this->entityManager->flush();
  371.         echo $i;
  372.         // echo count( $find);
  373.         die;
  374.     }
  375.     #[Route(
  376.         name'getPrices'
  377.         path'/get-prices',
  378.     )]
  379.     public function getPricesEntityManagerInterface $entityManagerRequest $request): Response
  380.     {
  381.         // die;
  382.         $category = [];
  383.         $group false;
  384.         // echo '<pre>';
  385.         // print_r($request->query->all());
  386.         // die;
  387.         $category $request->query->get('category');
  388.         $products $entityManager->getRepository(Products::class)->findBy(['show' => true]);
  389.         $optionGroup $entityManager->getRepository(Options::class)->findOneBy(['option_key' => 'show_price_group']);
  390.         if($optionGroup){
  391.             if(!empty($optionGroup->getValue())){
  392.                 $group explode(','$optionGroup->getValue());
  393.             }
  394.         }
  395.         // if(!empty( $category_id)){
  396.         //     $query = $entityManager->getRepository(Category::class)->find($category_id);
  397.         //     $categories[] = $query;
  398.         // }else{
  399.         $categories $entityManager->getRepository(Category::class)->findBy([], ['sort' => 'ASC']);
  400.         // }
  401.         $catArr = [];
  402.         foreach($categories as $cat){
  403.             if( !empty($category) ){
  404.                 if(in_array$cat->getId(), $category) ){
  405.                     $catArr[$cat->getId()] = [
  406.                         'name' => $cat->getName(),
  407.                         'products' => []
  408.                     ];
  409.                 }
  410.             }else{
  411.                 $catArr[$cat->getId()] = [
  412.                     'name' => $cat->getName(),
  413.                     'products' => []
  414.                 ];
  415.             }
  416.                 
  417.         }
  418.         foreach($products as $prod){
  419.             foreach($prod->getCategory() as $prodCat){
  420.                 if(isset($catArr[$prodCat->getId()]))
  421.                     $catArr[$prodCat->getId()]['products'][] = $prod;
  422.             }
  423.         }
  424.         $spreadsheet = new Spreadsheet();
  425.         // Get active sheet - it is also possible to retrieve a specific sheet
  426.         $sheet $spreadsheet->getActiveSheet();
  427.     
  428.         // Set cell name and merge cells
  429.         // $sheet->setCellValue('A1', 'Крамар ціни');
  430.         $sheet->getRowDimension(1)->setRowHeight(90);
  431.         $sheet->getColumnDimension('A')->setWidth(50);
  432.         $sheet->getColumnDimension('B')->setWidth(10);
  433.         $sheet->getColumnDimension('C')->setWidth(30);
  434.         $sheet->getColumnDimension('D')->setWidth(50);
  435.         $sheet->getColumnDimension('E')->setWidth(60);
  436.         $sheet->getColumnDimension('G')->setWidth(60);
  437.         // Set cell alignment and font weight
  438.         $styleArray = [
  439.             'alignment' => [
  440.                 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
  441.                 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
  442.             ],
  443.             'font' => [
  444.                 'bold' => true,
  445.             ],
  446.         ];
  447.         $sheet->getStyle('B1')->applyFromArray($styleArray)->getAlignment()->setWrapText(true);
  448.         $sheet->getStyle('C1')->applyFromArray($styleArray)->getAlignment()->setWrapText(true);
  449.         $sheet->getStyle('A:A')->applyFromArray($styleArray)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  450.         $sheet->mergeCells('A1:B1');
  451.         // Add image to worksheet
  452.         $imgPath 'logo.png';
  453.         $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
  454.         $drawing->setPath($imgPath);
  455.         $drawing->setCoordinates('A1'); // Set coordinates
  456.         $drawing->setWidth(200); // Set width
  457.         $drawing->setHeight(100); // Set height
  458.         $drawing->setWorksheet($sheet);
  459.         
  460.         $sheet->setCellValue('C1''https://felso.com.ua');
  461.         // $sheet->setCellValue('C1', '');
  462.         
  463.         $sheet->mergeCells('A2:G2');
  464.         $sheet->mergeCells('A3:G3');
  465.         $sheet->setCellValue('A2''Адреса компанії: м.Львів, вул.Манастирського 2 ');
  466.         $sheet->setCellValue('A3''Номер телефону   +38 (068) 844-11-44 +38 (073) 844-11-44');
  467.         // $sheet->setCellValue('D3', 'При замовленні від 0 до 100 кг. однієї позиції')->getStyle('D3')->applyFromArray($styleArray)->getAlignment()->setWrapText(true);
  468.         // $sheet->setCellValue('E3', 'При замовленні від 100 до 500 кг. однієї позиції')->getStyle('E3')->applyFromArray($styleArray)->getAlignment()->setWrapText(true);
  469.         // $sheet->setCellValue('F3', 'При замовленні від 500 до 1 тонни однієї позиції')->getStyle('F3')->applyFromArray($styleArray)->getAlignment()->setWrapText(true);
  470.         // $sheet->setCellValue('G3', 'При замовленні від 1 тонни')->getStyle('G3')->applyFromArray($styleArray)->getAlignment()->setWrapText(true);
  471.     
  472.         // Set column names
  473.         $columnNames = [
  474.             'Назва',
  475.             'Артикул',
  476.             '',
  477.             'характеристики',
  478.             'комплектація',
  479.             'Ціна',
  480.             'Посилання',
  481.             // 'Гурт 2',
  482.             // 'Гурт 1',
  483.             // 'VIP',
  484.         ];
  485.         $columnLetter 'A';
  486.         foreach ($columnNames as $key =>$columnName) {
  487.             // Allow to access AA column if needed and more
  488.             $sheet->setCellValue("{$columnLetter}4"$columnName)->getStyle($key)->applyFromArray($styleArray);
  489.             $columnLetter++;
  490.         }
  491.         $row 5;
  492.         foreach($catArr as $key => $category){
  493.             $sheet->setCellValue("A{$row}"$category['name'])->mergeCells("A{$row}:G{$row}");
  494.             $sheet->getStyle("A{$row}")->applyFromArray($styleArray);
  495.             $row++;
  496.             if(count($category['products']) > 0)
  497.                 foreach ($category['products'] as $product) {
  498.                     if($product->isDeleted())
  499.                         continue;
  500.                     /** Характеристики */
  501.                     $params '';
  502.                     foreach($product->getAttributeItems() as $attributeItems){
  503.                         $params .= $attributeItems->getAttribute()->getName() . ' - ' $attributeItems->getName() . "\n";
  504.                     }
  505.                     /** Комплектація */
  506.                     $productComplact '';
  507.                     foreach($product->getProductInfos() as $productInfos){
  508.                         $productComplact .= $productInfos->getName() . "\n";
  509.                     }
  510.                     $columnLetter++;
  511.                     
  512.                     $sheet->getRowDimension($row)->setRowHeight(100*0.75); // переведення 100px в пункти
  513.                     $sheet->setCellValue('A'.$row$product->getName());
  514.                     $sheet->getStyle('A' $row)->getAlignment()->setWrapText(true);
  515.                     $sheet->setCellValue('B'.$row$product->getArticle());
  516.                     $sheet->getStyle('B' $row)->getAlignment()->setWrapText(true); // Вмикає перенесення тексту
  517.                     // $sheet->setCellValue('C'.$row, $product->getPrice());
  518.                     /** Характеристики */
  519.                     $sheet->setCellValue('D'.$rowstrip_tags($params) );
  520.                     $sheet->getStyle('D' $row)->getAlignment()->setWrapText(true); // Вмикає перенесення тексту
  521.                     
  522.                     $sheet->setCellValue('E'.$row$productComplact);
  523.                     $sheet->getStyle('E' $row)->getAlignment()->setWrapText(true); // Вмикає перенесення тексту
  524.                     $sheet->setCellValue('F'.$row$product->getPrice());
  525.                     $sheet->setCellValue('G'.$row'https://felso.com.ua/product/' $product->getId());
  526.                     // $sheet->getStyle('C' . $row)->getAlignment()->setWrapText(true); // Вмикає перенесення тексту
  527.                     // $sheet->getRowDimension($row)->setRowHeight(-1); // Автоматична висота рядка
  528.                     if($product->getMainMedia() != null){
  529.                         
  530.                         // Отримуємо рік і місяць із дати завантаження
  531.                         $uploadDate $product->getMainMedia()->getUploadTimestamp();
  532.                         $year $uploadDate->format('Y');
  533.                         $month $uploadDate->format('m');
  534.                     
  535.                         // Формуємо повний шлях до зображення
  536.                         $imgPath $_SERVER["DOCUMENT_ROOT"] . '/media/' $year '/' $month '/90_px_' $product->getMainMedia()->filePath;
  537.                         if(file_exists($imgPath)){
  538.                         // $ = 'logo.png';
  539.                             $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
  540.                             $drawing->setPath($imgPath);
  541.                             $drawing->setCoordinates('C'.$row); // Set coordinates
  542.                             $drawing->setWidth(150); // Set width
  543.                             $drawing->setHeight(100); // Set height
  544.                             $drawing->setWorksheet($sheet);
  545.                         }
  546.                     
  547.                     }
  548.                     $row++;
  549.                 }
  550.         }
  551.         
  552.         $writer = new Xlsx($spreadsheet);
  553.         $fileName 'products_' date('YmdHis') . '.xlsx';
  554.         $writer->save($fileName);
  555.         // Вивантаження файлу
  556.         // Set the content-type:
  557.         header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  558.         header('Content-Length: ' filesize($fileName));
  559.         readfile($fileName); // send file
  560.         unlink($fileName); // delete file
  561.         return new Response();
  562.     }
  563.     #[Route(
  564.         name'addAttrCategory'
  565.         path'/add-attr-category',
  566.     )]
  567.     public function addAttrCategoryEntityManagerInterface $entityManager ){
  568.         $products $entityManager->getRepository(Products::class)->findBy(['show' => true]);
  569.         foreach( $products as $product ){
  570.             if(count($product->getAttributeItems())  > ){
  571.                 foreach($product->getAttributeItems() as $attrItem){
  572.                     $attibute $attrItem->getAttribute();
  573.                     foreach($product->getCategory() as $category){
  574.                         $attrItem->addCategory($category);
  575.                         $attibute->addCategory($category);
  576.                         $entityManager->persist($attrItem);
  577.                         $entityManager->persist($attibute);
  578.                     }
  579.                 }
  580.             }
  581.             
  582.         }
  583.         $entityManager->flush();
  584.         echo 1111;
  585.         die;
  586.     }   
  587.     #[Route(
  588.         name'get_wp_product_img'
  589.         path'/wp-get-product-img',
  590.         methods: ['GET'],
  591.     )]
  592.     public function get_wp_product_img(Request $request): Response
  593.     {
  594.         $prod =  json_decodefile_get_contents('https://kramar-shop.com/importAsd.php?img=1') );
  595.         // echo '<pre>';
  596.         // print_r($prod);
  597.         // die;
  598.         foreach($prod as $p){
  599.             $find $this->entityManager->getRepository(Products::class)->findOneBy(['code1c' => "WP-{$p->product_id}"]);
  600.             if( !is_null$find ) ){
  601.            
  602.                 // URL, куди ви хочете відправити дані
  603.                 $url 'https://api.kramar-shop.com/api/media_objects?product=' .  $find->getId();
  604.                 // echo " $url<br><br>";
  605.                 // Файл, який ви хочете відправити
  606.                 $file_path $p->url;
  607.                 // Ініціалізуємо cURL-сесію
  608.                 $ch curl_init();
  609.                 // Встановлюємо параметри запиту
  610.                 curl_setopt($chCURLOPT_URL$url);
  611.                 curl_setopt($chCURLOPT_POST1);
  612.                 curl_setopt($chCURLOPT_POSTFIELDS, [
  613.                     'file' => new \CURLFile($file_path)
  614.                 ]);
  615.                 // Виконуємо запит
  616.                 $response curl_exec($ch);
  617.                 // $json = json_decode($response);
  618.                 // Перевіряємо наявність помилок
  619.                 if (curl_errno($ch)) {
  620.                     echo 'Error:' curl_error($ch);
  621.                 }
  622.                 // Закриваємо cURL-сесію
  623.                 curl_close($ch);
  624.                 // Виводимо відповідь сервера
  625.             //     echo $response;
  626.             //     // echo '<pre>111';
  627.             //    var_dump($json);
  628.             }
  629.             // die;
  630.         }
  631.         // $prod =  json_decode( file_get_contents('https://kramar-shop.com/wp-api.php') );
  632.         // // echo '<pre>';
  633.         // // print_r($prod);die;
  634.         // $measurmentUnitObjs = $this->entityManager->getRepository(MeasurmentUnit::class)->findAll();
  635.         // $measurmentUnit= [];
  636.         // foreach($measurmentUnitObjs as $mu){
  637.         //     if($mu->getShortName() == 'пак.')
  638.         //         $measurmentUnit['уп.'] = $mu;
  639.         //     else
  640.         //         $measurmentUnit[$mu->getShortName()] = $mu;
  641.         // }
  642.         // foreach($prod as $p){
  643.            
  644.         //     $find = $this->entityManager->getRepository(Products::class)->findOneBy(['code1c' => "WP-{$p->id}"]);
  645.             
  646.         //     if(is_null( $find )){
  647.         //         $product = new Products();
  648.         //         $product->setName($p->name);
  649.         //         $product->setDescription($p->description);
  650.         //         $product->setMeasurementUnit( $measurmentUnit[$p->custom_weight]);
  651.         //         $product->setShow( ($p->custom_weight == 'publish')? true: false);
  652.         //         $product->setCode1c("WP-{$p->id}");
  653.         //         $product->setPrice($p->price);
  654.         //         $this->entityManager->persist($product);
  655.         //     }else{
  656.         //         $find->setPrice($p->price);
  657.         //         $this->entityManager->persist($find);
  658.                 
  659.         //     }
  660.         //     $this->entityManager->flush();
  661.         // }
  662.         die;
  663.     }
  664.     #[Route(
  665.         name'getDublicate'
  666.         path'/get-dublicate',
  667.     )]
  668.     public function getDublicateEntityManagerInterface $entityManagerRequest $request): Response
  669.     {
  670.         set_time_limit(0);
  671.         $duplicates $entityManager->createQueryBuilder()
  672.         ->select('p.article')
  673.         ->from(Products::class, 'p')
  674.         ->where('p.deleted = FALSE')
  675.         ->groupBy('p.article')
  676.         ->having('COUNT(p.article) > 1')
  677.         ->getQuery()
  678.         ->getResult();
  679.         $i  0;
  680.         foreach ($duplicates as $duplicate) {
  681.             // echo $duplicate['article'] . "<br>";
  682.             $products $entityManager->getRepository(Products::class)
  683.                 ->findBy(['article' => $duplicate['article'], 'deleted' => false]);
  684.             
  685.             // Keep the first product and remove the rest
  686.             $deleted true;
  687.             $isDeleted false;
  688.             foreach ($products as $product) {
  689.                 echo $product->getArticle();
  690.                 if(count($product->getOrderProducts()) > 0){
  691.                     $deleted false;
  692.                     echo ' - - false';
  693.                 }elseif(count$product->getCategory()) > OR count$product->getAttributeItems()) > 0){
  694.                     $deleted false;
  695.                     echo '- false';
  696.                 }else{
  697.                     $deleted true;
  698.                     echo ' - true';
  699.                 }
  700.                 if($deleted AND !$isDeleted){
  701.                     $i++;
  702.                     $isDeleted true;
  703.                     $product->setDeleted(true);
  704.                     $product->setDescription('delete dublicate product ' date('Y-m-d H:i:s'));
  705.                     $entityManager->persist$product );
  706.                 }
  707.                 
  708.                 
  709.                 echo '<br>';
  710.             }
  711.             if($i === 200){
  712.                 $entityManager->flush();
  713.                 $i=0;
  714.             }
  715.         }
  716.         $entityManager->flush();
  717.         die;
  718.     }
  719.     #[Route(
  720.         name'importProductFromExcel'
  721.         path'/product/import-from-excel',
  722.     )]
  723.     function importProductFromExcel(EntityManagerInterface $entityManagerTranslit $translit){
  724.         echo '<pre>';
  725.         $inputFileName 'products.xlsx';
  726.         $spreadsheet IOFactory::load($inputFileName);
  727.         $sheet $spreadsheet->getActiveSheet();
  728.         $i 0;
  729.         $category = [];
  730.         $attributes = [];
  731.         $products = [];  
  732.         // $url = $sheet->getDrawingCollection();
  733.         // $sheet->getCell('C1')->getValue()
  734.         // echo '<pre>';
  735.         // print_r($url);
  736.         // var_dump($url); die;
  737.         // die;
  738.         foreach ($sheet->getRowIterator() as $row) {
  739.             $cellIterator $row->getCellIterator();
  740.             $cellIterator->setIterateOnlyExistingCells(FALSE);
  741.             $data = [];
  742.             foreach ($cellIterator as $cell) {
  743.             //     echo '<pre>';   
  744.             // print_r($cell->getWorksheet()->getDrawingCollection());
  745.                 $value $cell->getValue();
  746.                 // $drawing = $cell->getWorksheet()->getDrawingCollection();
  747.                 // $hyperlink = $cell->getHyperlink();
  748.                 // if ($hyperlink) {
  749.                 //     $value = $hyperlink->getUrl();
  750.                 // }
  751.                 $data[] = $value;
  752.             }
  753.             // Assuming your Excel file has columns: id, name, price
  754.             // echo '<pre>';
  755.             if($i==0){
  756.                 foreach($data as $k => $d){
  757.                     if($k >= AND !empty($d)){
  758.                         $n str_replace(':'''$d);
  759.                         $attributes[$k] = [
  760.                             'name' => trim($n),
  761.                             'slug' => $translit->convert(trim($n)),
  762.                             'items' => []
  763.                         ];
  764.                     }
  765.                 }
  766.                 // print_r($data);
  767.                 $i++;
  768.                 continue;
  769.             }
  770.             
  771.             foreach($data as $k => $d){
  772.                 if($k >= AND !empty($d)){
  773.                     $attributes[$k]['items'][$translit->convert(trim($d))] = trim($d);
  774.                 }
  775.             }
  776.             if(!empty($data[3]))
  777.                 $category$translit->convert(trim$data[4] )) ] = trim$data[4] );
  778.       
  779.             $products[$i]['data'] = $data;
  780.            
  781.             $i++;
  782.         }
  783.         // print_r($category);
  784.         // print_r($attributes);
  785.         // die;
  786.         // die;
  787.         $findCategory $entityManager->getRepository(Category::class)->findAll();
  788.         $findAttributes $entityManager->getRepository(Attributes::class)->findAll();
  789.         foreach($category as $slug =>  $c){
  790.             $find false;
  791.             foreach($findCategory as $fCat){
  792.                 if($fCat->getName() == $c){
  793.                     $find true;
  794.                 }
  795.             }
  796.             if(!$find){
  797.                 $entityCat = new Category();
  798.                 $entityCat->setName($c);
  799.                 $entityCat->setSlug($slug);
  800.                 $entityCat->setMain(true);
  801.                 $entityCat->setType('category');
  802.                 $entityManager->persist$entityCat );
  803.                 
  804.             }
  805.         }
  806.         // echo '<pre>';
  807.         // print_r($attributes); die;
  808.         foreach($attributes as $name => $attrs){
  809.             $attr false;
  810.             $entityAttr '';
  811.             foreach($findAttributes as $fAttr){
  812.                 if($fAttr->getName() == $attrs['name']){
  813.                     $entityAttr $fAttr;
  814.                     $attr true;
  815.                     foreach($attrs['items'] as $i => $a){
  816.                         foreach($fAttr->getAttributeItems() as $f_a_i){
  817.                             if($f_a_i->getName() == $a){
  818.                                 unset($attrs['items'][$i]);
  819.                             }
  820.                         }
  821.                     }
  822.                 }
  823.             }
  824.              
  825.             if(!$attr){
  826.                 $entityAttr = new Attributes();
  827.                 $entityAttr->setName($attrs['name']);
  828.                 $entityAttr->setSlug($attrs['slug']);
  829.                 $entityManager->persist$entityAttr );
  830.             }
  831.             if(count($attrs['items']) > 0){
  832.                 foreach($attrs['items'] as $i => $a){
  833.                     $entityAttrItem = new AttributeItems();
  834.                     $entityAttrItem->setName($a);
  835.                     $entityAttrItem->setSlug($i);
  836.                     $entityAttrItem->setAttribute($entityAttr);
  837.                     $entityManager->persist$entityAttrItem );
  838.                 }
  839.             }
  840.             
  841.         }
  842.         // die;
  843.         $entityManager->flush();
  844.         // die;
  845.         $findCategory $entityManager->getRepository(Category::class)->findAll();
  846.         $findAttributes $entityManager->getRepository(Attributes::class)->findAll();
  847.         $findAttributesItems $entityManager->getRepository(AttributeItems::class)->findAll();
  848.         $findProducts $entityManager->getRepository(Products::class)->findAll();
  849.         $measurmentUnit $entityManager->getRepository(MeasurmentUnit::class)->findOneBy(['name' => 'Штука']);
  850.         // print_r($products); die;    
  851.         foreach($products as $product){
  852.             $search false;
  853.             $findProduct '';
  854.             foreach($findProducts  as $f_p){
  855.                 if($f_p->getArticle() == $product['data'][1]){
  856.                     $search true;
  857.                     $findProduct $f_p;
  858.                 }
  859.             }
  860.             $price floatval(trim(str_replace('грн''' $product['data'][2])));
  861.             if(!$search and !empty($product['data'][0])){
  862.                 $newProduct = new Products();
  863.                 $newProduct->setName($product['data'][0]);
  864.                 $newProduct->setArticle($product['data'][1]);
  865.                 $newProduct->setPrice($price);
  866.                 $newProduct->setShow(true);
  867.                 $findProduct->setBalance(1);
  868.                 // $newProduct->setPackingType($product['data'][7] . ' | ' . $product['data'][7]);
  869.                 $newProduct->getMeasurementUnit($measurmentUnit);
  870.                 foreach($product['data'] as $k => $d){
  871.                     if($k >= AND !empty($d)){
  872.                         foreach($findAttributesItems as $ati){
  873.                             if($ati->getName() == trim($d)){
  874.                                 $newProduct->addAttributeItem($ati);
  875.                             }
  876.                         }
  877.                     }
  878.                     if($k == AND !empty($d)){
  879.                         foreach ($findCategory as $f_c){
  880.                             if($f_c->getName() == trim($d)){
  881.                                 $newProduct->addCategory($f_c);
  882.                             }
  883.                         }
  884.                     }
  885.                 }
  886.                 $entityManager->persist$newProduct );
  887.             }else{
  888.                 echo $findProduct->getName() . "<br>";
  889.                 $findProduct->setPrice($price);
  890.                 $findProduct->setShow(true);
  891.                 $findProduct->setBalance(1);
  892.                 foreach($product['data'] as $k => $d){
  893.                     $searvhAttr false;
  894.                     if($k >= AND !empty($d)){
  895.                         foreach( $findProduct->getAttributeItems() as $productAttrItem){
  896.                             if( $productAttrItem->getName() ==  $d){
  897.                                 $searvhAttr true;
  898.                             }
  899.                         }
  900.                         if(!$searvhAttr){
  901.                             foreach($findAttributesItems as $ati){
  902.                                 if($ati->getName() == trim($d)){
  903.                                     $findProduct->addAttributeItem($ati);
  904.                                 }
  905.                             }
  906.                             $entityManager->persist$findProduct );
  907.                         }
  908.                     }
  909.                 }
  910.                 // if(empty( $findProduct->getCategory() )){
  911.                     foreach($product['data'] as $k => $d){
  912.                         if($k == AND !empty($d)){
  913.                             foreach ($findCategory as $f_c){
  914.                                 if($f_c->getName() == trim($d)){
  915.                                     echo  $f_c->getName(). "<br>";
  916.                                     $findProduct->addCategory($f_c);
  917.                                 }
  918.                             }
  919.                         }
  920.                     }
  921.                 // }
  922.                 
  923.                 $entityManager->persist$findProduct );
  924.                 
  925.             }
  926.         }
  927.         $entityManager->flush();
  928.         // $findProducts = $entityManager->getRepository(Products::class)->findAll();
  929.         // foreach ($sheet->getDrawingCollection() as $in =>  $drawing) {
  930.         //         // print_r($drawing->getCoordinates());
  931.         //         $c = str_replace('E', '', $drawing->getCoordinates() );
  932.         //         // print_r($sheet->getCell( "B$c" )->getValue());
  933.         //         // echo "<br>";
  934.         //         foreach($findProducts  as $f_p){
  935.         //             if($f_p->getArticle() == $sheet->getCell( "B$c" )->getValue()){
  936.         //                 $zipReader = fopen($drawing->getPath(),'r');
  937.         //                 $imageContents = '';
  938.         //                 while (!feof($zipReader)) {
  939.         //                     $imageContents .= fread($zipReader,1024);
  940.         //                 }
  941.         //                 fclose($zipReader);
  942.         //                 $extension = $drawing->getExtension();
  943.         //                 $imageBase64 = base64_encode($imageContents);
  944.         //                 $url = 'https://api-felso-brand.inneti.net/api/media_objects?product=' .  $f_p->getId();
  945.         //                 $imageFile = new \CURLFile($imageBase64, 'image/' . $extension, 'image.' . $extension);
  946.         //                 echo  $url; echo '<br>';
  947.         //                 // Set up the cURL request
  948.         //         // Ініціалізуємо cURL-сесію
  949.         //                 $ch = curl_init();
  950.         //                 // Встановлюємо параметри запиту
  951.         //                 curl_setopt($ch, CURLOPT_URL, $url);
  952.         //                 curl_setopt($ch, CURLOPT_POST, 1);
  953.         //                 curl_setopt($ch, CURLOPT_POSTFIELDS, ['image' => $imageFile]);
  954.         //                 // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  955.         //                 // Execute the cURL request
  956.         //               // Виконуємо запит
  957.         //                 $response = curl_exec($ch);
  958.         //                 // $json = json_decode($response);
  959.         //                 // Перевіряємо наявність помилок
  960.         //                 if (curl_errno($ch)) {
  961.         //                     echo 'Error:' . curl_error($ch);
  962.         //                 }
  963.         //                 // Закриваємо cURL-сесію
  964.         //                 curl_close($ch);
  965.         //                 die;
  966.             
  967.         //             }
  968.         //         }
  969.        
  970.             
  971.         //         // $zipReader = fopen($drawing->getPath(),'r');
  972.         //         // $imageContents = '';
  973.         
  974.         //         // while (!feof($zipReader)) {
  975.         //         //     $imageContents .= fread($zipReader,1024);
  976.         //         // }
  977.         //         // fclose($zipReader);
  978.         //         // $extension = $drawing->getExtension();
  979.         //         // $imageBase64 = base64_encode($imageContents);
  980.         //         // $url = 'https://api-felso-brand.inneti.net/api/media_objects?product=' .  $entity->getId();
  981.         //         // $imageFile = new CURLFile($imageBase64, 'image/' . $extension, 'image.' . $extension);
  982.         //         // // Set up the cURL request
  983.         //         // $ch = curl_init();
  984.         //         // curl_setopt($ch, CURLOPT_URL, $url);
  985.         //         // curl_setopt($ch, CURLOPT_POST, 1);
  986.         //         // curl_setopt($ch, CURLOPT_POSTFIELDS, ['image' => $imageFile]);
  987.         //         // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  988.             
  989.         //         // // Execute the cURL request
  990.         //         // $response = curl_exec($ch);
  991.             
  992.         //         // // Close cURL resource
  993.         //         // curl_close($ch);
  994.             
  995.         //     // }
  996.         //     // $myFileName = '00_Image_'.++$i.'.'.$extension;
  997.         //     // file_put_contents($myFileName,$imageContents);
  998.         // }
  999.         // $entityManager->flush();
  1000.             echo 111;
  1001.         die;
  1002.         // return $this->redirectToRoute('app_homepage');
  1003.     }
  1004.     public function imgCurl($entity$imgUrl$type='img'){
  1005.                 // continue;
  1006.                 // $img = file_get_contents($imgUrl);
  1007.                 $url 'https://api-felso.inneti.net/api/media_objects';
  1008.                 if( $type == 'img' )
  1009.                     $url .= '?product=' .  $entity->getId();
  1010.                 // echo " $url<br><br>";
  1011.                 // Файл, який ви хочете відправити
  1012.                 $file_path $imgUrl;
  1013.                 // Ініціалізуємо cURL-сесію
  1014.                 $ch curl_init();
  1015.                 // Встановлюємо параметри запиту
  1016.                 curl_setopt($chCURLOPT_URL$url);
  1017.                 curl_setopt($chCURLOPT_POST1);
  1018.                 curl_setopt($chCURLOPT_POSTFIELDS, [
  1019.                     'file' => new \CURLFile($file_path)
  1020.                 ]); 
  1021.                 echo '----';
  1022.                 // Виконуємо запит
  1023.                 $response curl_exec($ch);
  1024.                 echo '|||';
  1025.                 // $json = json_decode($response);
  1026.                 // Перевіряємо наявність помилок
  1027.                 if (curl_errno($ch)) {
  1028.                     echo '2Error:' curl_error($ch); die;
  1029.                 }
  1030.                 // Закриваємо cURL-сесію
  1031.                 curl_close($ch);
  1032.                 return $response;
  1033.     }
  1034.     public function newImg($findProducts,  $pathProductsDir$pathNew, ){
  1035.         echo $findProducts->getName() . "+++<br>"
  1036.         $uploadTimestamp = new  \DateTime();
  1037.         $mediaObject = new MediaObject();
  1038.         // $mediaObject->file = $uploadedFile;
  1039.         $mediaObject->uploadTimestamp $uploadTimestamp;
  1040.         $mediaObject->filePath $findProducts->getId().$pathProductsDir;
  1041.         $mediaObject->setName('product_img');
  1042.         $mediaObject->setProduct($findProducts);
  1043.         $this->entityManager->persist$mediaObject );
  1044.         $this->entityManager->flush();
  1045.         $year date('Y');
  1046.         $month date('m');
  1047.         $documentRoot $this->kernel->getProjectDir() . '/public/media';
  1048.         $path $documentRoot "/$year/$month/";
  1049.         $sizes = [902307001200];
  1050.         $manager = new ImageManager(
  1051.             new \Intervention\Image\Drivers\Gd\Driver() 
  1052.         );
  1053.         foreach($sizes as $s){
  1054.             $image $manager->read($pathNew);
  1055.             $image->scale(width$s);
  1056.             $newName "{$s}_px_" .  $findProducts->getId().$pathProductsDir;
  1057.             $image->save($path $newName );
  1058.             $newMedia = new MediaObject();
  1059.             $newMedia->filePath $newName;
  1060.             $newMedia->setName("resize-$s");
  1061.             $newMedia->setSize($s);
  1062.             $newMedia->setResizeImgParent($mediaObject);
  1063.             $this->entityManager->persist($newMedia);
  1064.             $this->entityManager->flush();
  1065.         
  1066.         }
  1067.         $findProducts null;
  1068.         return $mediaObject;
  1069.     }
  1070.     #[Route(
  1071.         name'importProductImg'
  1072.         path'/product/import-img',
  1073.     )]
  1074.     function importProductImg(EntityManagerInterface $entityManagerTranslit $translitMediaObjectsRepository $mediaObjectsRepository, ?\DateTimeInterface $uploadTimestamp){
  1075.         echo '<pre>';
  1076.         $path 'products_img';
  1077.         $nextPaths scandir($path);
  1078.         print_r($nextPaths);
  1079.         foreach($nextPaths as $nextPath){
  1080.             if($nextPath == '.' OR $nextPath == '..')
  1081.                 continue;
  1082.             $pathCat "$path/$nextPath";
  1083.             $pathCatDirs scandir($pathCat);
  1084.             
  1085.             foreach($pathCatDirs as $pathCatDir){
  1086.                 if($pathCatDir == '.' OR $pathCatDir == '..')
  1087.                     continue;
  1088.                 // if($pathCatDir == 'ID1250')
  1089.                 //     die;
  1090.                 // print_r($pathCatDir); die;
  1091.                 file_put_contents('import-img.log'$pathCatDir "\n"FILE_APPEND);
  1092.                 $pathProducts "$pathCat/$pathCatDir";
  1093.                 $pathProductsDirs scandir($pathProducts);
  1094.                 echo "<b>$pathCatDir</b><br>";
  1095.                 $findProducts $entityManager->getRepository(Products::class)->findOneBy(['article' => $pathCatDir]);
  1096.                 
  1097.                 if($findProducts ){
  1098.                     echo "<b>" $findProducts->getName() . "</b><br>";
  1099.                     foreach($findProducts->getMedia() as $m){
  1100.                         echo $m->getId() . "<br>";
  1101.                         $findProducts->removeMedium($m);
  1102.                     }
  1103.                     $mainMedia $findProducts->getMainMedia();
  1104.                     if($mainMedia){
  1105.                         echo "main - " $mainMedia->getId() . "<br>";
  1106.                         $mainMedia->removeMainProduct($findProducts);
  1107.                         $entityManager->persist$findProducts );
  1108.                     }
  1109.                     $MainMediaHover $findProducts->getMainMediaHover();
  1110.                     if($MainMediaHover){
  1111.                         echo "hover - main - " $MainMediaHover->getId() . "<br>";
  1112.                         $MainMediaHover->removeProductsHover($findProducts);
  1113.                         $entityManager->persist$MainMediaHover );
  1114.                     }
  1115.                     $entityManager->persist$findProducts );
  1116.                     $entityManager->flush();
  1117.                    
  1118.                 }else{
  1119.                     continue;
  1120.                 }
  1121.                 // echo $findProducts->getName();
  1122.                 echo "<br>";
  1123.                 foreach($pathProductsDirs as $pathProductsDir){
  1124.                     if($pathProductsDir == '.' OR $pathProductsDir == '..')
  1125.                         continue;
  1126.                     $pathImg =  $this->kernel->getProjectDir() . "/public/$pathProducts/$pathProductsDir";
  1127.                     $pathNew $this->kernel->getProjectDir() . "/public/media/" date('Y') . "/" date('m') . "/".$findProducts->getId()."$pathProductsDir";
  1128.                     echo $pathImg "---<br>";
  1129.                     echo $pathNew "---<br>";
  1130.                     
  1131.                     if($pathProductsDir == '1_0.png'){
  1132.                         if(copy($pathImg$pathNew)){
  1133.                             $mediaObject $this->newImg($findProducts$pathProductsDir$pathNew);
  1134.                             $findProducts->setMainMedia($mediaObject);
  1135.                             $entityManager->persist$findProducts );
  1136.                            
  1137.                         }
  1138.                     }elseif($pathProductsDir == '1_1.png'){
  1139.                         if(copy($pathImg$pathNew)){
  1140.                             $mediaObject $this->newImg($findProducts$pathProductsDir$pathNew);
  1141.                             $findProducts->setMainMediaHover($mediaObject);
  1142.                             $entityManager->persist$findProducts );
  1143.                         }
  1144.                        
  1145.                     }else{
  1146.                         if(copy($pathImg$pathNew)){
  1147.                             $mediaObject $this->newImg($findProducts$pathProductsDir$pathNew);
  1148.                             // $findProducts->setMainMediaHover($mediaObject);
  1149.                             $entityManager->persist$findProducts );
  1150.                         } 
  1151.                     }
  1152.                         
  1153.                 }
  1154.                 $entityManager->flush();
  1155.                 $entityManager->clear();
  1156.                 $findProducts '';
  1157.                 // die;
  1158.             }
  1159.             
  1160.         }
  1161.         // print_r($nextPaths);
  1162.         die;
  1163.         
  1164.     }
  1165.     #[Route('/products/export-xml'name'export_xml')]
  1166.     public function exportXml(EntityManagerInterface $entityManagerRequest $request): Response
  1167.     {
  1168.         $_get $request->query->all();
  1169.         $categoryId = isset($_get['category']) && !empty($_get['category']) ? $_get['category'] : null;
  1170.         // echo '<pre>';
  1171.         // var_dump($categoryId);
  1172.         // die;
  1173.         $categories $entityManager->getRepository(Category::class)->findAll();
  1174.      
  1175.         $products $entityManager->getRepository(Products::class)->findAll();
  1176.         $xml = new \SimpleXMLElement('<yml_catalog/>');
  1177.         $xml->addAttribute('date'date('Y-m-d H:i'));
  1178.         $shop $xml->addChild('shop');
  1179.         $shop->addChild('name''2PR');
  1180.         $shop->addChild('company''2PR');
  1181.         $shop->addChild('url''https://felso.inneti.net/');
  1182.         $shop->addChild('phone''068-844-11-44');
  1183.         $shop->addChild('platform''Store');
  1184.         $shop->addChild('version''2.1.0.1');
  1185.         // $currencies = $shop->addChild('currencies');
  1186.         // $currencies->addChild('currency')->addAttribute('id', 'UAH')->addAttribute('rate', '1');
  1187.         // Додаємо категорії
  1188.         $categoriesXml $shop->addChild('categories');
  1189.         foreach ($categories as $category) {
  1190.             if($categoryId !== null AND !in_array($category->getId(), $categoryId)){
  1191.                 continue;
  1192.             }
  1193.             $categoryXml $categoriesXml->addChild('category'$category->getName());
  1194.             $categoryXml->addAttribute('id'$category->getId());
  1195.             if ($category->getParent()) {
  1196.                 $categoryXml->addAttribute('parentId'$category->getParent()->getId());
  1197.             }
  1198.         }
  1199.                 // Додаємо продукти
  1200.                 $offers $shop->addChild('offers');
  1201.                 foreach ($products as $product) {
  1202.                     if($categoryId !== null){
  1203.                         $search false;
  1204.                         foreach($product->getCategory() as $cat){
  1205.                             if( in_array($cat->getId() , $categoryId) )
  1206.                                 $search true;
  1207.                         }
  1208.                         if(!$search)
  1209.                             continue;
  1210.                     }
  1211.                     $cat '';
  1212.                     if($product->getCategory() != null AND count($product->getCategory()) > 0)
  1213.                         $cat =  $product->getCategory()[0]->getId();
  1214.                     $img '';
  1215.                     if($product->getMainMedia() != null){
  1216.                         
  1217.                             // Отримуємо рік і місяць із дати завантаження
  1218.                             $uploadDate $product->getMainMedia()->getUploadTimestamp();
  1219.                             $year $uploadDate->format('Y');
  1220.                             $month $uploadDate->format('m');
  1221.                         
  1222.                             // Формуємо повний шлях до зображення
  1223.                             $img 'https://api-felso-brand.inneti.net/media/' $year '/' $month '/' $product->getMainMedia()->filePath;
  1224.                         
  1225.                     }
  1226.                         // $img = 
  1227.                     $offer $offers->addChild('offer');
  1228.                     $offer->addAttribute('id'$product->getId());
  1229.                     $offer->addAttribute('available'$product->isShow() ? 'true' 'false');
  1230.                     $offer->addChild('url''https://felso.inneti.net/product/' $product->getId());
  1231.                     $offer->addChild('price'$product->getPrice());
  1232.                     $offer->addChild('currencyId''UAH');
  1233.                     $offer->addChild('categoryId',  $cat );
  1234.                     $offer->addChild('picture'$img);
  1235.                     // $offer->addChild('vendor', $product->getVendor());
  1236.                     $offer->addChild('vendorCode'$product->getArticle());
  1237.                     $offer->addChild('name'$product->getName());
  1238.                     $offer->addChild('description'htmlspecialchars($product->getDescription()));
  1239.                 }
  1240.         
  1241.                 // Конвертація у XML
  1242.                 $response = new Response($xml->asXML());
  1243.                 $response->headers->set('Content-Type''application/xml');
  1244.         
  1245.                 return $response;
  1246.     }
  1247. }