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