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 =  ( isset( $_query['category'] ) ) ? $_query['category']: [];
  399.        
  400.         if($show)
  401.             $products $entityManager->getRepository(Products::class)->findBy(['show' => true]);
  402.         else
  403.             $products $entityManager->getRepository(Products::class)->findBy();
  404.         $optionGroup $entityManager->getRepository(Options::class)->findOneBy(['option_key' => 'show_price_group']);
  405.         if($optionGroup){
  406.             if(!empty($optionGroup->getValue())){
  407.                 $group explode(','$optionGroup->getValue());
  408.             }
  409.         }
  410.         // if(!empty( $category_id)){
  411.         //     $query = $entityManager->getRepository(Category::class)->find($category_id);
  412.         //     $categories[] = $query;
  413.         // }else{
  414.         $categories $entityManager->getRepository(Category::class)->findBy([], ['sort' => 'ASC']);
  415.         // }
  416.         $catArr = [];
  417.         foreach($categories as $cat){
  418.             if( !empty($category) ){
  419.                 if(in_array$cat->getId(), $category) ){
  420.                     $catArr[$cat->getId()] = [
  421.                         'name' => $cat->getName(),
  422.                         'products' => []
  423.                     ];
  424.                 }
  425.             }else{
  426.                 $catArr[$cat->getId()] = [
  427.                     'name' => $cat->getName(),
  428.                     'products' => []
  429.                 ];
  430.             }
  431.                 
  432.         }
  433.         foreach($products as $prod){
  434.             foreach($prod->getCategory() as $prodCat){
  435.                 if(isset($catArr[$prodCat->getId()]))
  436.                     $catArr[$prodCat->getId()]['products'][] = $prod;
  437.             }
  438.         }
  439.         $spreadsheet = new Spreadsheet();
  440.         // Get active sheet - it is also possible to retrieve a specific sheet
  441.         $sheet $spreadsheet->getActiveSheet();
  442.     
  443.         // Set cell name and merge cells
  444.         // $sheet->setCellValue('A1', 'Крамар ціни');
  445.         $sheet->getRowDimension(1)->setRowHeight(90);
  446.         $sheet->getColumnDimension('A')->setWidth(50);
  447.         $sheet->getColumnDimension('B')->setWidth(10);
  448.         $sheet->getColumnDimension('C')->setWidth(30);
  449.         $sheet->getColumnDimension('D')->setWidth(30);
  450.         $sheet->getColumnDimension('E')->setWidth(30);
  451.         $sheet->getColumnDimension('F')->setWidth(30);
  452.         $sheet->getColumnDimension('G')->setWidth(50);
  453.         $sheet->getColumnDimension('H')->setWidth(60);
  454.         $sheet->getColumnDimension('I')->setWidth(60);
  455.         // Set cell alignment and font weight
  456.         $styleArray = [
  457.             'alignment' => [
  458.                 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
  459.                 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
  460.             ],
  461.             'font' => [
  462.                 'bold' => true,
  463.             ],
  464.         ];
  465.         $sheet->getStyle('B1')->applyFromArray($styleArray)->getAlignment()->setWrapText(true);
  466.         $sheet->getStyle('C1')->applyFromArray($styleArray)->getAlignment()->setWrapText(true);
  467.         $sheet->getStyle('A:A')->applyFromArray($styleArray)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  468.         $sheet->mergeCells('A1:B1');
  469.         // Add image to worksheet
  470.         $imgPath 'logo.png';
  471.         $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
  472.         $drawing->setPath($imgPath);
  473.         $drawing->setCoordinates('A1'); // Set coordinates
  474.         $drawing->setWidth(200); // Set width
  475.         $drawing->setHeight(100); // Set height
  476.         $drawing->setWorksheet($sheet);
  477.         
  478.         $sheet->setCellValue('C1'$domen_front);
  479.         // $sheet->setCellValue('C1', '');
  480.         
  481.         $sheet->mergeCells('A2:G2');
  482.         $sheet->mergeCells('A3:G3');
  483.         $sheet->setCellValue('A2''Адреса компанії: м.Львів, вул.Манастирського 2 ');
  484.         // $sheet->setCellValue('A3', 'Номер телефону   +38 (068) 844-11-44 +38 (073) 844-11-44');
  485.         // $sheet->setCellValue('D3', 'При замовленні від 0 до 100 кг. однієї позиції')->getStyle('D3')->applyFromArray($styleArray)->getAlignment()->setWrapText(true);
  486.         // $sheet->setCellValue('E3', 'При замовленні від 100 до 500 кг. однієї позиції')->getStyle('E3')->applyFromArray($styleArray)->getAlignment()->setWrapText(true);
  487.         // $sheet->setCellValue('F3', 'При замовленні від 500 до 1 тонни однієї позиції')->getStyle('F3')->applyFromArray($styleArray)->getAlignment()->setWrapText(true);
  488.         // $sheet->setCellValue('G3', 'При замовленні від 1 тонни')->getStyle('G3')->applyFromArray($styleArray)->getAlignment()->setWrapText(true);
  489.     
  490.         // Set column names
  491.         $columnNames = [
  492.             'Назва',
  493.             'Артикул',
  494.             '',
  495.             'Ціна РРЦ в ₴',
  496.             'Ціна для диллера в ₴',
  497.             'Ціна для диллера в $',
  498.             'характеристики',
  499.             'комплектація',
  500.             'Посилання',
  501.             // 'Гурт 2',
  502.             // 'Гурт 1',
  503.             // 'VIP',
  504.         ];
  505.         $columnLetter 'A';
  506.         foreach ($columnNames as $key =>$columnName) {
  507.             // Allow to access AA column if needed and more
  508.             $sheet->setCellValue("{$columnLetter}4"$columnName)->getStyle($key)->applyFromArray($styleArray);
  509.             $columnLetter++;
  510.         }
  511.         $row 9;
  512.         foreach($catArr as $key => $category){
  513.             $sheet->setCellValue("A{$row}"$category['name'])->mergeCells("A{$row}:G{$row}");
  514.             $sheet->getStyle("A{$row}")->applyFromArray($styleArray);
  515.             $row++;
  516.             if(count($category['products']) > 0)
  517.                 foreach ($category['products'] as $product) {
  518.                     if($product->isDeleted())
  519.                         continue;
  520.                     /** Характеристики */
  521.                     $params '';
  522.                     foreach($product->getAttributeItems() as $attributeItems){
  523.                         $params .= $attributeItems->getAttribute()->getName() . ' - ' $attributeItems->getName() . "\n";
  524.                     }
  525.                     /** Комплектація */
  526.                     $productComplact '';
  527.                     foreach($product->getProductInfos() as $productInfos){
  528.                         $productComplact .= $productInfos->getName() . "\n";
  529.                     }
  530.                     $columnLetter++;
  531.                     
  532.                     $sheet->getRowDimension($row)->setRowHeight(100*0.75); // переведення 100px в пункти
  533.                     $sheet->setCellValue('A'.$row$product->getName());
  534.                     $sheet->getStyle('A' $row)->getAlignment()->setWrapText(true);
  535.                     $sheet->setCellValue('B'.$row$product->getArticle());
  536.                     $sheet->getStyle('B' $row)->getAlignment()->setWrapText(true); // Вмикає перенесення тексту
  537.                     // $sheet->setCellValue('C'.$row, $product->getPrice());
  538.                     $sheet->setCellValue('D'.$row$product->getPrice());
  539.                     $sheet->setCellValue('E'.$rowround$product->getPrice() * 0.75 1));
  540.                     $sheet->setCellValue('F'.$rowround( ($product->getPrice() * 0.75) /  $currency 1));
  541.                     /** Характеристики */
  542.                     $sheet->setCellValue('G'.$rowstrip_tags($params) );
  543.                     $sheet->getStyle('G' $row)->getAlignment()->setWrapText(true); // Вмикає перенесення тексту
  544.                     
  545.                     $sheet->setCellValue('H'.$row$productComplact);
  546.                     $sheet->getStyle('H' $row)->getAlignment()->setWrapText(true); // Вмикає перенесення тексту
  547.                     $sheet->setCellValue('I'.$row$domen_front '/product/' $product->getId());
  548.                     // $sheet->getStyle('C' . $row)->getAlignment()->setWrapText(true); // Вмикає перенесення тексту
  549.                     // $sheet->getRowDimension($row)->setRowHeight(-1); // Автоматична висота рядка
  550.                     if($product->getMainMedia() != null){
  551.                         
  552.                         // Отримуємо рік і місяць із дати завантаження
  553.                         $uploadDate $product->getMainMedia()->getUploadTimestamp();
  554.                         $year $uploadDate->format('Y');
  555.                         $month $uploadDate->format('m');
  556.                     
  557.                         // Формуємо повний шлях до зображення
  558.                         $imgPath $_SERVER["DOCUMENT_ROOT"] . '/media/' $year '/' $month '/90_px_' $product->getMainMedia()->filePath;
  559.                         if(file_exists($imgPath)){
  560.                         // $ = 'logo.png';
  561.                             $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
  562.                             $drawing->setPath($imgPath);
  563.                             $drawing->setCoordinates('C'.$row); // Set coordinates
  564.                             $drawing->setWidth(150); // Set width
  565.                             $drawing->setHeight(100); // Set height
  566.                             $drawing->setWorksheet($sheet);
  567.                         }
  568.                     
  569.                     }
  570.                     $row++;
  571.                 }
  572.         }
  573.         
  574.         $writer = new Xlsx($spreadsheet);
  575.         $fileName 'products_' date('YmdHis') . '.xlsx';
  576.         $writer->save($fileName);
  577.         // Вивантаження файлу
  578.         // Set the content-type:
  579.         header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  580.         header('Content-Length: ' filesize($fileName));
  581.         readfile($fileName); // send file
  582.         unlink($fileName); // delete file
  583.         return new Response();
  584.     }
  585.     #[Route(
  586.         name'addAttrCategory'
  587.         path'/add-attr-category',
  588.     )]
  589.     public function addAttrCategoryEntityManagerInterface $entityManager ){
  590.         $products $entityManager->getRepository(Products::class)->findBy(['show' => true]);
  591.         foreach( $products as $product ){
  592.             if(count($product->getAttributeItems())  > ){
  593.                 foreach($product->getAttributeItems() as $attrItem){
  594.                     $attibute $attrItem->getAttribute();
  595.                     foreach($product->getCategory() as $category){
  596.                         $attrItem->addCategory($category);
  597.                         $attibute->addCategory($category);
  598.                         $entityManager->persist($attrItem);
  599.                         $entityManager->persist($attibute);
  600.                     }
  601.                 }
  602.             }
  603.             
  604.         }
  605.         $entityManager->flush();
  606.         echo 1111;
  607.         die;
  608.     }   
  609.     #[Route(
  610.         name'get_wp_product_img'
  611.         path'/wp-get-product-img',
  612.         methods: ['GET'],
  613.     )]
  614.     public function get_wp_product_img(Request $request): Response
  615.     {
  616.         $prod =  json_decodefile_get_contents('https://kramar-shop.com/importAsd.php?img=1') );
  617.         // echo '<pre>';
  618.         // print_r($prod);
  619.         // die;
  620.         foreach($prod as $p){
  621.             $find $this->entityManager->getRepository(Products::class)->findOneBy(['code1c' => "WP-{$p->product_id}"]);
  622.             if( !is_null$find ) ){
  623.            
  624.                 // URL, куди ви хочете відправити дані
  625.                 $url 'https://api.kramar-shop.com/api/media_objects?product=' .  $find->getId();
  626.                 // echo " $url<br><br>";
  627.                 // Файл, який ви хочете відправити
  628.                 $file_path $p->url;
  629.                 // Ініціалізуємо cURL-сесію
  630.                 $ch curl_init();
  631.                 // Встановлюємо параметри запиту
  632.                 curl_setopt($chCURLOPT_URL$url);
  633.                 curl_setopt($chCURLOPT_POST1);
  634.                 curl_setopt($chCURLOPT_POSTFIELDS, [
  635.                     'file' => new \CURLFile($file_path)
  636.                 ]);
  637.                 // Виконуємо запит
  638.                 $response curl_exec($ch);
  639.                 // $json = json_decode($response);
  640.                 // Перевіряємо наявність помилок
  641.                 if (curl_errno($ch)) {
  642.                     echo 'Error:' curl_error($ch);
  643.                 }
  644.                 // Закриваємо cURL-сесію
  645.                 curl_close($ch);
  646.                 // Виводимо відповідь сервера
  647.             //     echo $response;
  648.             //     // echo '<pre>111';
  649.             //    var_dump($json);
  650.             }
  651.             // die;
  652.         }
  653.         // $prod =  json_decode( file_get_contents('https://kramar-shop.com/wp-api.php') );
  654.         // // echo '<pre>';
  655.         // // print_r($prod);die;
  656.         // $measurmentUnitObjs = $this->entityManager->getRepository(MeasurmentUnit::class)->findAll();
  657.         // $measurmentUnit= [];
  658.         // foreach($measurmentUnitObjs as $mu){
  659.         //     if($mu->getShortName() == 'пак.')
  660.         //         $measurmentUnit['уп.'] = $mu;
  661.         //     else
  662.         //         $measurmentUnit[$mu->getShortName()] = $mu;
  663.         // }
  664.         // foreach($prod as $p){
  665.            
  666.         //     $find = $this->entityManager->getRepository(Products::class)->findOneBy(['code1c' => "WP-{$p->id}"]);
  667.             
  668.         //     if(is_null( $find )){
  669.         //         $product = new Products();
  670.         //         $product->setName($p->name);
  671.         //         $product->setDescription($p->description);
  672.         //         $product->setMeasurementUnit( $measurmentUnit[$p->custom_weight]);
  673.         //         $product->setShow( ($p->custom_weight == 'publish')? true: false);
  674.         //         $product->setCode1c("WP-{$p->id}");
  675.         //         $product->setPrice($p->price);
  676.         //         $this->entityManager->persist($product);
  677.         //     }else{
  678.         //         $find->setPrice($p->price);
  679.         //         $this->entityManager->persist($find);
  680.                 
  681.         //     }
  682.         //     $this->entityManager->flush();
  683.         // }
  684.         die;
  685.     }
  686.     #[Route(
  687.         name'getDublicate'
  688.         path'/get-dublicate',
  689.     )]
  690.     public function getDublicateEntityManagerInterface $entityManagerRequest $request): Response
  691.     {
  692.         set_time_limit(0);
  693.         $duplicates $entityManager->createQueryBuilder()
  694.         ->select('p.article')
  695.         ->from(Products::class, 'p')
  696.         ->where('p.deleted = FALSE')
  697.         ->groupBy('p.article')
  698.         ->having('COUNT(p.article) > 1')
  699.         ->getQuery()
  700.         ->getResult();
  701.         $i  0;
  702.         foreach ($duplicates as $duplicate) {
  703.             // echo $duplicate['article'] . "<br>";
  704.             $products $entityManager->getRepository(Products::class)
  705.                 ->findBy(['article' => $duplicate['article'], 'deleted' => false]);
  706.             
  707.             // Keep the first product and remove the rest
  708.             $deleted true;
  709.             $isDeleted false;
  710.             foreach ($products as $product) {
  711.                 echo $product->getArticle();
  712.                 if(count($product->getOrderProducts()) > 0){
  713.                     $deleted false;
  714.                     echo ' - - false';
  715.                 }elseif(count$product->getCategory()) > OR count$product->getAttributeItems()) > 0){
  716.                     $deleted false;
  717.                     echo '- false';
  718.                 }else{
  719.                     $deleted true;
  720.                     echo ' - true';
  721.                 }
  722.                 if($deleted AND !$isDeleted){
  723.                     $i++;
  724.                     $isDeleted true;
  725.                     $product->setDeleted(true);
  726.                     $product->setDescription('delete dublicate product ' date('Y-m-d H:i:s'));
  727.                     $entityManager->persist$product );
  728.                 }
  729.                 
  730.                 
  731.                 echo '<br>';
  732.             }
  733.             if($i === 200){
  734.                 $entityManager->flush();
  735.                 $i=0;
  736.             }
  737.         }
  738.         $entityManager->flush();
  739.         die;
  740.     }
  741.     #[Route(
  742.         name'importProductFromExcel'
  743.         path'/product/import-from-excel',
  744.     )]
  745.     function importProductFromExcel(EntityManagerInterface $entityManagerTranslit $translit){
  746.         echo '<pre>';
  747.         $inputFileName 'products.xlsx';
  748.         $spreadsheet IOFactory::load($inputFileName);
  749.         $sheet $spreadsheet->getActiveSheet();
  750.         $i 0;
  751.         $category = [];
  752.         $attributes = [];
  753.         $products = [];  
  754.         // $url = $sheet->getDrawingCollection();
  755.         // $sheet->getCell('C1')->getValue()
  756.         // echo '<pre>';
  757.         // print_r($url);
  758.         // var_dump($url); die;
  759.         // die;
  760.         foreach ($sheet->getRowIterator() as $row) {
  761.             $cellIterator $row->getCellIterator();
  762.             $cellIterator->setIterateOnlyExistingCells(FALSE);
  763.             $data = [];
  764.             foreach ($cellIterator as $cell) {
  765.             //     echo '<pre>';   
  766.             // print_r($cell->getWorksheet()->getDrawingCollection());
  767.                 $value $cell->getValue();
  768.                 // $drawing = $cell->getWorksheet()->getDrawingCollection();
  769.                 // $hyperlink = $cell->getHyperlink();
  770.                 // if ($hyperlink) {
  771.                 //     $value = $hyperlink->getUrl();
  772.                 // }
  773.                 $data[] = $value;
  774.             }
  775.             // Assuming your Excel file has columns: id, name, price
  776.             // echo '<pre>';
  777.             if($i==0){
  778.                 foreach($data as $k => $d){
  779.                     if($k >= AND !empty($d)){
  780.                         $n str_replace(':'''$d);
  781.                         $attributes[$k] = [
  782.                             'name' => trim($n),
  783.                             'slug' => $translit->convert(trim($n)),
  784.                             'items' => []
  785.                         ];
  786.                     }
  787.                 }
  788.                 // print_r($data);
  789.                 $i++;
  790.                 continue;
  791.             }
  792.             
  793.             foreach($data as $k => $d){
  794.                 if($k >= AND !empty($d)){
  795.                     $attributes[$k]['items'][$translit->convert(trim($d))] = trim($d);
  796.                 }
  797.             }
  798.             if(!empty($data[3]))
  799.                 $category$translit->convert(trim$data[4] )) ] = trim$data[4] );
  800.       
  801.             $products[$i]['data'] = $data;
  802.            
  803.             $i++;
  804.         }
  805.         // print_r($category);
  806.         // print_r($attributes);
  807.         // die;
  808.         // die;
  809.         $findCategory $entityManager->getRepository(Category::class)->findAll();
  810.         $findAttributes $entityManager->getRepository(Attributes::class)->findAll();
  811.         foreach($category as $slug =>  $c){
  812.             $find false;
  813.             foreach($findCategory as $fCat){
  814.                 if($fCat->getName() == $c){
  815.                     $find true;
  816.                 }
  817.             }
  818.             if(!$find){
  819.                 $entityCat = new Category();
  820.                 $entityCat->setName($c);
  821.                 $entityCat->setSlug($slug);
  822.                 $entityCat->setMain(true);
  823.                 $entityCat->setType('category');
  824.                 $entityManager->persist$entityCat );
  825.                 
  826.             }
  827.         }
  828.         // echo '<pre>';
  829.         // print_r($attributes); die;
  830.         foreach($attributes as $name => $attrs){
  831.             $attr false;
  832.             $entityAttr '';
  833.             foreach($findAttributes as $fAttr){
  834.                 if($fAttr->getName() == $attrs['name']){
  835.                     $entityAttr $fAttr;
  836.                     $attr true;
  837.                     foreach($attrs['items'] as $i => $a){
  838.                         foreach($fAttr->getAttributeItems() as $f_a_i){
  839.                             if($f_a_i->getName() == $a){
  840.                                 unset($attrs['items'][$i]);
  841.                             }
  842.                         }
  843.                     }
  844.                 }
  845.             }
  846.              
  847.             if(!$attr){
  848.                 $entityAttr = new Attributes();
  849.                 $entityAttr->setName($attrs['name']);
  850.                 $entityAttr->setSlug($attrs['slug']);
  851.                 $entityManager->persist$entityAttr );
  852.             }
  853.             if(count($attrs['items']) > 0){
  854.                 foreach($attrs['items'] as $i => $a){
  855.                     $entityAttrItem = new AttributeItems();
  856.                     $entityAttrItem->setName($a);
  857.                     $entityAttrItem->setSlug($i);
  858.                     $entityAttrItem->setAttribute($entityAttr);
  859.                     $entityManager->persist$entityAttrItem );
  860.                 }
  861.             }
  862.             
  863.         }
  864.         // die;
  865.         $entityManager->flush();
  866.         // die;
  867.         $findCategory $entityManager->getRepository(Category::class)->findAll();
  868.         $findAttributes $entityManager->getRepository(Attributes::class)->findAll();
  869.         $findAttributesItems $entityManager->getRepository(AttributeItems::class)->findAll();
  870.         $findProducts $entityManager->getRepository(Products::class)->findAll();
  871.         $measurmentUnit $entityManager->getRepository(MeasurmentUnit::class)->findOneBy(['name' => 'Штука']);
  872.         // print_r($products); die;    
  873.         foreach($products as $product){
  874.             $search false;
  875.             $findProduct '';
  876.             foreach($findProducts  as $f_p){
  877.                 if($f_p->getArticle() == $product['data'][1]){
  878.                     $search true;
  879.                     $findProduct $f_p;
  880.                 }
  881.             }
  882.             $price floatval(trim(str_replace('грн''' $product['data'][2])));
  883.             if(!$search and !empty($product['data'][0])){
  884.                 $newProduct = new Products();
  885.                 $newProduct->setName($product['data'][0]);
  886.                 $newProduct->setArticle($product['data'][1]);
  887.                 $newProduct->setPrice($price);
  888.                 $newProduct->setShow(true);
  889.                 $findProduct->setBalance(1);
  890.                 // $newProduct->setPackingType($product['data'][7] . ' | ' . $product['data'][7]);
  891.                 $newProduct->getMeasurementUnit($measurmentUnit);
  892.                 foreach($product['data'] as $k => $d){
  893.                     if($k >= AND !empty($d)){
  894.                         foreach($findAttributesItems as $ati){
  895.                             if($ati->getName() == trim($d)){
  896.                                 $newProduct->addAttributeItem($ati);
  897.                             }
  898.                         }
  899.                     }
  900.                     if($k == AND !empty($d)){
  901.                         foreach ($findCategory as $f_c){
  902.                             if($f_c->getName() == trim($d)){
  903.                                 $newProduct->addCategory($f_c);
  904.                             }
  905.                         }
  906.                     }
  907.                 }
  908.                 $entityManager->persist$newProduct );
  909.             }else{
  910.                 echo $findProduct->getName() . "<br>";
  911.                 $findProduct->setPrice($price);
  912.                 $findProduct->setShow(true);
  913.                 $findProduct->setBalance(1);
  914.                 foreach($product['data'] as $k => $d){
  915.                     $searvhAttr false;
  916.                     if($k >= AND !empty($d)){
  917.                         foreach( $findProduct->getAttributeItems() as $productAttrItem){
  918.                             if( $productAttrItem->getName() ==  $d){
  919.                                 $searvhAttr true;
  920.                             }
  921.                         }
  922.                         if(!$searvhAttr){
  923.                             foreach($findAttributesItems as $ati){
  924.                                 if($ati->getName() == trim($d)){
  925.                                     $findProduct->addAttributeItem($ati);
  926.                                 }
  927.                             }
  928.                             $entityManager->persist$findProduct );
  929.                         }
  930.                     }
  931.                 }
  932.                 // if(empty( $findProduct->getCategory() )){
  933.                     foreach($product['data'] as $k => $d){
  934.                         if($k == AND !empty($d)){
  935.                             foreach ($findCategory as $f_c){
  936.                                 if($f_c->getName() == trim($d)){
  937.                                     echo  $f_c->getName(). "<br>";
  938.                                     $findProduct->addCategory($f_c);
  939.                                 }
  940.                             }
  941.                         }
  942.                     }
  943.                 // }
  944.                 
  945.                 $entityManager->persist$findProduct );
  946.                 
  947.             }
  948.         }
  949.         $entityManager->flush();
  950.         // $findProducts = $entityManager->getRepository(Products::class)->findAll();
  951.         // foreach ($sheet->getDrawingCollection() as $in =>  $drawing) {
  952.         //         // print_r($drawing->getCoordinates());
  953.         //         $c = str_replace('E', '', $drawing->getCoordinates() );
  954.         //         // print_r($sheet->getCell( "B$c" )->getValue());
  955.         //         // echo "<br>";
  956.         //         foreach($findProducts  as $f_p){
  957.         //             if($f_p->getArticle() == $sheet->getCell( "B$c" )->getValue()){
  958.         //                 $zipReader = fopen($drawing->getPath(),'r');
  959.         //                 $imageContents = '';
  960.         //                 while (!feof($zipReader)) {
  961.         //                     $imageContents .= fread($zipReader,1024);
  962.         //                 }
  963.         //                 fclose($zipReader);
  964.         //                 $extension = $drawing->getExtension();
  965.         //                 $imageBase64 = base64_encode($imageContents);
  966.         //                 $url = 'https://api-felso-brand.inneti.net/api/media_objects?product=' .  $f_p->getId();
  967.         //                 $imageFile = new \CURLFile($imageBase64, 'image/' . $extension, 'image.' . $extension);
  968.         //                 echo  $url; echo '<br>';
  969.         //                 // Set up the cURL request
  970.         //         // Ініціалізуємо cURL-сесію
  971.         //                 $ch = curl_init();
  972.         //                 // Встановлюємо параметри запиту
  973.         //                 curl_setopt($ch, CURLOPT_URL, $url);
  974.         //                 curl_setopt($ch, CURLOPT_POST, 1);
  975.         //                 curl_setopt($ch, CURLOPT_POSTFIELDS, ['image' => $imageFile]);
  976.         //                 // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  977.         //                 // Execute the cURL request
  978.         //               // Виконуємо запит
  979.         //                 $response = curl_exec($ch);
  980.         //                 // $json = json_decode($response);
  981.         //                 // Перевіряємо наявність помилок
  982.         //                 if (curl_errno($ch)) {
  983.         //                     echo 'Error:' . curl_error($ch);
  984.         //                 }
  985.         //                 // Закриваємо cURL-сесію
  986.         //                 curl_close($ch);
  987.         //                 die;
  988.             
  989.         //             }
  990.         //         }
  991.        
  992.             
  993.         //         // $zipReader = fopen($drawing->getPath(),'r');
  994.         //         // $imageContents = '';
  995.         
  996.         //         // while (!feof($zipReader)) {
  997.         //         //     $imageContents .= fread($zipReader,1024);
  998.         //         // }
  999.         //         // fclose($zipReader);
  1000.         //         // $extension = $drawing->getExtension();
  1001.         //         // $imageBase64 = base64_encode($imageContents);
  1002.         //         // $url = 'https://api-felso-brand.inneti.net/api/media_objects?product=' .  $entity->getId();
  1003.         //         // $imageFile = new CURLFile($imageBase64, 'image/' . $extension, 'image.' . $extension);
  1004.         //         // // Set up the cURL request
  1005.         //         // $ch = curl_init();
  1006.         //         // curl_setopt($ch, CURLOPT_URL, $url);
  1007.         //         // curl_setopt($ch, CURLOPT_POST, 1);
  1008.         //         // curl_setopt($ch, CURLOPT_POSTFIELDS, ['image' => $imageFile]);
  1009.         //         // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  1010.             
  1011.         //         // // Execute the cURL request
  1012.         //         // $response = curl_exec($ch);
  1013.             
  1014.         //         // // Close cURL resource
  1015.         //         // curl_close($ch);
  1016.             
  1017.         //     // }
  1018.         //     // $myFileName = '00_Image_'.++$i.'.'.$extension;
  1019.         //     // file_put_contents($myFileName,$imageContents);
  1020.         // }
  1021.         // $entityManager->flush();
  1022.             echo 111;
  1023.         die;
  1024.         // return $this->redirectToRoute('app_homepage');
  1025.     }
  1026.     public function imgCurl($entity$imgUrl$type='img'){
  1027.                 // continue;
  1028.                 // $img = file_get_contents($imgUrl);
  1029.                 $url 'https://api-felso.inneti.net/api/media_objects';
  1030.                 if( $type == 'img' )
  1031.                     $url .= '?product=' .  $entity->getId();
  1032.                 // echo " $url<br><br>";
  1033.                 // Файл, який ви хочете відправити
  1034.                 $file_path $imgUrl;
  1035.                 // Ініціалізуємо cURL-сесію
  1036.                 $ch curl_init();
  1037.                 // Встановлюємо параметри запиту
  1038.                 curl_setopt($chCURLOPT_URL$url);
  1039.                 curl_setopt($chCURLOPT_POST1);
  1040.                 curl_setopt($chCURLOPT_POSTFIELDS, [
  1041.                     'file' => new \CURLFile($file_path)
  1042.                 ]); 
  1043.                 echo '----';
  1044.                 // Виконуємо запит
  1045.                 $response curl_exec($ch);
  1046.                 echo '|||';
  1047.                 // $json = json_decode($response);
  1048.                 // Перевіряємо наявність помилок
  1049.                 if (curl_errno($ch)) {
  1050.                     echo '2Error:' curl_error($ch); die;
  1051.                 }
  1052.                 // Закриваємо cURL-сесію
  1053.                 curl_close($ch);
  1054.                 return $response;
  1055.     }
  1056.     public function newImg($findProducts,  $pathProductsDir$pathNew, ){
  1057.         echo $findProducts->getName() . "+++<br>"
  1058.         $uploadTimestamp = new  \DateTime();
  1059.         $mediaObject = new MediaObject();
  1060.         // $mediaObject->file = $uploadedFile;
  1061.         $mediaObject->uploadTimestamp $uploadTimestamp;
  1062.         $mediaObject->filePath $findProducts->getId().$pathProductsDir;
  1063.         $mediaObject->setName('product_img');
  1064.         $mediaObject->setProduct($findProducts);
  1065.         $this->entityManager->persist$mediaObject );
  1066.         $this->entityManager->flush();
  1067.         $year date('Y');
  1068.         $month date('m');
  1069.         $documentRoot $this->kernel->getProjectDir() . '/public/media';
  1070.         $path $documentRoot "/$year/$month/";
  1071.         $sizes = [902307001200];
  1072.         $manager = new ImageManager(
  1073.             new \Intervention\Image\Drivers\Gd\Driver() 
  1074.         );
  1075.         foreach($sizes as $s){
  1076.             $image $manager->read($pathNew);
  1077.             $image->scale(width$s);
  1078.             $newName "{$s}_px_" .  $findProducts->getId().$pathProductsDir;
  1079.             $image->save($path $newName );
  1080.             $newMedia = new MediaObject();
  1081.             $newMedia->filePath $newName;
  1082.             $newMedia->setName("resize-$s");
  1083.             $newMedia->setSize($s);
  1084.             $newMedia->setResizeImgParent($mediaObject);
  1085.             $this->entityManager->persist($newMedia);
  1086.             $this->entityManager->flush();
  1087.         
  1088.         }
  1089.         $findProducts null;
  1090.         return $mediaObject;
  1091.     }
  1092.     #[Route(
  1093.         name'importProductImg'
  1094.         path'/product/import-img',
  1095.     )]
  1096.     function importProductImg(EntityManagerInterface $entityManagerTranslit $translitMediaObjectsRepository $mediaObjectsRepository, ?\DateTimeInterface $uploadTimestamp){
  1097.         echo '<pre>';
  1098.         $path 'products_img';
  1099.         $nextPaths scandir($path);
  1100.         print_r($nextPaths);
  1101.         foreach($nextPaths as $nextPath){
  1102.             if($nextPath == '.' OR $nextPath == '..')
  1103.                 continue;
  1104.             $pathCat "$path/$nextPath";
  1105.             $pathCatDirs scandir($pathCat);
  1106.             
  1107.             foreach($pathCatDirs as $pathCatDir){
  1108.                 if($pathCatDir == '.' OR $pathCatDir == '..')
  1109.                     continue;
  1110.                 // if($pathCatDir == 'ID1250')
  1111.                 //     die;
  1112.                 // print_r($pathCatDir); die;
  1113.                 file_put_contents('import-img.log'$pathCatDir "\n"FILE_APPEND);
  1114.                 $pathProducts "$pathCat/$pathCatDir";
  1115.                 $pathProductsDirs scandir($pathProducts);
  1116.                 echo "<b>$pathCatDir</b><br>";
  1117.                 $findProducts $entityManager->getRepository(Products::class)->findOneBy(['article' => $pathCatDir]);
  1118.                 
  1119.                 if($findProducts ){
  1120.                     echo "<b>" $findProducts->getName() . "</b><br>";
  1121.                     foreach($findProducts->getMedia() as $m){
  1122.                         echo $m->getId() . "<br>";
  1123.                         $findProducts->removeMedium($m);
  1124.                     }
  1125.                     $mainMedia $findProducts->getMainMedia();
  1126.                     if($mainMedia){
  1127.                         echo "main - " $mainMedia->getId() . "<br>";
  1128.                         $mainMedia->removeMainProduct($findProducts);
  1129.                         $entityManager->persist$findProducts );
  1130.                     }
  1131.                     $MainMediaHover $findProducts->getMainMediaHover();
  1132.                     if($MainMediaHover){
  1133.                         echo "hover - main - " $MainMediaHover->getId() . "<br>";
  1134.                         $MainMediaHover->removeProductsHover($findProducts);
  1135.                         $entityManager->persist$MainMediaHover );
  1136.                     }
  1137.                     $entityManager->persist$findProducts );
  1138.                     $entityManager->flush();
  1139.                    
  1140.                 }else{
  1141.                     continue;
  1142.                 }
  1143.                 // echo $findProducts->getName();
  1144.                 echo "<br>";
  1145.                 foreach($pathProductsDirs as $pathProductsDir){
  1146.                     if($pathProductsDir == '.' OR $pathProductsDir == '..')
  1147.                         continue;
  1148.                     $pathImg =  $this->kernel->getProjectDir() . "/public/$pathProducts/$pathProductsDir";
  1149.                     $pathNew $this->kernel->getProjectDir() . "/public/media/" date('Y') . "/" date('m') . "/".$findProducts->getId()."$pathProductsDir";
  1150.                     echo $pathImg "---<br>";
  1151.                     echo $pathNew "---<br>";
  1152.                     
  1153.                     if($pathProductsDir == '1_0.png'){
  1154.                         if(copy($pathImg$pathNew)){
  1155.                             $mediaObject $this->newImg($findProducts$pathProductsDir$pathNew);
  1156.                             $findProducts->setMainMedia($mediaObject);
  1157.                             $entityManager->persist$findProducts );
  1158.                            
  1159.                         }
  1160.                     }elseif($pathProductsDir == '1_1.png'){
  1161.                         if(copy($pathImg$pathNew)){
  1162.                             $mediaObject $this->newImg($findProducts$pathProductsDir$pathNew);
  1163.                             $findProducts->setMainMediaHover($mediaObject);
  1164.                             $entityManager->persist$findProducts );
  1165.                         }
  1166.                        
  1167.                     }else{
  1168.                         if(copy($pathImg$pathNew)){
  1169.                             $mediaObject $this->newImg($findProducts$pathProductsDir$pathNew);
  1170.                             // $findProducts->setMainMediaHover($mediaObject);
  1171.                             $entityManager->persist$findProducts );
  1172.                         } 
  1173.                     }
  1174.                         
  1175.                 }
  1176.                 $entityManager->flush();
  1177.                 $entityManager->clear();
  1178.                 $findProducts '';
  1179.                 // die;
  1180.             }
  1181.             
  1182.         }
  1183.         // print_r($nextPaths);
  1184.         die;
  1185.         
  1186.     }
  1187.     #[Route('/products/export-xml'name'export_xml')]
  1188.     public function exportXml(EntityManagerInterface $entityManagerRequest $request): Response
  1189.     {
  1190.         $_get $request->query->all();
  1191.         $categoryId = isset($_get['category']) && !empty($_get['category']) ? $_get['category'] : null;
  1192.         // echo '<pre>';
  1193.         // var_dump($categoryId);
  1194.         // die;
  1195.         $categories $entityManager->getRepository(Category::class)->findAll();
  1196.      
  1197.         $products $entityManager->getRepository(Products::class)->findAll();
  1198.         $xml = new \SimpleXMLElement('<yml_catalog/>');
  1199.         $xml->addAttribute('date'date('Y-m-d H:i'));
  1200.         $shop $xml->addChild('shop');
  1201.         $shop->addChild('name''2PR');
  1202.         $shop->addChild('company''2PR');
  1203.         $shop->addChild('url''https://felso.inneti.net/');
  1204.         $shop->addChild('phone''068-844-11-44');
  1205.         $shop->addChild('platform''Store');
  1206.         $shop->addChild('version''2.1.0.1');
  1207.         // $currencies = $shop->addChild('currencies');
  1208.         // $currencies->addChild('currency')->addAttribute('id', 'UAH')->addAttribute('rate', '1');
  1209.         // Додаємо категорії
  1210.         $categoriesXml $shop->addChild('categories');
  1211.         foreach ($categories as $category) {
  1212.             if($categoryId !== null AND !in_array($category->getId(), $categoryId)){
  1213.                 continue;
  1214.             }
  1215.             $categoryXml $categoriesXml->addChild('category'$category->getName());
  1216.             $categoryXml->addAttribute('id'$category->getId());
  1217.             if ($category->getParent()) {
  1218.                 $categoryXml->addAttribute('parentId'$category->getParent()->getId());
  1219.             }
  1220.         }
  1221.                 // Додаємо продукти
  1222.                 $offers $shop->addChild('offers');
  1223.                 foreach ($products as $product) {
  1224.                     if($categoryId !== null){
  1225.                         $search false;
  1226.                         foreach($product->getCategory() as $cat){
  1227.                             if( in_array($cat->getId() , $categoryId) )
  1228.                                 $search true;
  1229.                         }
  1230.                         if(!$search)
  1231.                             continue;
  1232.                     }
  1233.                     $cat '';
  1234.                     if($product->getCategory() != null AND count($product->getCategory()) > 0)
  1235.                         $cat =  $product->getCategory()[0]->getId();
  1236.                     $img '';
  1237.                     if($product->getMainMedia() != null){
  1238.                         
  1239.                             // Отримуємо рік і місяць із дати завантаження
  1240.                             $uploadDate $product->getMainMedia()->getUploadTimestamp();
  1241.                             $year $uploadDate->format('Y');
  1242.                             $month $uploadDate->format('m');
  1243.                         
  1244.                             // Формуємо повний шлях до зображення
  1245.                             $img 'https://api-felso-brand.inneti.net/media/' $year '/' $month '/' $product->getMainMedia()->filePath;
  1246.                         
  1247.                     }
  1248.                         // $img = 
  1249.                     $offer $offers->addChild('offer');
  1250.                     $offer->addAttribute('id'$product->getId());
  1251.                     $offer->addAttribute('available'$product->isShow() ? 'true' 'false');
  1252.                     $offer->addChild('url''https://felso.inneti.net/product/' $product->getId());
  1253.                     $offer->addChild('price'$product->getPrice());
  1254.                     $offer->addChild('currencyId''UAH');
  1255.                     $offer->addChild('categoryId',  $cat );
  1256.                     $offer->addChild('picture'$img);
  1257.                     // $offer->addChild('vendor', $product->getVendor());
  1258.                     $offer->addChild('vendorCode'$product->getArticle());
  1259.                     $offer->addChild('name'$product->getName());
  1260.                     $offer->addChild('description'htmlspecialchars($product->getDescription()));
  1261.                 }
  1262.         
  1263.                 // Конвертація у XML
  1264.                 $response = new Response($xml->asXML());
  1265.                 $response->headers->set('Content-Type''application/xml');
  1266.         
  1267.                 return $response;
  1268.     }
  1269. }