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