src/Trinity/WebshopBundle/Controller/FrontController.php line 425

Open in your IDE?
  1. <?php
  2. namespace App\Trinity\WebshopBundle\Controller;
  3. use App\CmsBundle\Controller\StorageController;
  4. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  5. use Symfony\Component\Routing\Annotation\Route;
  6. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\HttpFoundation\JsonResponse;
  9. use App\Trinity\WebshopBundle\Entity\Category;
  10. use App\Trinity\WebshopBundle\Entity\Invoice;
  11. use App\Trinity\WebshopBundle\Entity\OrderPayment;
  12. use App\Trinity\WebshopBundle\Entity\Review;
  13. use App\Trinity\WebshopBundle\Entity\SavedSearch;
  14. use App\Trinity\WebshopBundle\Entity\InvoiceProduct;
  15. use App\Trinity\WebshopBundle\Classes\Pdf;
  16. use App\Trinity\WebshopBundle\Entity\Tag;
  17. use App\Trinity\WebshopBundle\Classes\Picqer;
  18. use Twig\Environment;
  19. class FrontController extends StorageController
  20. {
  21.     /**
  22.      * @Route("/webshop-main/save/search", name="save_search")
  23.      * @Template()
  24.      */
  25.     public function savesearchAction(Request $request)
  26.     {
  27.         $this->init($request);
  28.         $validCaptcha $this->Settings->validateGoogleRecaptcha($request->request->get('g-recaptcha-response'));
  29.         if(($validCaptcha)){
  30.             if(!empty($_POST['email'])){
  31.                 $SavedSearch = new SavedSearch();
  32.                 $SavedSearch->setWebshop($this->Webshop);
  33.                 $SavedSearch->setEmail($_POST['email']);
  34.                 $SavedSearch->setDateStart(new \DateTime());
  35.                 $SavedSearch->setParameters($_POST);
  36.                 $em $this->getDoctrine()->getManager();
  37.                 $em->persist($SavedSearch);
  38.                 $em->flush();
  39.             }else{
  40.                 $spec_query '';
  41.                 $spec_filter = [];
  42.                 $licenseplate null;
  43.                 if(!empty($this->get('session')->get('ecomm_spec_filter'))){
  44.                     $spec_filter $this->get('session')->get('ecomm_spec_filter');
  45.                 }
  46.                 if(!empty($this->get('session')->get('ecomm_spec_plate'))){
  47.                     $licenseplate $this->get('session')->get('ecomm_spec_plate');
  48.                 }
  49.                 /*if(!empty($this->get('session')->get('ecomm_spec_query'))){
  50.                     $spec_query = $this->get('session')->get('ecomm_spec_query');
  51.                 }*/
  52.                 $data = [
  53.                     'spec_filter' => $spec_filter,
  54.                     'licenseplate' => $licenseplate,
  55.                     'spec_query' => $spec_query,
  56.                 ];
  57.                 $SavedSearch = new SavedSearch();
  58.                 $SavedSearch->setWebshop($this->Webshop);
  59.                 $SavedSearch->setEmail($_POST['filter-email']);
  60.                 $SavedSearch->setDateStart(new \DateTime());
  61.                 $SavedSearch->setParameters($data);
  62.                 $em $this->getDoctrine()->getManager();
  63.                 $em->persist($SavedSearch);
  64.                 $em->flush();
  65.             }
  66.             return new JsonResponse(['success' => true]);
  67.         }else{
  68.             return new JsonResponse(['success' => false'message' => 'Ongeldige captcha.']);
  69.         }
  70.     }
  71.     public function check_diff_multi($array1$array2){
  72.         $result = array();
  73.         foreach($array1 as $key => $val) {
  74.              if(isset($array2[$key])){
  75.                if(is_array($val) && $array2[$key]){
  76.                    $result[$key] = $this->check_diff_multi($val$array2[$key]);
  77.                }
  78.            } else {
  79.                $result[$key] = $val;
  80.            }
  81.         }
  82.         return $result;
  83.     }
  84.     public function initPaging(Request $request){
  85.         $em $this->getDoctrine()->getManager();
  86.         $this->Settings $em->getRepository('CmsBundle:Settings')->findByLanguage($this->languagestr_replace('www.'''$request->getHttpHost()));
  87.         if(is_null($this->Settings)) $this->Settings = new \App\CmsBundle\Entity\Settings();
  88.         $this->absoluteUrl $request->getScheme() . '://' $request->getHttpHost() . $request->getBasePath();
  89.         $this->FirstPage null;
  90.         $tmp_pages $this->getDoctrine()->getRepository('CmsBundle:Page')->findBy(array('language' => $this->Settings->getLanguage(), 'page' => null'base' => null'enabled' => true), array('sort' => 'ASC'), 1);
  91.         if(!empty($tmp_pages)){
  92.             $this->FirstPage $tmp_pages[0];
  93.         }
  94.     }
  95.     public function parse$tpl$args = array() ){
  96.         $args'Settings' ] = $this->Settings;
  97.         $args'languages' ] = $this->getDoctrine()->getRepository('CmsBundle:Language')->findAll();
  98.         if( !isset($args'bodyClass' ]) ) $args'bodyClass' ] = 'sub';
  99.         return $this->render($tpl '.html.twig'$args);
  100.     }
  101.     /**
  102.      * Load dynamic category as defined in WebshopBundle
  103.      *
  104.      * @param  Request $request
  105.      * @Template()
  106.      */
  107.     public function loadAction(Request $request)
  108.     {
  109.         $this->init($request);
  110.         $params = array();
  111.         $params[] = $request->get('param1');
  112.         $params[] = $request->get('param2');
  113.         $params[] = $request->get('param3');
  114.         // Find recipes page
  115.         $RecipesPage null;
  116.         $blocks $this->getDoctrine()->getRepository('CmsBundle:PageBlock')->findByData('TrinityRecipesBundle');
  117.         foreach($blocks as $Block){
  118.             $p $Block->getWrapper()->getPage();
  119.             if($p->getLanguage() == $this->language){
  120.                 $RecipesPage $p;
  121.                 break;
  122.             }
  123.         }
  124.         $this->initPaging($request);
  125.         $this->init($request);
  126.         $Webshop $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($this->language$this->Settings);
  127.         $Settings $Webshop->getSettings();
  128.         $custom_breadcrumbs = [];
  129.         $custom_breadcrumbs[] = [
  130.             'name' => $this->trans('home', [], 'webshop_backend'),
  131.             'url' => $this->generateUrl('homepage') . substr($this->Settings->getBaseUri(),1)
  132.         ];
  133.         // VALIDATE HOMEPAGE AS HIGHEST LEVEL
  134.         $access $this->FirstPage->getAccess();
  135.         if($access != null){
  136.             // Validate permissions
  137.             if($access == 'login'){
  138.                 $checkRoles $this->FirstPage->getAccessRoles();
  139.                 if($checkRoles){
  140.                     if(!is_array($checkRoles)) $checkRoles = [$checkRoles];
  141.                     $hasRoleAccess false;
  142.                     foreach($checkRoles as $role){
  143.                         if($this->get('security.authorization_checker')->isGranted($role)){
  144.                             $hasRoleAccess true;
  145.                             break;
  146.                         }
  147.                     }
  148.                     if(!$hasRoleAccess){
  149.                         if ($this->FirstPage->getAccessAllowLogin()) {
  150.                             // LOGIN FORM
  151.                             $hasLoginInvalidRoles false;
  152.                             if($this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')){
  153.                                 $hasLoginInvalidRoles true;
  154.                             }
  155.                             $metatags       $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getBySystem(0, (int)$this->FirstPage->getId(), true);
  156.                             $systemMetatags $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getBySystem(1falsefalse);
  157.                             $lastUsername '';
  158.                             $error null;
  159.                             $this->FirstPage->setTitle('Inloggen');
  160.                             $this->FirstPage->setLabel('Inloggen');
  161.                             $this->FirstPage->requireAuth true;
  162.                             return $this->parse'CmsBundle:Page:page'$this->attributes([
  163.                                 'loginform'            => true,
  164.                                 'bodyClass'            => 'dynamic',
  165.                                 'Page'                 => $this->FirstPage,
  166.                                 'metatags'             => $metatags,
  167.                                 'systemMetatags'       => $systemMetatags,
  168.                                 'error'                => $error,
  169.                                 'last_username'        => $lastUsername,
  170.                                 'hasLoginInvalidRoles' => $hasLoginInvalidRoles,
  171.                             ]));
  172.                         }else{
  173.                             throw $this->createAccessDeniedException('Permission denied');
  174.                         }
  175.                     }
  176.                 }
  177.             }elseif($access == 'no-login'){
  178.                 if($this->get('security.authorization_checker')->isGranted('ROLE_USER')){
  179.                     throw $this->createAccessDeniedException('Permission denied');
  180.                 }
  181.             }
  182.         }
  183.         $this->get('session')->set('last-route'$request->get('_route'));
  184.         $Page $Settings->getPage();
  185.         if(empty($Page)){
  186.             $Page = new \App\CmsBundle\Entity\Page();
  187.             $Page->setOptionBreadcrumbs(false);
  188.             $Page->setOptionSubnavigation(false);
  189.             $Page->setOptionTitle(false);
  190.         }
  191.         $metatags       $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getBySystem(0, (int)$Page->getId(), true);
  192.         $systemMetatags $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getBySystem(1falsefalse);
  193.         $all_products null;
  194.         $price_range null;
  195.         $catFix false;
  196.         $Product null;
  197.         $Category null;
  198.         if ($request->get('categoryId')) {
  199.             $Category $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findOneBy(['webshop' => $Webshop'id' => $request->get('categoryId')]);
  200.             if(empty($Category)){
  201.                 $_Category $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findOneBy(['id' => $request->get('categoryId')]);
  202.                 if($_Category->getWebshop() != $Webshop){
  203.                     // Webshop mismatch
  204.                     // Try to find one based on the same slug and webshop
  205.                     $Category $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findOneBy(['webshop' => $Webshop'slug' => $_Category->getSlug()]);
  206.                 }
  207.                 if(empty($Category)){
  208.                     throw $this->createNotFoundException('Category ' $request->get('categoryId') . ' not found');
  209.                 }
  210.             }
  211.             // Parsed wrong language category
  212.             if($Category->getWebshop() && ($Category->getWebshop()->getLanguage() != $this->language || $Category->getWebshop() != $this->Webshop)){
  213.                 $TmpCategory $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findOneBy([ 'slug' => $Category->getSlug(), 'webshop' => $this->Webshop ]);
  214.                 if($TmpCategory) {
  215.                     $Category $TmpCategory;
  216.                 }
  217.             }
  218.             if(!empty($params[1])){
  219.                 $Product $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->findByCategoryAndSlug($Category$params[1], true);
  220.             }else if(!empty($params[0])){
  221.                 $Product $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->findByCategoryAndSlug($Category$params[0], true);
  222.             } else if($request->get('productId')){
  223.                 $Product $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->findOneBy(['webshop' => $Webshop'id' => $request->get('productId')]);
  224.             }
  225.             // if($this->containerInterface->getParameter('kernel.environment') == 'dev'){
  226.             if(empty($Product)){
  227.                 // Fix for dynamic assigned products based on promotions
  228.                 if(!empty($params[1])){
  229.                     $FoundProduct $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->findOneBySlug($params[1]);
  230.                 }elseif(!empty($params[0])){
  231.                     $FoundProduct $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->findOneBySlug($params[0]);
  232.                 }
  233.                 // Found product itself, try look for dynamic promotion link
  234.                 if(!empty($FoundProduct) && !empty($FoundProduct->getCategory())){
  235.                     $CategoryProduct $FoundProduct->getCategory()->first();
  236.                     if((int)$this->WebshopSettings->getUriType() == 1){
  237.                         $productUrl '';
  238.                         $productUrl .= ($this->Webshop->getSettings()->getUri() ? '/' $this->Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
  239.                         // $productUrl .= $productname;
  240.                         // $productUrl .= '/' . $FoundProduct->getNumber();
  241.                         $productUrl .= $CategoryProduct->getCategory()->getUri();
  242.                         $productUrl .= '/' $FoundProduct->getSlug();
  243.                     }else{
  244.                         $productUrl '';
  245.                         $productUrl .= ($this->Webshop->getSettings()->getUri() ? '/' $this->Webshop->getSettings()->getUri() : $this->generateUrl('homepage') . ($this->Webshop->getCmssettings()->getBaseUri() ? $this->Webshop->getCmssettings()->getBaseUri() . '/' ''));
  246.                         //$productUrl .= ($Webshop->getSettings()->getUri() ? '/' . $Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
  247.                         $productUrl .= $CategoryProduct->getCategory()->getUri();
  248.                         $productUrl .= '/' $FoundProduct->getSlug();
  249.                         $productUrl str_replace('//''/'$productUrl);
  250.                     }
  251.                     header('Location:' $productUrl);
  252.                     exit;
  253.                 }
  254.             }
  255.             // }
  256.         }
  257.         // pelikan
  258.         if (is_numeric($params[0])) {
  259.             $Product $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->findOneBy(['number' => $params[0], 'language' => $this->language]);
  260.             $Category $Product->getCategory()->first()->getCategory();
  261.         }
  262.         if(!empty($_GET['q'])){
  263.             $res $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->search($this->Webshop, ['q' => $_GET['q']], 'id''asc');
  264.             if(!empty($res['total'])){
  265.                 $FoundProduct $res['results'][0];
  266.                 if(!empty($FoundProduct->getTemplateKey())){
  267.                     if((int)$this->WebshopSettings->getUriType() == 1){
  268.                         $productUrl '';
  269.                         $productUrl .= ($this->Webshop->getSettings()->getUri() ? '/' $this->Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
  270.                         // $productUrl .= $productname;
  271.                         // $productUrl .= '/' . $FoundProduct->getNumber();
  272.                         $productUrl .= $FoundProduct->getCategory()->first()->getCategory()->getUri();
  273.                         $productUrl .= '/' $FoundProduct->getSlug();
  274.                     }else{
  275.                         $productUrl '';
  276.                         $productUrl .= ($this->Webshop->getSettings()->getUri() ? '/' $this->Webshop->getSettings()->getUri() : $this->generateUrl('homepage') . ($this->Webshop->getCmssettings()->getBaseUri() ? $this->Webshop->getCmssettings()->getBaseUri() . '/' ''));
  277.                         //$productUrl .= ($Webshop->getSettings()->getUri() ? '/' . $Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
  278.                         $productUrl .= $FoundProduct->getCategory()->first()->getCategory()->getUri();
  279.                         $productUrl .= '/' $FoundProduct->getSlug();
  280.                         $productUrl str_replace('//''/'$productUrl);
  281.                     }
  282.                     header('Location:' $productUrl);
  283.                     exit;
  284.                 }
  285.             }
  286.         }
  287.         $sort null;
  288.         $sort_dir 'asc';
  289.         $defaultSort $this->WebshopSettings->getDefaultSort();
  290.         if(!empty($defaultSort)){
  291.             $defaultSort str_replace('-'' '$defaultSort);
  292.             $sort $defaultSort;
  293.         }
  294.         /**
  295.          * 
  296.          * 
  297.          *     ==============================================================================================================
  298.          *     ==============================================================================================================
  299.          *     ==============================================================================================================
  300.          *     ==============================================================================================================
  301.          * 
  302.          *     PRODUCT DETAIL
  303.          * 
  304.          *     ==============================================================================================================
  305.          *     ==============================================================================================================
  306.          *     ==============================================================================================================
  307.          *     ==============================================================================================================
  308.          * 
  309.          * 
  310.          */
  311.         if($Product){
  312.             //$this->Timer->break('Found product: ' . $Product->getLabel() . ', start product display');
  313.             // Check from parameters if caching must be enabled
  314.             $allowCache false;
  315.             if ($this->containerInterface->hasParameter('trinity_cache') && ($this->containerInterface->getParameter('trinity_cache') == 'true' || $this->containerInterface->getParameter('trinity_cache'))) {
  316.                 $allowCache true;
  317.             }
  318.             if(!empty($_GET['nocache']) || !empty($_GET['resetcache']) || !empty($_GET['timer']) || $this->containerInterface->getParameter('kernel.environment') == 'dev' || $Settings->getB2b()){
  319.                 $allowCache false;
  320.             }
  321.             /* if ($allowCache) {
  322.                 $cachedData = $Product->getCacheData();
  323.                 if(!empty($cachedData)){
  324.                     // Return cached data
  325.                     echo $cachedData;
  326.                     exit;
  327.                 }
  328.             } */
  329.             $Product->activeCategory $Category;
  330.             $recipes = [];
  331.             if(!empty($Product->getBundleLinkdata())){
  332.                 $bld $Product->getBundleLinkdata();
  333.                 if(!empty($bld['RecipesBundle'])){
  334.                     foreach($bld['RecipesBundle'] as $recipe_id){
  335.                         $Recipe $this->getDoctrine()->getRepository(\App\Trinity\RecipesBundle\Entity\Recipe::class)->find($recipe_id);
  336.                         if(!empty($Recipe)){
  337.                             $recipes[] = $Recipe;
  338.                         }
  339.                     }
  340.                 }
  341.             }
  342.             /*if($this->containerInterface->getParameter('kernel.environment') == 'dev'){
  343.                 dump($Product->getId());
  344.                 $displayPrice = $Product->getDisplayPrice($this->WebshopSettings, $this->WebshopCustomer, $this->getUser(), true);
  345.                 die($displayPrice);
  346.             }*/
  347.             if($Product->getType() == || $Product->getType() == 2){
  348.                 // if($this->containerInterface->getParameter('kernel.environment') == 'dev'){
  349.                     if(empty($Product->getLinkedProductsSorted()) && empty($Product->getSuper())){
  350.                         throw $this->createNotFoundException('Product ' $Product->getId() . ' not found');
  351.                     }
  352.                 // }
  353.             }
  354.             // $Product = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($request->get('productId'));
  355.             $current_productViewHistory $this->get('session')->get('product-view-history');
  356.             $productHistory = [$Product->getId()];
  357.             if(!empty($current_productViewHistory)){
  358.                 foreach($current_productViewHistory as $id){
  359.                     $historyProd $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($id);
  360.                     if($historyProd){
  361.                         if($id != $Product->getId() && $historyProd->getVisible() && $historyProd->getEnabled()){
  362.                             if(!in_array($id$productHistory)){
  363.                                 if(count($productHistory) < 5){
  364.                                     $productHistory[] = $id;
  365.                                 }
  366.                             }
  367.                         }
  368.                     }
  369.                 }
  370.             }
  371.             // Sign-up for restock messages
  372.             if(!empty($_POST['signupstock'])){
  373.                 $receipients $Product->getRestockNotify();
  374.                 $receipients[] = $_POST['signupstock'];
  375.                 $Product->setRestockNotify($receipients);
  376.                 $em $this->getDoctrine()->getManager();
  377.                 $em->persist($Product);
  378.                 $em->flush();
  379.                 header('Location:' $request->getUri() . '?notify-restock=true');
  380.                 exit;
  381.             }
  382.             $this->get('session')->set('product-view-history'$productHistory);
  383.             $firstAvailable null;
  384.             $firstAvailablePrice 100000000000;
  385.             if ($Product->getLinkedProducts()->count() > 0) {
  386.                 foreach($Product->getLinkedProducts() as $LP){
  387.                     if($LP->canOrder()){
  388.                         if($LP->getRealPriceIncl() < $firstAvailablePrice){
  389.                             $firstAvailable $LP;
  390.                             $firstAvailablePrice $LP->getRealPriceIncl();
  391.                         }
  392.                     }
  393.                 }
  394.             }
  395.             $productHistoryObjects = [];
  396.             foreach($productHistory as $id){
  397.                 if($id != $Product->getId()){
  398.                     $productHistoryObjects[$id] = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->findOneById($id);
  399.                 }
  400.             }
  401.             /*$productRelatedObjects = [];
  402.             $limit = 10;
  403.             $count = 0;
  404.             $CatProds = $Product->getCategory()[0]->getCategory()->getProducts();
  405.             foreach($CatProds as $CatProd){
  406.                 if($count <= $limit){
  407.                     if($CatProd->getProduct()->getId() != $Product->getId()){
  408.                         $productRelatedObjects[$CatProd->getProduct()->getId()] = $CatProd->getProduct();
  409.                         $count++;
  410.                     }
  411.                 } else {
  412.                     break;
  413.                 }
  414.             }*/
  415.             // Cleaner way and directly filtered by brand and model
  416.             $f = [];
  417.             $BrandsSpec $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->findOneBy(['label' => 'Merk']);
  418.             $ModelsSpec $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->findOneBy(['label' => 'Model']);
  419.             $specData $Product->getSimplifiedSpecValues();
  420.             foreach($specData as $k => $v){
  421.                 if(!empty($BrandsSpec) && $k == $BrandsSpec->getId()){ $f[$k] = $v; }
  422.                 if(!empty($ModelsSpec) && $k == $ModelsSpec->getId()){ $f[$k] = $v; }
  423.             }
  424.             $productRelatedObjects_raw $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->search(
  425.                 $this->Webshop,
  426.                 [
  427.                     'category' => $Product->getCategory()->first()->getCategory(),
  428.                     'visible' => 1,
  429.                     'filters' => $f,
  430.                     'ignore_ids' => [$Product->getId()],
  431.                 ], null'asc', ($this->WebshopSettings->getPagination() == 'none'), false1100
  432.             );
  433.             $productRelatedObjects $productRelatedObjects_raw['results'];
  434.             $country $Settings->getMapZoomCountry();
  435.             if (empty($Settings->getMapZoomCountry())) {
  436.                 $country '';
  437.             }
  438.             switch ($country)
  439.             {
  440.                 case 'nl':
  441.                     $center_lat 52.307963;
  442.                     $center_lng 5.551342;
  443.                     $center_zoom 7;
  444.                     break;
  445.                 case 'be':
  446.                     $center_lat 50.683057;
  447.                     $center_lng 4.731317;
  448.                     $center_zoom 8;
  449.                     break;
  450.                 case 'gb':
  451.                     $center_lat 54.121844;
  452.                     $center_lng = -2.767957;
  453.                     $center_zoom 6;
  454.                     break;
  455.                 case 'de':
  456.                     $center_lat 51.085295;
  457.                     $center_lng 10.027864;
  458.                     $center_zoom 6;
  459.                     break;
  460.                 case 'fr':
  461.                     $center_lat 47.091676;
  462.                     $center_lng 2.791095;
  463.                     $center_zoom 6;
  464.                     break;
  465.                 case 'it':
  466.                     $center_lat 43.095551;
  467.                     $center_lng 12.306936;
  468.                     $center_zoom 5;
  469.                     break;
  470.                 case 'ch':
  471.                     $center_lat 46.911197;
  472.                     $center_lng 8.297312;
  473.                     $center_zoom 8;
  474.                     break;
  475.                 case 'cz':
  476.                     $center_lat 49.832784;
  477.                     $center_lng 15.493717;
  478.                     $center_zoom 7.5;
  479.                     break;
  480.                 default:
  481.                     $center_lat 50.626387;
  482.                     $center_lng 9.889074;
  483.                     $center_zoom 4;
  484.                     break;
  485.             }
  486.             $custom_breadcrumbs[] = [
  487.                 'name' => $Category->getLabel(),
  488.                 'url' => ($Settings->getUri() ? '/' $Settings->getUri() : $this->generateUrl('homepage')) . $Category->getUri()
  489.             ];
  490.             if($Product->getTemplateKey() == 'printer_types.html.twig' || $Product->getTemplateKey() == 'printer_cartridges.html.twig'){
  491.                 $custom_breadcrumbs[] = [
  492.                     'name' => $Product->getFullLabel(),
  493.                     'url' => ($Settings->getUri() ? '/' $Settings->getUri() : $this->generateUrl('homepage')) . 'printers/' $Product->getSlug()
  494.                 ];
  495.             }else{
  496.                 $custom_breadcrumbs[] = [
  497.                     'name' => $Product->getFullLabel(),
  498.                     'url' => ($Settings->getUri() ? '/' $Settings->getUri() : $this->generateUrl('homepage')) . 'product/' $Product->getNumber() . '/' $Product->getSlug()
  499.                 ];
  500.             }
  501.             $this->breadcrumbs->addItem($Category->getLabel(), ($Settings->getUri() ? $Settings->getUri() : $this->generateUrl('homepage') . (!empty($this->Settings->getBaseUri()) ? substr($this->Settings->getBaseUri(),1) . '/' '')) . $Category->getUri());
  502.             $this->breadcrumbs->addItem($Product->getFullLabel(), ($Settings->getUri() ? $Settings->getUri() : $this->generateUrl('homepage') . (!empty($this->Settings->getBaseUri()) ? substr($this->Settings->getBaseUri(),1) . '/' '')) . 'product/' $Product->getNumber() . '/' $Product->getSlug());
  503.             // Validate
  504.             if(!$Product->getEnabled()){
  505.                 throw $this->createNotFoundException('Product ' $Product->getId() . ' not found');
  506.             }
  507.             $Page->setTitle($Product->getLabel());
  508.             // Prepare specs
  509.             $specsList = [];
  510.             $specs = [];
  511.             foreach($Product->getCategory() as $_Category){
  512.                 foreach($_Category->getCategory()->getSpecGroups() as $_SpecGroup){
  513.                     if(!$this->Webshop->getSpecGroups()->contains($_SpecGroup)) continue;
  514.                     foreach($_SpecGroup->getSpecs() as $_Spec){
  515.                         if(!$Webshop->getSpecs()->contains($_Spec)) continue;
  516.                         $specsList[] = $_Spec;
  517.                     }
  518.                 }
  519.             }
  520.             foreach($Product->getSpecGroups() as $_SpecGroup){
  521.                 if(!$this->Webshop->getSpecGroups()->contains($_SpecGroup)) continue;
  522.                 foreach($_SpecGroup->getSpecs() as $_Spec){
  523.                     if(!$Webshop->getSpecs()->contains($_Spec)) continue;
  524.                     $specsList[] = $_Spec;
  525.                 }
  526.             }
  527.             /*foreach($Product->getLinkedProducts()->first()->getSpecGroups() as $_SpecGroup){
  528.                 if(!$this->Webshop->getSpecGroups()->contains($_SpecGroup)) continue;
  529.                 foreach($_SpecGroup->getSpecs() as $_Spec){
  530.                     if(!$Webshop->getSpecs()->contains($_Spec)) continue;
  531.                     $specsList[] = $_Spec;
  532.                 }
  533.             }*/
  534.             $selectSpecs = [];
  535.             $specsSorted = [];
  536.             foreach($specsList as $_Spec){
  537.                 if($_Spec->getHidden() == true) { continue; }
  538.                 if($_Spec->getOptDetail() != true) { continue; }
  539.                 if($_Spec->getType() == 'dropdown'){
  540.                     $default = [];
  541.                     $available $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findBy(['spec' => $_Spec], ['position' => 'asc']);
  542.                     $SpecValues $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findValuesByProduct(
  543.                         $_Spec,
  544.                         $Product
  545.                     );
  546.                 }else{
  547.                     $default '';
  548.                     $available null;
  549.                     $SpecValues $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findValuesByProduct(
  550.                         $_Spec,
  551.                         $Product
  552.                     );
  553.                 }
  554.                 if($_Spec->getMultiple() && $_Spec->getChooseMultiple() && !empty($SpecValues)){
  555.                     $selectSpecs[$_Spec->getId()] = ['Spec' => $_Spec'values' => $SpecValues];
  556.                 }
  557.                 $groups = [];
  558.                 $lastGroup null;
  559.                 if($_Spec->getGroups()->count()){
  560.                     foreach($_Spec->getGroups() as $_SpecGroup){
  561.                         $lastGroup $_SpecGroup;
  562.                         $groups[] = $_SpecGroup->getLabel();
  563.                     }
  564.                 }
  565.                 $spdata = [
  566.                     'id'         => $_Spec->getId(),
  567.                     'label'      => $_Spec->getLabel(),
  568.                     'code'       => $_Spec->getCode(),
  569.                     'value'      => (!empty($SpecValues) ? $SpecValues $default),
  570.                     'available'  => $available,
  571.                     'groups'     => $groups,
  572.                     'multiple'   => $_Spec->getMultiple(),
  573.                     'choose'     => $_Spec->getChooseMultiple(),
  574.                     'required'   => $_Spec->getRequired(),
  575.                     'type'       => $_Spec->getType(),
  576.                     'hidden'     => $_Spec->getHidden(),
  577.                     'opt_filter' => $_Spec->getOptFilter(),
  578.                     'opt_detail' => $_Spec->getOptDetail(),
  579.                 ];
  580.                 $specs[$_Spec->getId()] = $spdata;
  581.                 if($lastGroup){
  582.                     $specsSorted[$lastGroup->getLabel()][$_Spec->getId()] = $spdata;
  583.                 }
  584.             }
  585.             // dump($specs);die();
  586.             $MatchLinked null;
  587.             $FirstLinked null;
  588.             $OriginalProduct $Product;
  589.             $filterTarget = [];
  590.             $filterTarget_readable = [];
  591.             if(!empty($_GET['filter'])){
  592.                 foreach($_GET['filter'] as $spec_id => $options){
  593.                     $Spec $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->find($spec_id);
  594.                     foreach($options as $v){
  595.                         $SpecValue $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findOneBy(['spec' => $Spec'value' => $v]);
  596.                         if(!empty($SpecValue)){
  597.                             $filterTarget[] = $spec_id '+' $SpecValue->getId();
  598.                             $filterTarget_readable[] = $Spec->getLabel() . '(' $spec_id ')+' $SpecValue->getValue() . '(' $SpecValue->getId() . ')';
  599.                         }
  600.                     }
  601.                 }
  602.             }
  603.             $configHex = [];
  604.             $configSpecs = [];
  605.             $configSpecs_alt = [];
  606.             $configSpecs_done = [];
  607.             $configSpecs_data = [];
  608.             $configSpecsObjects = [];
  609.             $usedSpecIds = [];
  610.             if($Product->getType() == 1){
  611.                 // Prepare specs
  612.                 $configSpecs = [];
  613.                 $configSpecs_pos = [];
  614.                 foreach($Product->getLinkedProducts() as $LinkedProduct){
  615.                     if($LinkedProduct->getEnabled()){
  616.                     foreach($LinkedProduct->getSpecValues() as $SpecValue){
  617.                         $configHex[$SpecValue->getValue()] = $SpecValue->getHex();
  618.                         /* if($FirstLinked == null){
  619.                             $FirstLinked = $LinkedProduct;
  620.                         } */
  621.                         $Spec $SpecValue->getSpec();
  622.                         if(!is_null($Spec) && ($Spec->getType() == 'dropdown' || $Spec->getType() == 'color')){
  623.                             if(!$Spec->getChooseMultiple()){
  624.                                 if($Spec->getOptFilter() != true) { continue; }
  625.                                 $configSpecs_pos[$Spec->getId()] = $Spec->getPosition();
  626.                                 $groups = [];
  627.                                 if($Spec->getGroups()->count()){
  628.                                     foreach($Spec->getGroups() as $_SpecGroup){
  629.                                         $groups[] = $_SpecGroup->getLabel();
  630.                                     }
  631.                                 }
  632.                                 // Required for parent
  633.                                 $specs[$Spec->getId()] = [
  634.                                     'id'         => $Spec->getId(),
  635.                                     'label'      => $Spec->getLabel(),
  636.                                     'code'       => $Spec->getCode(),
  637.                                     'value'      => null,
  638.                                     'available'  => null,
  639.                                     'groups'     => $groups,
  640.                                     'multiple'   => $Spec->getMultiple(),
  641.                                     'choose'     => $Spec->getChooseMultiple(),
  642.                                     'required'   => $Spec->getRequired(),
  643.                                     'type'       => $Spec->getType(),
  644.                                     'opt_filter' => $Spec->getOptFilter(),
  645.                                     'opt_detail' => $Spec->getOptDetail(),
  646.                                     // 'hidden'    => $Spec->getHidden(),
  647.                                 ];
  648.                                 /*if($Spec->getMultiple() && $Spec->getChooseMultiple()){
  649.                                     $selectSpecs[$Spec->getId()] = $Spec;
  650.                                 }*/
  651.                                 $configSpecsObjects[$SpecValue->getId()] = $SpecValue;
  652.                                 // if($Spec->getOptDetail()){
  653.                                     if(!isset($configSpecs[$Spec->getId()][$SpecValue->getPosition() . '+' $SpecValue->getId()])){
  654.                                         $configSpecs[$Spec->getId()][$SpecValue->getPosition() . '+' $SpecValue->getId()] = [];
  655.                                     }
  656.                                     $configSpecs[$Spec->getId()][$SpecValue->getPosition() . '+' $SpecValue->getId()][] = $LinkedProduct->getId();
  657.                                     $configSpecs_alt[$Spec->getId() . '+' $SpecValue->getId()][] = $LinkedProduct->getId();
  658.                                     //ksort($configSpecs[$Spec->getId()]);
  659.                                     $usedSpecIds[] = $Spec->getId();
  660.                                 // }
  661.                             }
  662.                         }
  663.                     }
  664.                 }
  665.             }
  666.             }
  667.             $sorted = [];
  668.             if(!empty($configSpecs_pos)){
  669.                 asort($configSpecs_pos);
  670.                 foreach($configSpecs_pos as $k => $pos){
  671.                     $sorted[$k] = [];
  672.                 }
  673.             }
  674.             // Sort configSpecs afterwards
  675.             foreach($configSpecs as $specid => $values){
  676.                 foreach($values as $k => $v){
  677.                     $k explode('+'$k);
  678.                     $sorted[$specid][$k[0]][$k[1]] = $v;
  679.                     ksort($sorted[$specid]);
  680.                 }
  681.             }
  682.             $configSpecs = [];
  683.             foreach($sorted as $specid => $d1){
  684.                 foreach($d1 as $sort => $d2){
  685.                     foreach($d2 as $svid => $vs){
  686.                         $configSpecs[$specid][$sort '+' $svid] = $vs;
  687.                     }
  688.                 }
  689.             }
  690.             // Find child product by filters
  691.             $foundCount = [];
  692.             foreach($filterTarget as $targetSpec){
  693.                 if(!empty($configSpecs_alt[$targetSpec])){
  694.                     // dump($configSpecs_alt[$targetSpec]);die();
  695.                     if(count($configSpecs_alt[$targetSpec]) > 0){
  696.                         foreach($configSpecs_alt[$targetSpec] as $id){
  697.                             if(empty($foundCount[$id])) $foundCount[$id] = 0;
  698.                             $foundCount[$id]++;
  699.                         }
  700.                         // $FirstLinked = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($configSpecs_alt[$targetSpec][0]);
  701.                     }
  702.                 }
  703.             }
  704.             foreach($foundCount as $id => $count){
  705.                 if($count == count($filterTarget)){
  706.                     $FirstLinked $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($id);
  707.                 }
  708.             }
  709.             foreach($configSpecs as $spec_id => $values){
  710.                 foreach($values as $pos_data => $links){
  711.                     $pos_data explode('+'$pos_data);
  712.                     $configSpecs_done[$spec_id][$configSpecsObjects[$pos_data[1]]->getValue()] = $links;
  713.                     $configSpecs_data[$spec_id][$configSpecsObjects[$pos_data[1]]->getValue()] = $configSpecsObjects[$pos_data[1]]->getId();
  714.                 }
  715.             }
  716.             /*foreach($usedSpecIds as $id){
  717.                 ksort($configSpecs[$id]);
  718.             }*/
  719.             // dump($configSpecs);die();
  720.             // Update views
  721.             $em $this->getDoctrine()->getManager();
  722.             $Product->setViews((int)$Product->getViews() + 1);
  723.             // Update real selling price
  724.             /*if($this->containerInterface->getParameter('kernel.environment') == 'dev'){
  725.                 dump($Product->getRealPrice());
  726.                 dump($Product->getRealPriceIncl());
  727.                 die();
  728.             }*/
  729.             /* if($FirstLinked){
  730.                 if($Product->getSellPrice() != $FirstLinked->getSellPrice()){
  731.                     $Product->setSellPrice($FirstLinked->getSellPrice());
  732.                 }
  733.                 if($Product->getSellPriceIncl() != $FirstLinked->getSellPriceIncl()){
  734.                     $Product->setSellPriceIncl($FirstLinked->getSellPriceIncl());
  735.                 }
  736.             }else{
  737.                 $Product->setSellPrice($Product->getRealPrice());
  738.                 $Product->setSellPriceIncl($Product->getRealPriceIncl());
  739.             } */
  740.             $em->persist($Product);
  741.             $em->flush();
  742.             if($FirstLinked){
  743.                 $Alt $Product;
  744.                 if($this->WebshopSettings->getInitializeConfigurable()){
  745.                     // Keep configurable global
  746.                     $Alt $FirstLinked;
  747.                 }else{
  748.                     $Product $FirstLinked;
  749.                 }
  750.                 // Prepare specs
  751.                 $specsList = [];
  752.                 $specs = [];
  753.                 foreach($FirstLinked->getCategory() as $_Category){
  754.                     foreach($_Category->getCategory()->getSpecGroups() as $_SpecGroup){
  755.                         if(!$this->Webshop->getSpecGroups()->contains($_SpecGroup)) continue;
  756.                         foreach($_SpecGroup->getSpecs() as $_Spec){
  757.                             if(!$Webshop->getSpecs()->contains($_Spec)) continue;
  758.                             $specsList[] = $_Spec;
  759.                         }
  760.                     }
  761.                 }
  762.                 foreach($FirstLinked->getSpecGroups() as $_SpecGroup){
  763.                     if(!$this->Webshop->getSpecGroups()->contains($_SpecGroup)) continue;
  764.                     foreach($_SpecGroup->getSpecs() as $_Spec){
  765.                         if(!$Webshop->getSpecs()->contains($_Spec)) continue;
  766.                         $specsList[] = $_Spec;
  767.                     }
  768.                 }
  769.                 // dump($specsList);die();
  770.                 $selectSpecs = [];
  771.                 foreach($specsList as $_Spec){
  772.                     if($_Spec->getHidden() == true) continue;
  773.                     if($_Spec->getType() == 'dropdown'){
  774.                         $default = [];
  775.                         $available $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findBy(['spec' => $_Spec], ['position' => 'asc']);
  776.                         $SpecValues $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findValuesByProduct(
  777.                             $_Spec,
  778.                             $Product
  779.                         );
  780.                     }else{
  781.                         $default '';
  782.                         $available null;
  783.                         $SpecValues $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findValuesByProduct(
  784.                             $_Spec,
  785.                             $Product
  786.                         );
  787.                     }
  788.                     if($_Spec->getMultiple() && $_Spec->getChooseMultiple() && !empty($SpecValues)){
  789.                         $selectSpecs[$_Spec->getId()] = ['Spec' => $_Spec'values' => $SpecValues];
  790.                     }
  791.                     $groups = [];
  792.                     if($_Spec->getGroups()->count()){
  793.                         foreach($_Spec->getGroups() as $_SpecGroup){
  794.                             $groups[] = $_SpecGroup->getLabel();
  795.                         }
  796.                     }
  797.                     $specs[$_Spec->getId()] = [
  798.                         'id'         => $_Spec->getId(),
  799.                         'label'      => $_Spec->getLabel(),
  800.                         'code'       => $_Spec->getCode(),
  801.                         'value'      => (!empty($SpecValues) ? $SpecValues $default),
  802.                         'available'  => $available,
  803.                         'groups'     => $groups,
  804.                         'multiple'   => $_Spec->getMultiple(),
  805.                         'choose'     => $_Spec->getChooseMultiple(),
  806.                         'required'   => $_Spec->getRequired(),
  807.                         'type'       => $_Spec->getType(),
  808.                         'opt_filter' => $_Spec->getOptFilter(),
  809.                         'opt_detail' => $_Spec->getOptDetail(),
  810.                         'hidden'     => $_Spec->getHidden(),
  811.                     ];
  812.                 }
  813.             }
  814.             // dump($specs); die();
  815.             // Find favorite products
  816.             $isLinked false;
  817.             $WebshopUser $this->getDoctrine()->getRepository('TrinityWebshopBundle:User')->findOneByUser($this->getUser());
  818.             if($WebshopUser){
  819.                 foreach($WebshopUser->getProductList() as $ItemList){
  820.                     foreach($ItemList->getProducts() as $p){
  821.                         if($p == $Product){
  822.                             $isLinked true;
  823.                         }
  824.                     }
  825.                 }
  826.             }
  827.             $metatags       $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getBySystem(0, (int)$Page->getId(), true);
  828.             $systemMetatags $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getBySystem(1falsefalse);
  829.             $children_count = [];
  830.             $children = [];
  831.             $carFilterName = ['merk' => '''model' => '''bouwjaar' => ''];
  832.             $rootCategory $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findOneByLabel('Onderdelen');
  833.             if(!empty($rootCategory)){
  834.                 $spec_filter_checked = [];
  835.                 foreach($Product->getSpecValues() as $SV){
  836.                     $Spec $SV->getSpec();
  837.                     if(!empty($Spec) && in_array($Spec->getId(), [265266267])){
  838.                         if($Spec->getId() == 265){
  839.                             $carFilterName['merk'] = $SV->getValue();
  840.                         }
  841.                         if($Spec->getId() == 266){
  842.                             $carFilterName['model'] = $SV->getValue();
  843.                         }
  844.                         if($Spec->getId() == 267){
  845.                             $carFilterName['bouwjaar'] = $SV->getValue();
  846.                         }
  847.                         $spec_filter_checked[$Spec->getId()] = $SV->getValue();
  848.                     }
  849.                 }
  850.                 if(!empty($spec_filter_checked)){
  851.                     $children_raw $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findCategoriesWithSpecs($rootCategory$spec_filter_checked'root');
  852.                     foreach($children_raw as $c){
  853.                         if($c['id']){
  854.                             $children[] = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->find($c['id']);
  855.                             $children_count[$c['id']] = $c['num'];
  856.                         }
  857.                     }
  858.                 }
  859.             }
  860.             $category_view_query '?merk=' $carFilterName['merk'] . '&model=' $carFilterName['model'] . '&bouwjaar=' $carFilterName['bouwjaar'] . '';
  861.             $carFilterName implode(' '$carFilterName);
  862.             
  863.             $total_rating = ['total' => 0'rating_total' => 0'avg' => 0];
  864.             $total_rating_raw $this->getDoctrine()->getRepository('TrinityWebshopBundle:Review')->productTotal($Product->getId());
  865.             $total_rating_rawTwo $this->getDoctrine()->getRepository('TrinityWebshopBundle:Review')->countTotalByProduct($Product->getId());
  866.             if(!empty($total_rating_raw[0])){
  867.                 $total_rating $total_rating_raw[0];
  868.             }
  869.             if(!empty($total_rating_rawTwo)){
  870.                 $total_rating['total'] = $total_rating_rawTwo;
  871.             }
  872.             $total_rating['avg_up'] = (ceil($total_rating['avg'] * 2) / 2);
  873.     
  874.             $specs_disabled_format = [];
  875.             $simpSpec $Product->getSimplifiedSpecValues(true);
  876.             if(!empty($simpSpec)){
  877.                 $svid $simpSpec['svid'];
  878.                 $checkSpec $simpSpec['Spec'];
  879.                 
  880.                 $tmp_all = [];
  881.                 $tmp_enabled = [];
  882.                 $tmp_disabled = [];
  883.                 $tmp_matching = [];
  884.                 $sv_obj = [];
  885.                 foreach($OriginalProduct->getLinkedProducts() as $ChildProduct){
  886.                     foreach($ChildProduct->getSpecValues() as $SV){
  887.                         if($svid){
  888.                             if($SV->getId() == $svid){
  889.                                 $tmp_matching[] = $ChildProduct;
  890.                             }else{
  891.                                 if($checkSpec != $SV->getSpec()){
  892.                                     $tmp_all[$SV->getId()] = $SV->getValue();
  893.                                     $sv_obj[$SV->getId()] = $SV;
  894.                                 }
  895.                             }
  896.                         }else{
  897.                             $tmp_matching[] = $ChildProduct;
  898.                             $tmp_all[$SV->getId()] = $SV->getValue();
  899.                             $sv_obj[$SV->getId()] = $SV;
  900.                         }
  901.                     }
  902.                 }
  903.                 foreach($tmp_matching as $ChildProduct){
  904.                     foreach($ChildProduct->getSpecValues() as $SV){
  905.                         if($checkSpec != $SV->getSpec() && $ChildProduct->canOrder()){
  906.                             $tmp_enabled[$SV->getId()] = $SV->getValue();
  907.                             $sv_obj[$SV->getId()] = $SV;
  908.                         }
  909.                     }
  910.                 }
  911.                 $tmp_disabled array_diff($tmp_all$tmp_enabled);
  912.                 foreach($tmp_disabled as $svid => $svlabel){
  913.                     if(!empty($sv_obj[$svid]->getSpec())){
  914.                         $specs_disabled_format[$sv_obj[$svid]->getSpec()->getId()][] = $svlabel;
  915.                     }
  916.                 }
  917.             }
  918.             
  919.             
  920.             if($Settings->getPicqerChoice() == && !empty($Settings->getPicqerApikey()) && !empty($Settings->getPicqerUrl())){
  921.                 $Picqer = new Picqer($Settings->getPicqerApikey(), $Settings->getPicqerUrl());
  922.                 if($Settings->getPicqerFulfillment()){
  923.                     if(!empty($Settings->getPicqerFulfillmentId())){
  924.                         $fulfilment_id $Settings->getPicqerFulfillmentId();
  925.                     } else {
  926.                         $fulfilment_id null;
  927.                     }
  928.                 } else {
  929.                     $fulfilment_id null;
  930.                 }
  931.                 $stock $Picqer::checkStock($Product$fulfilment_id);
  932.                 if($stock !== "Product not found in Picqer" && $stock !== "Product empty"){
  933.                     if($Product->getStockAmount() != $stock){
  934.                         $Product->setStockAmount($stock);
  935.                     }
  936.                 }
  937.             }
  938.             if(preg_match('/price_incl.*?(asc|desc)/'$sort$m)){
  939.                 $sort 'sell_price ' $m[1];
  940.             }
  941.             $products_data = [];
  942.             $priceRange = [(int)$Product->getMin(),(int)$Product->getMax()];
  943.             if($Product->getTemplateKey() == 'printer_cartridges.html.twig'){
  944.                 // Currently Pelikan specific
  945.                 $spec_filter_checked = [];
  946.                 $get_q '';
  947.                 $get_qo '';
  948.                 $products_data $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->search(null, array(
  949.                     'spec_filter_checked' => $spec_filter_checked,
  950.                     'relation' => $Product,
  951.                     'visible' => true,
  952.                     'page' => 1,
  953.                     /*'limit' => [
  954.                         'start' => 0,
  955.                         'limit' => 9
  956.                     ],*/
  957.                     'q' => $get_q,
  958.                     'qo' => $get_qo,
  959.                     'filters' => $spec_filter_checked,
  960.                 ), $sort$sort_dir, ($Settings->getPagination() == 'none'), false, (!empty($_GET['page']) && is_numeric($_GET['page']) ? $_GET['page'] : 1), $this->WebshopSettings->getPerPage());
  961.             }
  962.             $activeRelations = [];
  963.             foreach($Product->getRelations() as $Relation){
  964.                 if($Relation->getEnabled() && $Relation->getVisible()){
  965.                     $activeRelations[] = $Relation;
  966.                 }
  967.             }
  968.             //dump($Product->getId());
  969.             //dump($Product->getRelations()->count());
  970.             //dump($activeRelations);die();
  971.             $canonical_url '';
  972.             $foundCategory null;
  973.             foreach ($Product->getCategory() as $catProd)
  974.             {
  975.                 if (empty($foundCategory)) {
  976.                     $foundCategory $catProd->getCategory();
  977.                 } else if ($Settings->getCanonicalType() == 'first-main-cat') {
  978.                     if (!empty($foundCategory->getParent()) && $foundCategory->getParent()->getId() == $catProd->getCategory()->getId()) {
  979.                         $foundCategory $catProd->getCategory();
  980.                     }
  981.                 } else if (is_null($Settings->getCanonicalType()) || $Settings->getCanonicalType() == 'first-sub-cat') {
  982.                     $subCat $catProd->getCategory();
  983.                     $tempCat null;
  984.                     $subLoop true;
  985.                     do {
  986.                         if (!empty($subCat->getParent()) &&
  987.                             $subCat->getParent()->getId() == $foundCategory->getId()) {
  988.                             $tempCat $subCat;
  989.                         } else if (!empty($subCat->getParent()) &&
  990.                                    !empty($subCat->getParent()->getParent()) &&
  991.                                    $subCat->getParent()->getParent()->getId() == $foundCategory->getId()) {
  992.                             $tempCat $subCat;
  993.                         } else if (!empty($subCat->getParent()) && 
  994.                                    !empty($subCat->getParent()->getParent()) &&
  995.                                    !empty($subCat->getParent()->getParent()->getParent()) &&
  996.                                    $subCat->getParent()->getParent()->getParent()->getId() == $foundCategory->getId()) {
  997.                             $tempCat $subCat;
  998.                         } else {
  999.                             $subLoop false;
  1000.                         }
  1001.                         $subCat $subCat->getParent();
  1002.                     } while ($subLoop);
  1003.                     if (!empty($tempCat)) {
  1004.                         $foundCategory $tempCat;
  1005.                     }
  1006.                 }
  1007.             }
  1008.             if (!empty($foundCategory)) {
  1009.                 $canonical_url $foundCategory->getUri() . '/' $Product->getSlug();
  1010.             }
  1011.             $Product $this->parseEntityPageUrls($Product);
  1012.             $Settings $this->parseSettingsPageUrls($Settings);
  1013.             $specsByGroup = [];
  1014.             foreach($specs as $id => $spec){
  1015.                 if(!empty($spec['groups'])){
  1016.                     foreach($spec['groups'] as $g){
  1017.                         $specsByGroup[$g][$id] = $spec;
  1018.                     }
  1019.                 }else{
  1020.                     $specsByGroup['Default'][$id] = $spec;
  1021.                 }
  1022.             }
  1023.             if($this->Meta && !empty($Product)){
  1024.                 $this->Meta->registerView($request'webshop_product'$Product->getId(), $Product->getLabel());
  1025.             }
  1026.             $response $this->render('@TrinityWebshop/front/product.html.twig'$this->attributes([
  1027.                 'Category'              => $Category,
  1028.                 'Product'               => $Product,
  1029.                 'OriginalProduct'       => $OriginalProduct,
  1030.                 'firstAvailable'        => $firstAvailable,
  1031.                 'configHex'             => $configHex,
  1032.                 'specs'                 => $specs,
  1033.                 'specsSorted'           => $specsSorted,
  1034.                 'specsByGroup'          => $specsByGroup,
  1035.                 'configSpecs'           => $configSpecs_done,
  1036.                 'configSpecsIds'        => $configSpecs_data,
  1037.                 'selectSpecs'           => $selectSpecs,
  1038.                 'metatags'              => $metatags,
  1039.                 'systemMetatags'        => $systemMetatags,
  1040.                 'Page'                  => $Page,
  1041.                 'usedSpecIds'           => $usedSpecIds,
  1042.                 
  1043.                 'products_data'         => $products_data,
  1044.                 'priceRange'            => $priceRange,
  1045.                 'sort'                  => $sort,
  1046.                 'productHistoryObjects' => (array)$productHistoryObjects,
  1047.                 'productRelatedObjects' => (array)$productRelatedObjects,
  1048.                 'WebshopSettings'       => $Settings,
  1049.                 'isLinked'              => $isLinked,
  1050.                 'bodyClass'             => 'product-detail',
  1051.                 'custom_breadcrumbs'    => $custom_breadcrumbs,
  1052.                 'locale'                => '',
  1053.                 'center_lat'            => $center_lat,
  1054.                 'center_lng'            => $center_lng,
  1055.                 'center_zoom'           => $center_zoom,
  1056.                 'specs_disabled'        => $specs_disabled_format,
  1057.                 'category_view'         => $children,
  1058.                 'category_view_count'   => $children_count,
  1059.                 'category_view_query'   => $category_view_query,
  1060.                 'canonical_url'         => $canonical_url,
  1061.                 'carFilterName'         => $carFilterName,
  1062.                 'total_rating'          => $total_rating,
  1063.                 'activeRelations'       => $activeRelations,
  1064.                 'recipes'               => $recipes,
  1065.                 'RecipesPage' => $RecipesPage,
  1066.             ]));
  1067.             if ($allowCache) {
  1068.                 $Product->setCacheData($response->getContent());
  1069.             }
  1070.             //$response = $this->responseRewriteOutput($response, false, false);
  1071.             return $response;
  1072.         }
  1073.         /**
  1074.          * 
  1075.          * 
  1076.          *     ==============================================================================================================
  1077.          *     ==============================================================================================================
  1078.          *     ==============================================================================================================
  1079.          *     ==============================================================================================================
  1080.          * 
  1081.          *     ROOT CATEGORY OVERVIEW
  1082.          * 
  1083.          *     ==============================================================================================================
  1084.          *     ==============================================================================================================
  1085.          *     ==============================================================================================================
  1086.          *     ==============================================================================================================
  1087.          * 
  1088.          * 
  1089.          */
  1090.         elseif($Category != null && $Category->getShowSubCategories()){
  1091.             /*
  1092.                 Categorie shows sub categories, not products
  1093.              */
  1094.             $Category $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->find($request->get('categoryId'));
  1095.             $Page->setTitle($Category->getLabel());
  1096.             $allRootCategories = [];
  1097.             if($Category->getShowAll()){
  1098.                 $allRootCategories $this->getDoctrine()->getRepository(Category::class)->findBy(['parent' => null], ['position' => 'asc']);
  1099.             }
  1100.             $children = [];
  1101.             $doSearch false;
  1102.             $noResults false;
  1103.             if(!empty($_GET['r']) && $_GET['r'] == 'no-results'){
  1104.                 $noResults true;
  1105.             }
  1106.             $brandAndModelArr = [];
  1107.             $brandAndModel '[]';
  1108.             $cachedir preg_replace('/src\/.*?$/'''__DIR__) . 'var/cache/';
  1109.             if(file_exists($cachedir 'brands_sorted.json')){
  1110.                 $brandAndModelArr_tmp json_decode(file_get_contents($cachedir 'brands_sorted.json'), true);
  1111.                 $brandAndModelArr = [];
  1112.                 if(!is_array($brandAndModelArr_tmp)) $brandAndModelArr_tmp = [];
  1113.                 else{
  1114.                     if(!empty($brandAndModelArr_tmp[$Category->getId()])){
  1115.                         $brandAndModelArr $brandAndModelArr_tmp[$Category->getId()];
  1116.                     }
  1117.                 }
  1118.                 $brandAndModel json_encode($brandAndModelArr);
  1119.             }
  1120.             $typesArr = [];
  1121.             $types '[]';
  1122.             $cachedir preg_replace('/src\/.*?$/'''__DIR__) . 'var/cache/';
  1123.             if(file_exists($cachedir 'types_sorted.json')){
  1124.                 $typesArr_tmp json_decode(file_get_contents($cachedir 'types_sorted.json'), true);
  1125.                 $typesArr = [];
  1126.                 if(!is_array($typesArr_tmp)) $typesArr_tmp = [];
  1127.                 else{
  1128.                     if(!empty($typesArr_tmp[$Category->getId()])){
  1129.                         $typesArr $typesArr_tmp[$Category->getId()];
  1130.                     }
  1131.                 }
  1132.                 $types json_encode($typesArr);
  1133.             }
  1134.             $spec_query '';
  1135.             $spec_filter = [];
  1136.             $licenseplate null;
  1137.             if (!$Settings->getDisableRememberSearch()) {
  1138.                 if(!empty($this->get('session')->get('ecomm_spec_filter'))){
  1139.                     $spec_filter $this->get('session')->get('ecomm_spec_filter');
  1140.                 }
  1141.                 if(!empty($this->get('session')->get('ecomm_spec_plate'))){
  1142.                     $licenseplate $this->get('session')->get('ecomm_spec_plate');
  1143.                 }
  1144.                 /*if(!empty($this->get('session')->get('ecomm_spec_query'))){
  1145.                     $spec_query = $this->get('session')->get('ecomm_spec_query');
  1146.                 }*/
  1147.             }
  1148.             if(!empty($_GET['clearplate'])){
  1149.                 $licenseplate '';
  1150.                 $spec_filter = [];
  1151.                 $this->get('session')->set('ecomm_spec_plate''');
  1152.                 $this->get('session')->set('ecomm_spec_filter', []);
  1153.             }
  1154.             /*$BrandsSpec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->findOneBy(['label' => 'Merk']);
  1155.             $ModelsSpec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->findOneBy(['label' => 'Model']);*/
  1156.         
  1157.             $category_label '';
  1158.             if(!empty($_GET['c'])){
  1159.                 $C $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->find($_GET['c']);
  1160.                 $category_label $C->getLabel();
  1161.             }
  1162.             if(!empty($_GET['q']) && $_GET['q'] != 'undefined'){
  1163.                 $spec_query $_GET['q'];
  1164.                 // $this->get('session')->set('ecomm_spec_query', $_GET['q']);
  1165.             }else{
  1166.                 if(isset($_GET['q'])){
  1167.                     // $this->get('session')->set('ecomm_spec_query', '');
  1168.                 }
  1169.             }
  1170.             if(!empty($spec_query)){
  1171.                 $spec_query_tmp explode(' '$spec_query);
  1172.                 $modelsToSearch = [];
  1173.                 foreach($spec_query_tmp as $qpi => $qp){
  1174.                     foreach($brandAndModelArr as $brand => $models){
  1175.                         if(strtolower($brand) == strtolower($qp)){
  1176.                             $spec_filter['Merk'] = $brand;
  1177.                             unset($spec_query_tmp[$qpi]);
  1178.                             $modelsToSearch $models;
  1179.                             break;
  1180.                         }
  1181.                     }
  1182.                 }
  1183.                 foreach($spec_query_tmp as $qpi => $qp){
  1184.                     foreach($modelsToSearch as $model){
  1185.                         if(strtolower($model) == strtolower($qp)){
  1186.                             $spec_filter['Model'] = $model;
  1187.                             unset($spec_query_tmp[$qpi]);
  1188.                             break;
  1189.                         }
  1190.                     }
  1191.                 }
  1192.                 $spec_query implode(' '$spec_query_tmp);
  1193.             }
  1194.             if($spec_query == 'undefined'){
  1195.                 $spec_query '';
  1196.                 // $this->get('session')->set('ecomm_spec_query', '');
  1197.             }
  1198.             if(!empty($_GET['merk'])){
  1199.                 $spec_filter['Merk'] = $_GET['merk'];
  1200.                 if(!empty($_GET['model'])){
  1201.                     $spec_filter['Model'] = $_GET['model'];
  1202.                     if(!empty($_GET['bouwjaar'])){
  1203.                         $spec_filter['Bouwjaar'] = $_GET['bouwjaar'];
  1204.                     }
  1205.                 }
  1206.                 $this->get('session')->set('ecomm_spec_filter'$spec_filter);
  1207.             }
  1208.             if(!empty($_GET['type']) && $_GET['type'] != 'Alle onderdelen'){
  1209.                 $spec_filter['Type Onderdeel'] = $_GET['type'];
  1210.                 $this->get('session')->set('ecomm_spec_filter'$spec_filter);
  1211.             }else{
  1212.                 if(isset($_GET['type']) && isset($spec_filter['Type Onderdeel'])){
  1213.                     unset($spec_filter['Type Onderdeel']);
  1214.                     $this->get('session')->set('ecomm_spec_filter'$spec_filter);
  1215.                 }
  1216.             }
  1217.             if(!empty($_GET['licenseplate'])){
  1218.                 $licenseplate $_GET['licenseplate'];
  1219.             }
  1220.             $model null;
  1221.             $type null;
  1222.             $year null;
  1223.             if(!empty($licenseplate)){
  1224.                 $api_url 'https://services.onderdelenlijn.nl/parts/v7.asmx?WSDL';
  1225.                 $user 'info@beyonit.nl';
  1226.                 $pass 'fUAJT6!XP';
  1227.                 $Webshop $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($this->language$this->Settings);
  1228.                 
  1229.                 $SOAP_LOCATION_APP $api_url;
  1230.                 $soapClient = new \SoapClient($SOAP_LOCATION_APP, ["trace" => 1"exception" => 0'cache_wsdl' => WSDL_CACHE_NONE'soap_version' => SOAP_1_2]);
  1231.                 $soapMessage = [
  1232.                     'Credentials' => [
  1233.                         'Username' => $user,
  1234.                         'Password' => $pass,
  1235.                     ],
  1236.                     'Parameters' => [
  1237.                         'Culture' => "NL",
  1238.                         'TviRequest' => [
  1239.                             'Type' => 'LicensePlate',
  1240.                             'Value' => $licenseplate
  1241.                         ]
  1242.                     ]
  1243.                 ];
  1244.                 $soapResult $soapClient->TviData($soapMessage);
  1245.                 $res json_decode(json_encode($soapResult), true);
  1246.                 if(!empty($res["TviDataResult"]["Result"])){
  1247.                     $array $res["TviDataResult"]["Result"];
  1248.                     $model = (!empty($array["Basic"]["MakeModel"]["MakeName"]) ? $array["Basic"]["MakeModel"]["MakeName"] : null);
  1249.                     $type  = (!empty($array["Basic"]["MakeModel"]["ModelName"]) ? $array["Basic"]["MakeModel"]["ModelName"] : null);
  1250.                     $year  = (!empty($array["Basic"]["Constructed"]['Year']) ? $array["Basic"]["Constructed"]['Year'] : null);
  1251.                     $month = (!empty($array["Basic"]["Constructed"]['Month']) ? $array["Basic"]["Constructed"]['Month'] : null);
  1252.                     $spec_filter['Merk'] = $model;
  1253.                     $spec_filter['Model'] = $type;
  1254.                     $spec_filter['Bouwjaar'] = $year;
  1255.                 }
  1256.             }
  1257.             if(!empty($spec_filter['Merk']) && $spec_filter['Merk'] == 'Alle merken'){
  1258.                 if($model){
  1259.                     $spec_filter['Merk'] = $model;
  1260.                     $this->get('session')->set('ecomm_spec_filter'$spec_filter);
  1261.                 }else{
  1262.                     unset($spec_filter['Merk']);
  1263.                 }
  1264.             }
  1265.             if(!empty($spec_filter['Model']) && $spec_filter['Model'] == 'Alle modellen'){
  1266.                 if($type){
  1267.                     $spec_filter['Model'] = $type;
  1268.                     $this->get('session')->set('ecomm_spec_filter'$spec_filter);
  1269.                 }else{
  1270.                     unset($spec_filter['Model']);
  1271.                 }
  1272.             }
  1273.             if(!empty($spec_filter['Type Onderdeel']) && $spec_filter['Type Onderdeel'] == 'Alle onderdelen'){
  1274.                 unset($spec_filter['Type Onderdeel']);
  1275.             }
  1276.             if(!empty($_GET['drop'])){
  1277.                 if($_GET['drop'] == 'all'){
  1278.                     // $this->get('session')->set('ecomm_spec_query', '');
  1279.                     $spec_query '';
  1280.                     $spec_filter = [];
  1281.                     $this->get('session')->set('ecomm_spec_filter', []);
  1282.                     $this->get('session')->set('ecomm_spec_plate''');
  1283.                 }else if(preg_match('/_/'$_GET['drop'])){
  1284.                     $_GET['drop'] = explode('_'$_GET['drop']);
  1285.                     // $q = explode(' ', $this->get('session')->get('ecomm_spec_query'));
  1286.                     foreach($q as $k => $v){
  1287.                         if($_GET['drop'][1] == $k){
  1288.                             unset($q[$k]);
  1289.                         }
  1290.                     }
  1291.                     $q implode(' '$q);
  1292.                     // $this->get('session')->set('ecomm_spec_query', $q);
  1293.                     $spec_query $q;
  1294.                 }else{
  1295.                     if($_GET['drop'] == 'q'){
  1296.                         // Drop search filter
  1297.                         // $this->get('session')->set('ecomm_spec_query', '');
  1298.                         $spec_query '';
  1299.                     }else{
  1300.                         // Drop spec filter
  1301.                         $spec_id $_GET['drop'];
  1302.                         $Spec $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->find($spec_id);
  1303.                         if(!empty($Spec) && isset($spec_filter[$Spec->getLabel()])){
  1304.                             unset($spec_filter[$Spec->getLabel()]);
  1305.                             $this->get('session')->set('ecomm_spec_filter'$spec_filter);
  1306.                             $this->get('session')->set('ecomm_spec_plate''');
  1307.                         }
  1308.                     }
  1309.                 }
  1310.             }
  1311.             $spec_filter_checked = [];
  1312.             $filters_visual = [];
  1313.             
  1314.             if(!empty($spec_filter) && is_array($spec_filter)){
  1315.                 foreach($spec_filter as $specLabel => $value){
  1316.                     // TMP IGNORE
  1317.                     if(in_array($specLabel, ['Bouwmaand'])) continue;
  1318.                     $Spec $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->findOneBy(['label' => $specLabel]);
  1319.                     if(!empty($Spec)){
  1320.                         $spec_filter_checked[$Spec->getId()] = $value;
  1321.                         $filters_visual[$Spec->getId()] = ['label' => ($Spec->getLabel() == 'Model compatibiliteit' 'Bouwjaar' $Spec->getLabel()), 'value' => $value];
  1322.                     }
  1323.                 }
  1324.             }
  1325.             if(!empty($spec_query)){
  1326.                 $spec_filter_checked['q'] = explode(' '$spec_query);
  1327.                 // $filters_visual['q'] = ['label' => 'Zoeken', 'value' => implode(', ', $spec_filter_checked['q'])];
  1328.                 foreach($spec_filter_checked['q'] as $qpart){
  1329.                     if(!isset($filters_visual['q'])){
  1330.                         $filters_visual['q'] = [];
  1331.                     }
  1332.                     $filters_visual['q'][] = ['label' => 'Zoeken''value' => $qpart];
  1333.                 }
  1334.             }
  1335.             $level 'root';
  1336.             if(count($Category->getParents()) > 0){
  1337.                 $level 'sub';
  1338.             }
  1339.             if($level == 'sub'){
  1340.                 $custom_breadcrumbs[] = [
  1341.                     'name' => $Category->getParent()->getLabel(),
  1342.                     'url' => ($Settings->getUri() ? '/' $Settings->getUri() : $this->generateUrl('homepage')) . $Category->getParent()->getUri()
  1343.                 ];
  1344.             }
  1345.             $custom_breadcrumbs[] = [
  1346.                 'name' => $Category->getLabel(),
  1347.                 'url' => ($Settings->getUri() ? '/' $Settings->getUri() : $this->generateUrl('homepage')) . $Category->getUri()
  1348.             ];
  1349.             $children_count = [];
  1350.             if(!empty($spec_filter_checked)){
  1351.                 $doSearch true;
  1352.                 $redirectToId null;
  1353.                 $children = [];
  1354.                 $children_raw $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findCategoriesWithSpecs($Category$spec_filter_checked$level);
  1355.                 // Check if only one category
  1356.                 if(count($children_raw) == && !empty($children_raw[0])){
  1357.                     $tmp_id $children_raw[0]['id'];
  1358.                     $redirectToId $children_raw[0]['id'];
  1359.                     // Test sub
  1360.                     $sub_children_raw $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findCategoriesWithSpecs($tmp_id$spec_filter_checked'sub');
  1361.                     if(count($sub_children_raw) == && !empty($sub_children_raw[0])){
  1362.                         $redirectToId $sub_children_raw[0]['id'];
  1363.                     }
  1364.                 }
  1365.                 if(!empty($redirectToId)){
  1366.                     // Redirect to category
  1367.                     $CatRedirect $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->find($redirectToId);
  1368.                     return $this->redirectToRoute($CatRedirect->getSlugKey());
  1369.                 }
  1370.                 foreach($children_raw as $c){
  1371.                     if($c['id']){
  1372.                         $children[] = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->find($c['id']);
  1373.                         $children_count[$c['id']] = $c['num'];
  1374.                     }
  1375.                 }
  1376.             }
  1377.             if(!$doSearch){
  1378.                 // No search, show categories index
  1379.                 $children $Category->getChildren();
  1380.                 /*if($this->containerInterface->getParameter('kernel.environment') == 'dev'){
  1381.                     dump($children->last());die();
  1382.                 }*/
  1383.                 if($level == 'root'){
  1384.                     foreach($children as $Child){
  1385.                         if($Child->getHidden()) continue;
  1386.                         $children_count[$Child->getId()] = 0;
  1387.                         foreach($Child->getChildren() as $SubChild){
  1388.                             $children_count[$Child->getId()] += $SubChild->getProducts()->count();
  1389.                         }
  1390.                     }
  1391.                 }else{
  1392.                     foreach($children as $Child){
  1393.                         if($Child->getHidden()) continue;
  1394.                         $children_count[$Child->getId()] = $Child->getProducts()->count();
  1395.                     }
  1396.                 }
  1397.             }
  1398.             $Category $this->parseEntityPageUrls($Category);
  1399.             $response $this->render('@TrinityWebshop/front/root_category.html.twig'$this->attributes([
  1400.                 'Category'           => $Category,
  1401.                 'Page'               => $Page,
  1402.                 'children'           => $children,
  1403.                 'noResults'          => $noResults,
  1404.                 'systemMetatags'     => $systemMetatags,
  1405.                 'licenseplate'       => $licenseplate,
  1406.                 'brandAndModel'      => $brandAndModel,
  1407.                 'brandAndModelArr'   => $brandAndModelArr,
  1408.                 'types'              => $types,
  1409.                 'typesArr'           => $typesArr,
  1410.                 'category_label'     => $category_label,
  1411.                 'custom_breadcrumbs' => $custom_breadcrumbs,
  1412.                 'children_count'     => $children_count,
  1413.                 'filters_visual'     => $filters_visual,
  1414.                 'spec_filter'        => $spec_filter,
  1415.                 'merk'               => (!empty($spec_filter['Merk']) ? $spec_filter['Merk'] : ''),
  1416.                 'model'              => (!empty($spec_filter['Model']) ? $spec_filter['Model'] : ''),
  1417.                 'bouwjaar'           => (!empty($spec_filter['Bouwjaar']) ? $spec_filter['Bouwjaar'] : ''),
  1418.                 'type'               => (!empty($spec_filter['Type']) ? $spec_filter['Type'] : ''),
  1419.                 'q'                  => $spec_query,
  1420.                 'licensepate'        => (!empty($spec_filter['licensepate']) ? $spec_filter['licensepate'] : ''),
  1421.                 'bodyClass'          => 'root-category-view',
  1422.                 'allRootCategories'  => $allRootCategories,
  1423.                 'RecipesPage' => $RecipesPage,
  1424.             ]));
  1425.             //$response = $this->responseRewriteOutput($response, false, false);
  1426.             return $response;
  1427.         }
  1428.         /**
  1429.          * 
  1430.          * 
  1431.          *     ==============================================================================================================
  1432.          *     ==============================================================================================================
  1433.          *     ==============================================================================================================
  1434.          *     ==============================================================================================================
  1435.          *
  1436.          *     CATEGORY DETAIL / PRODUCT OVERVIEW
  1437.          * 
  1438.          *     ==============================================================================================================
  1439.          *     ==============================================================================================================
  1440.          *     ==============================================================================================================
  1441.          *     ==============================================================================================================
  1442.          * 
  1443.          * 
  1444.          */
  1445.         else{
  1446.             $filters = [];
  1447.             if ($request->query->get('q')) {
  1448.                 $filters['q'] = $request->query->get('q');
  1449.             }
  1450.             if ($request->query->get('category')) {
  1451.                 $filters['category'] = $request->query->get('category');
  1452.             }
  1453.             $webshop_tags $this->getDoctrine()->getRepository(Tag::class)->findAll();
  1454.             if (empty($_GET['q']) && !empty($_GET['brand']) && isset($_GET['model'])) {
  1455.                 $brand_prod $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($_GET['brand']);
  1456.                 $model_prod null;
  1457.                 if(!empty($_GET['model'])){
  1458.                     $model_prod $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($_GET['model']);
  1459.                 }
  1460.                 
  1461.                 if(!empty($brand_prod)){
  1462.                     if(!empty($model_prod)){
  1463.                         if((int)$this->WebshopSettings->getUriType() == 1){
  1464.                             $productUrl '';
  1465.                             $productUrl .= ($Webshop->getSettings()->getUri() ? '/' $Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
  1466.                             // $productUrl .= $productname;
  1467.                             // $productUrl .= '/' . $model_prod->getNumber();
  1468.                             $productUrl .= $model_prod->getCategory()->first()->getCategory()->getUri();
  1469.                             $productUrl .= '/' $model_prod->getSlug();
  1470.                         }else{
  1471.                             $productUrl '';
  1472.                             $productUrl .= ($Webshop->getSettings()->getUri() ? '/' $Webshop->getSettings()->getUri() : $this->generateUrl('homepage') . ($Webshop->getCmssettings()->getBaseUri() ? $Webshop->getCmssettings()->getBaseUri() . '/' ''));
  1473.                             //$productUrl .= ($Webshop->getSettings()->getUri() ? '/' . $Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
  1474.                             $productUrl .= $model_prod->getCategory()->first()->getCategory()->getUri();
  1475.                             $productUrl .= '/' $model_prod->getSlug();
  1476.                             $productUrl str_replace('//''/'$productUrl);
  1477.                         }
  1478.                     }else{
  1479.                         if((int)$this->WebshopSettings->getUriType() == 1){
  1480.                             $productUrl '';
  1481.                             $productUrl .= ($Webshop->getSettings()->getUri() ? '/' $Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
  1482.                             // $productUrl .= $productname;
  1483.                             // $productUrl .= '/' . $model_prod->getNumber();
  1484.                             $productUrl .= $brand_prod->getCategory()->first()->getCategory()->getUri();
  1485.                             $productUrl .= '/' $brand_prod->getSlug();
  1486.                         }else{
  1487.                             $productUrl '';
  1488.                             $productUrl .= ($Webshop->getSettings()->getUri() ? '/' $Webshop->getSettings()->getUri() : $this->generateUrl('homepage') . ($Webshop->getCmssettings()->getBaseUri() ? $Webshop->getCmssettings()->getBaseUri() . '/' ''));
  1489.                             //$productUrl .= ($Webshop->getSettings()->getUri() ? '/' . $Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
  1490.                             $productUrl .= $brand_prod->getCategory()->first()->getCategory()->getUri();
  1491.                             $productUrl .= '/' $brand_prod->getSlug();
  1492.                             $productUrl str_replace('//''/'$productUrl);
  1493.                         }
  1494.                     }
  1495.                     header('Location: ' $productUrl);
  1496.                     exit;
  1497.                 }
  1498.             }
  1499.             /*$brandAndModel = [];
  1500.             $cachedir = preg_replace('/src\/.*?$/', '', __DIR__) . 'var/cache/';
  1501.             if(file_exists($cachedir . 'brands.json')){
  1502.                 $brandAndModelArr = json_decode(file_get_contents($cachedir . 'brands.json'), true);
  1503.                 if(!is_array($brandAndModelArr)) $brandAndModelArr = [];
  1504.                 $brandAndModel = json_encode($brandAndModelArr);
  1505.             }*/
  1506.             $brandAndModelArr = [];
  1507.             $brandAndModel '[]';
  1508.             if(!empty($Category)){
  1509.                 $cachedir preg_replace('/src\/.*?$/'''__DIR__) . 'var/cache/';
  1510.                 if(file_exists($cachedir 'brands_sorted.json')){
  1511.                     $brandAndModelArr json_decode(file_get_contents($cachedir 'brands_sorted.json'), true);
  1512.                     if(!is_array($brandAndModelArr)) $brandAndModelArr = [];
  1513.                     else{
  1514.                         if(!empty($brandAndModelArr[$Category->getId()])){
  1515.                             $brandAndModelArr $brandAndModelArr[$Category->getId()];
  1516.                         }
  1517.                     }
  1518.                     $brandAndModel json_encode($brandAndModelArr);
  1519.                 }
  1520.             }
  1521.             $typesArr = [];
  1522.             $types '[]';
  1523.             if(!empty($Category)){
  1524.                 $cachedir preg_replace('/src\/.*?$/'''__DIR__) . 'var/cache/';
  1525.                 if(file_exists($cachedir 'types_sorted.json')){
  1526.                     $typesArr json_decode(file_get_contents($cachedir 'types_sorted.json'), true);
  1527.                     if(!is_array($typesArr)) $typesArr = [];
  1528.                     else{
  1529.                         if(!empty($typesArr[$Category->getId()])){
  1530.                             $typesArr $typesArr[$Category->getId()];
  1531.                         }
  1532.                     }
  1533.                     $types json_encode($typesArr);
  1534.                 }
  1535.             }
  1536.             if(!empty($request->get('categoryId')) && is_numeric($request->get('categoryId'))){
  1537.                 $Category $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->find($request->get('categoryId'));
  1538.             }else{
  1539.                 throw $this->createNotFoundException('Category not found');
  1540.             }
  1541.             $allRootCategories = [];
  1542.             if($Category->getShowAll()){
  1543.                 $allRootCategories $this->getDoctrine()->getRepository(Category::class)->findBy(['parent' => null], ['position' => 'asc']);
  1544.             }
  1545.             if($Category->getId() == 4872 || $Category->getId() == 4871){
  1546.                 $this->get('session')->set('ecomm_spec_filter', []);
  1547.                 $this->get('session')->set('ecomm_spec_plate''');
  1548.                 // $this->get('session')->set('ecomm_spec_query', '');
  1549.             }
  1550.             if ($Category->getHidden()) {
  1551.                 throw $this->createNotFoundException('Category ' $request->get('categoryId') . ' not found [hidden]');
  1552.             }
  1553.             $spec_filter = [];
  1554.             $spec_query null;
  1555.             $licenseplate null;
  1556.             if (!$Settings->getDisableRememberSearch()) {
  1557.             if(!empty($this->get('session')->get('ecomm_spec_filter'))){
  1558.                 $spec_filter $this->get('session')->get('ecomm_spec_filter');
  1559.             }
  1560.             if(!empty($this->get('session')->get('ecomm_spec_plate'))){
  1561.                 $licenseplate $this->get('session')->get('ecomm_spec_plate');
  1562.             }
  1563.             /*if(!empty($this->get('session')->get('ecomm_spec_query'))){
  1564.                 $spec_query = $this->get('session')->get('ecomm_spec_query');
  1565.         }*/
  1566.             }
  1567.             if(!empty($_GET['Merk'])){
  1568.                 $spec_filter['Merk'] = $_GET['Merk'];
  1569.                 $this->get('session')->set('ecomm_spec_filter'$spec_filter);
  1570.             }
  1571.             if(!empty($_GET['Model'])){
  1572.                 $spec_filter['Model'] = $_GET['Model'];
  1573.                 $this->get('session')->set('ecomm_spec_filter'$spec_filter);
  1574.             }
  1575.             if(!empty($_GET['spec'])){
  1576.                 foreach($_GET['spec'] as $sid => $v){
  1577.                     // if($sid == 11){
  1578.                         $spec_filter[$sid] = $v;
  1579.                     // }
  1580.                 }
  1581.             }
  1582.             if(isset($spec_filter['Merk']) && $spec_filter['Merk'] == 'Alle merken'){
  1583.                 unset($spec_filter['Merk']);
  1584.                 $this->get('session')->set('ecomm_spec_filter'$spec_filter);
  1585.             }
  1586.             if(isset($spec_filter['Model']) && $spec_filter['Model'] == 'Alle modellen'){
  1587.                 unset($spec_filter['Model']);
  1588.                 $this->get('session')->set('ecomm_spec_filter'$spec_filter);
  1589.             }
  1590.             if(!empty($spec_query)){
  1591.                 $spec_query_tmp explode(' '$spec_query);
  1592.                 $modelsToSearch = [];
  1593.                 foreach($spec_query_tmp as $qpi => $qp){
  1594.                     foreach($brandAndModelArr as $brand => $models){
  1595.                         if(strtolower($brand) == strtolower($qp)){
  1596.                             $spec_filter['Merk'] = $brand;
  1597.                             unset($spec_query_tmp[$qpi]);
  1598.                             $modelsToSearch $models;
  1599.                             break;
  1600.                         }
  1601.                     }
  1602.                 }
  1603.                 foreach($spec_query_tmp as $qpi => $qp){
  1604.                     foreach($modelsToSearch as $model){
  1605.                         if(strtolower($model) == strtolower($qp)){
  1606.                             $spec_filter['Model'] = $model;
  1607.                             unset($spec_query_tmp[$qpi]);
  1608.                             break;
  1609.                         }
  1610.                     }
  1611.                 }
  1612.                 $spec_query implode(' '$spec_query_tmp);
  1613.             }
  1614.             $filters_visual = [];
  1615.             $spec_filter_checked = [];
  1616.             if(!empty($spec_filter) && is_array($spec_filter)){
  1617.                 foreach($spec_filter as $specLabel => $value){
  1618.                     // TMP IGNORE
  1619.                     // if(in_array($specLabel, ['Bouwjaar'])) continue;
  1620.                     if(is_numeric($specLabel)){
  1621.                         $Spec $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->findOneBy(['id' => $specLabel]);
  1622.                     }else{
  1623.                     $Spec $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->findOneBy(['label' => $specLabel]);
  1624.                     }
  1625.                     if(!empty($Spec)){
  1626.                         $spec_filter_checked[$Spec->getId()] = $value;
  1627.                         $filters_visual[$Spec->getId()] = ['label' => ($Spec->getLabel() == 'Model compatibiliteit' 'Bouwjaar' $Spec->getLabel()), 'value' => $value];
  1628.                     }
  1629.                 }
  1630.             }
  1631.             if(empty($filters['q']) && !empty($spec_query)){
  1632.                 $filters['q'] = $spec_query;
  1633.             }
  1634.             if(!empty($spec_query)){
  1635.                 $spec_filter_checked['q'] = explode(' '$spec_query);
  1636.                 // $filters_visual['q'] = ['label' => 'Zoeken', 'value' => implode(', ', $spec_filter_checked['q'])];
  1637.                 foreach($spec_filter_checked['q'] as $qpart){
  1638.                     if(!isset($filters_visual['q'])){
  1639.                         $filters_visual['q'] = [];
  1640.                     }
  1641.                     $filters_visual['q'][] = ['label' => 'Zoeken''value' => $qpart];
  1642.                 }
  1643.             }
  1644.             /*$brands = [];
  1645.             $BrandsSpec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->findOneBy(['label' => 'Merk']);
  1646.             $ModelsSpec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->findOneBy(['label' => 'Model']);
  1647.             foreach($BrandsSpec->getValues() as $SpecValue){
  1648.                 if(!in_array($SpecValue->getValue(), $brands)){
  1649.                     $brands[] = $SpecValue->getValue();
  1650.                     sort($brands);
  1651.                     dump($SpecValue->getValue());
  1652.                     if($SpecValue->getProducts()->count() > 0){
  1653.                         foreach($ModelsSpec->getValues() as $ModelSpecValue){
  1654.                             if($ModelSpecValue)
  1655.                         }
  1656.                     }
  1657.                 }
  1658.             }
  1659.             dump($brands);die();*/
  1660.             $this->Timer->reset();
  1661.             $cats array_reverse($Category->getParents());
  1662.             foreach($cats as $cr){
  1663.                 $custom_breadcrumbs[] = [
  1664.                     'name' => $cr->getLabel(),
  1665.                     'url' => ($Settings->getUri() ? '/' $Settings->getUri() : $this->generateUrl('homepage')) . $cr->getUri()
  1666.                 ];
  1667.             }
  1668.             $this->Timer->mark('Load category');
  1669.             $categories $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findBy(['parent' => null]);
  1670.             $this->Timer->mark('Load categories');
  1671.             if(empty($Category)){
  1672.                 return $this->redirectToRoute('homepage');
  1673.             }
  1674.             // Parsed wrong language category
  1675.             if($Category->getWebshop() && $Category->getWebshop()->getLanguage() != $this->language){
  1676.                 $TmpCategory $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findOneBy([ 'slug' => $Category->getSlug(), 'webshop' => $this->Webshop ]);
  1677.                 if($TmpCategory){$Category $TmpCategory; }
  1678.             }
  1679.             // Parsed wrong webshop
  1680.             if($Category->getWebshop() != $this->Webshop){
  1681.                 $TmpCategory $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findOneBy([ 'slug' => $Category->getSlug(), 'webshop' => $this->Webshop ]);
  1682.                 if($TmpCategory){$Category $TmpCategory; }
  1683.             }
  1684.             if(($Category->getWebshop() && $Category->getWebshop()->getLanguage() != $this->language) || ($Category->getWebshop() != $this->Webshop)){
  1685.                 return $this->redirectToRoute('homepage');
  1686.             }
  1687.             $Page->setTitle($Category->getLabel());
  1688.             $custom_breadcrumbs[] = [
  1689.                 'name' => $Category->getLabel(),
  1690.                 'url' => ($Settings->getUri() ? '/' $Settings->getUri() : $this->generateUrl('homepage')) . $Category->getUri()
  1691.             ];
  1692.             $this->breadcrumbs->addItem($Category->getLabel(), ($Settings->getUri() ? '/' $Settings->getUri() : $this->generateUrl('homepage')) . $Category->getUri());
  1693.             $this->Timer->mark('Before products');
  1694.             $get_q null;
  1695.             $get_qo null;
  1696.             if ($Settings->getSearchMode() && $Settings->getSearchMode() == 'or')
  1697.             {
  1698.                 if(!empty($request->query->get('q'))){
  1699.                     $get_q $request->query->get('q');
  1700.                     /*if(preg_match('/^([a-zA-Z]+)(\d+)$/', $get_q, $m)){
  1701.                         $get_q = $m[1] . ' ' . $m[2];
  1702.                     }
  1703.                     $get_q = explode(' ', $get_q);*/
  1704.                     if(!empty($get_q)){
  1705.                         /*if(preg_match('/^([a-zA-Z]+)(\d+)$/', $get_q, $m)){
  1706.                             $get_q = [];
  1707.                             $get_qo = [];
  1708.                             $get_qo = [];
  1709.                             // if(strlen($m[1]) > 2){
  1710.                                 $get_q[] = $m[1];
  1711.                             // }
  1712.                             // if(strlen($m[2]) > 2){
  1713.                                 $get_q[] = $m[2];
  1714.                             // }
  1715.                             $get_qo[] = $m[1] . $m[2];
  1716.                             $get_qo[] = $m[1] . '-' . $m[2];
  1717.                             $get_qo[] = $m[1] . ' ' . $m[2];
  1718.                         }else{*/
  1719.                             $f explode(' '$get_q);
  1720.                             $get_q = [];
  1721.                             $get_qo = [];
  1722.                             foreach($f as $v){
  1723.                                 // if(strlen($v) > 2){
  1724.                                     $get_q[] = $v;
  1725.                                 // }
  1726.                             }
  1727.                             $get_qo[] = implode($f'-');
  1728.                             $get_qo[] = implode($f' ');
  1729.                         //}
  1730.                     }
  1731.                 }
  1732.             } else {
  1733.                 if (isset($filters['q'])) {
  1734.                     $get_q $filters['q'];
  1735.                 }
  1736.             }
  1737.             if(preg_match('/price_incl.*?(asc|desc)/'$sort$m)){
  1738.                 $sort 'sell_price_incl ' $m[1];
  1739.             }
  1740.             $SearchCategory $Category;
  1741.             if(!empty($SearchCategory) && ($SearchCategory->getSlug() == 'category' || $SearchCategory->getSlug() == 'categorie' || $SearchCategory->getSlug() == 'kategorie')){
  1742.                 $SearchCategory null;
  1743.             }
  1744.             $relationProduct null;
  1745.             if(!empty($_GET['brand'])){
  1746.                 $brand_prod $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($_GET['brand']);
  1747.                 $model_prod null;
  1748.                 if(!empty($_GET['model'])){
  1749.                     $model_prod $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($_GET['model']);
  1750.                 }
  1751.                 if(!empty($brand_prod)){
  1752.                     $relationProduct $brand_prod;
  1753.                 }
  1754.                 if(!empty($model_prod)){
  1755.                     $relationProduct $model_prod;
  1756.                 }
  1757.             }
  1758.             $dev false;
  1759.             if($this->containerInterface->getParameter('kernel.environment') == 'dev'){
  1760.                 $dev true;
  1761.             }
  1762.             $products_data $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->search($this->Webshop, array(
  1763.                 'spec_filter_checked' => $spec_filter_checked,
  1764.                 'category' => $SearchCategory,
  1765.                 'relation' => $relationProduct,
  1766.                 'visible' => true,
  1767.                 'page' => 1,
  1768.                 /*'limit' => [
  1769.                     'start' => 0,
  1770.                     'limit' => 9
  1771.                 ],*/
  1772.                 'q' => $get_q,
  1773.                 'qo' => $get_qo,
  1774.                 'dev' => $dev,
  1775.                 'filters' => $spec_filter_checked,
  1776.                 // 'debug' => ($dev ? true : false),
  1777.             ), $sort$sort_dir, ($Settings->getPagination() == 'none'), false, (!empty($_GET['page']) && is_numeric($_GET['page']) ? $_GET['page'] : 1), $this->WebshopSettings->getPerPage());
  1778.             $this->Timer->mark('Products loaded');
  1779.             /*if($this->containerInterface->getParameter('kernel.environment') == 'dev'){
  1780.                 dump($products_data);die();
  1781.             }*/
  1782.             if (empty($products_data['total']) && !empty($_GET['brand']) && isset($_GET['model'])) {
  1783.                 $brand_prod $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($_GET['brand']);
  1784.                 $model_prod null;
  1785.                 if(!empty($_GET['model'])){
  1786.                     $model_prod $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($_GET['model']);
  1787.                 }
  1788.                 
  1789.                 if(!empty($brand_prod)){
  1790.                     if(!empty($model_prod)){
  1791.                         if((int)$this->WebshopSettings->getUriType() == 1){
  1792.                             $productUrl '';
  1793.                             $productUrl .= ($Webshop->getSettings()->getUri() ? '/' $Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
  1794.                             // $productUrl .= $productname;
  1795.                             // $productUrl .= '/' . $model_prod->getNumber();
  1796.                             $productUrl .= $model_prod->getCategory()->first()->getCategory()->getUri();
  1797.                             $productUrl .= '/' $model_prod->getSlug();
  1798.                         }else{
  1799.                             $productUrl '';
  1800.                             $productUrl .= ($Webshop->getSettings()->getUri() ? '/' $Webshop->getSettings()->getUri() : $this->generateUrl('homepage') . ($Webshop->getCmssettings()->getBaseUri() ? $Webshop->getCmssettings()->getBaseUri() . '/' ''));
  1801.                             //$productUrl .= ($Webshop->getSettings()->getUri() ? '/' . $Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
  1802.                             $productUrl .= $model_prod->getCategory()->first()->getCategory()->getUri();
  1803.                             $productUrl .= '/' $model_prod->getSlug();
  1804.                             $productUrl str_replace('//''/'$productUrl);
  1805.                         }
  1806.                     }else{
  1807.                         if((int)$this->WebshopSettings->getUriType() == 1){
  1808.                             $productUrl '';
  1809.                             $productUrl .= ($Webshop->getSettings()->getUri() ? '/' $Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
  1810.                             // $productUrl .= $productname;
  1811.                             // $productUrl .= '/' . $model_prod->getNumber();
  1812.                             $productUrl .= $brand_prod->getCategory()->first()->getCategory()->getUri();
  1813.                             $productUrl .= '/' $brand_prod->getSlug();
  1814.                         }else{
  1815.                             $productUrl '';
  1816.                             $productUrl .= ($Webshop->getSettings()->getUri() ? '/' $Webshop->getSettings()->getUri() : $this->generateUrl('homepage') . ($Webshop->getCmssettings()->getBaseUri() ? $Webshop->getCmssettings()->getBaseUri() . '/' ''));
  1817.                             //$productUrl .= ($Webshop->getSettings()->getUri() ? '/' . $Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
  1818.                             $productUrl .= $brand_prod->getCategory()->first()->getCategory()->getUri();
  1819.                             $productUrl .= '/' $brand_prod->getSlug();
  1820.                             $productUrl str_replace('//''/'$productUrl);
  1821.                         }
  1822.                     }
  1823.                     // dump($productUrl);die();
  1824.                     header('Location: ' $productUrl);
  1825.                     exit;
  1826.                 }
  1827.             }elseif(empty($products_data['total']) && !empty($_GET['q'])){
  1828.                 // dump($_GET['q']);die();
  1829.             }
  1830.             if(empty($products_data['total']) && $Settings->getFillEmptyCat()){
  1831.                 // Try to find by underlying categories
  1832.                 if($Category->getChildren()->count()){
  1833.                     $catlist = [];
  1834.                     foreach($Category->getChildren() as $c){
  1835.                         $catlist[] = $c->getId();
  1836.                     }
  1837.                     $products_data $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->search($this->Webshop, array(
  1838.                         'spec_filter_checked' => $spec_filter_checked,
  1839.                         'category' => $catlist,
  1840.                         'visible' => true,
  1841.                         'page' => 1,
  1842.                         'q' => $get_q,
  1843.                         'qo' => $get_qo,
  1844.                         'filters' => $spec_filter_checked,
  1845.                     ), $sort$sort_dir, ($Settings->getPagination() == 'none'), false, (!empty($_GET['page']) && is_numeric($_GET['page']) ? $_GET['page'] : 1), $this->WebshopSettings->getPerPage());
  1846.                     //$all_products = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->gatherProducts($catlist);
  1847.                     // $price_range = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->getPriceRange($Webshop, $catlist);
  1848.                     $catFix true;
  1849.                 }
  1850.                 $this->Timer->mark('Products (fill underlying) loaded');
  1851.             }
  1852.             $this->Timer->mark('Stuff loaded');
  1853.             $products $products_data['results'];
  1854.             foreach($products as $i => $p){
  1855.                 $p->activeCategory $Category;
  1856.                 $products[$i] = $p;
  1857.             }
  1858.             // $prices = [];
  1859.             // foreach ($products as $i => $product) {
  1860.             //     // check if this is the right function to get the right price, should doe sales, promotions etc.
  1861.             //     $p = $product->getRealPriceIncl($this->WebshopSettings);
  1862.             //     if(!empty($p)){
  1863.             //         $prices[] = $p;
  1864.             //     }
  1865.             // }
  1866.             if(!empty($Category->getMin()) && !empty($Category->getMax())){
  1867.                 $priceRange = [$Category->getMin(), $Category->getMax()];
  1868.                 // $priceRange = [0, 1];
  1869.             }else{
  1870.                 if(empty($price_range)){
  1871.                     $price_range $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->getPriceRange($Webshop$Category);
  1872.                 }
  1873.                 if(!empty($price_range)){
  1874.                     $pr $price_range[0];
  1875.                     $priceRange = [floor($pr['min_price']), ceil($pr['max_price'])];
  1876.                 }else{
  1877.                     $priceRange = [00];
  1878.                     if(!empty($prices)){
  1879.                         $priceRange = [floor(min($prices)), ceil(max($prices))];
  1880.                     }
  1881.                 }
  1882.             }
  1883.             $this->Timer->mark('Price range');
  1884.             // Prepare specs
  1885.             $specs = [];
  1886.             $groups = [];
  1887.             /*
  1888.             if(empty($all_products)){
  1889.                 $all_products = $Category->getProducts(); //$this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->findAll();
  1890.             }
  1891.             foreach($all_products as $Product){
  1892.                 $Product = $Product->getProduct();
  1893.                 foreach($Product->getCategory() as $_Category){
  1894.                     foreach($_Category->getCategory()->getSpecGroups() as $_SpecGroup){
  1895.                         if(!$this->Webshop->getSpecGroups()->contains($_SpecGroup)) continue;
  1896.                         $groups[$_SpecGroup->getId()] = $_SpecGroup;
  1897.                     }
  1898.                 }
  1899.                 foreach($Product->getSpecGroups() as $_SpecGroup){
  1900.                     if(!$this->Webshop->getSpecGroups()->contains($_SpecGroup)) continue;
  1901.                     $groups[$_SpecGroup->getId()] = $_SpecGroup;
  1902.                 }
  1903.             }
  1904.             $this->Timer->mark('Loaded: specs');
  1905.             // dump($groups);
  1906.             $productsList = [];
  1907.             foreach($all_products as $Product){
  1908.                 $Product = $Product->getProduct();
  1909.                 if($Product->getVisible() && $Product->getEnabled()){
  1910.                     $productsList[] = $Product;
  1911.                 }
  1912.                 if($Product->getType() > 0){
  1913.                     foreach($Product->getLinkedProducts() as $P){
  1914.                         $productsList[] = $P;
  1915.                     }
  1916.                 }
  1917.             }
  1918.             // dump(count($productsList));die();
  1919.             $this->Timer->mark('Loaded: productslist');
  1920.             // dump($productsList);die();
  1921.             if($this->WebshopSettings->getShowUnusedSpecs()){
  1922.                 foreach($groups as $_SpecGroup){
  1923.                     if(!$this->Webshop->getSpecGroups()->contains($_SpecGroup)) continue;
  1924.                     foreach($_SpecGroup->getSpecs() as $_Spec){
  1925.                         if(!$Webshop->getSpecs()->contains($_Spec)) continue;
  1926.                         if($_Spec->getHidden() == true || $_Spec->getOptFilter() == false) continue;
  1927.                         if($_Spec->getType() == 'dropdown'){
  1928.                             $available = $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findBy(['spec' => $_Spec], ['position' => 'asc']);
  1929.                             $SpecValues = $_Spec->getValues();
  1930.                             if(!empty($SpecValues)){
  1931.                                 $foundValues = 0;
  1932.                                 foreach($SpecValues as $v){
  1933.                                     if(!empty($v->getValue())){
  1934.                                         $foundValues++;
  1935.                                     }
  1936.                                 }
  1937.                                 if($foundValues == 0){
  1938.                                     continue;
  1939.                                 }
  1940.                                 if(isset($specs[$_Spec->getId()])){
  1941.                                     if(!is_array($specs[$_Spec->getId()]['value'])){
  1942.                                         $specs[$_Spec->getId()]['value'] = [$specs[$_Spec->getId()]['value']];
  1943.                                     }
  1944.                                         $specs[$_Spec->getId()]['value'] = array_unique(array_merge($specs[$_Spec->getId()]['value'], (!empty($SpecValues) ? $SpecValues : $default)));
  1945.                                     // }
  1946.                                 }else{
  1947.                                     $specs[$_Spec->getId()] = [
  1948.                                         'id'    => $_Spec->getId(),
  1949.                                         'label'    => $this->trans($_Spec->getLabel(), 'webshop'),
  1950.                                         'value'    => (!empty($SpecValues) ? $SpecValues : $default),
  1951.                                         'available'    => $available,
  1952.                                         'multiple'  => $_Spec->getMultiple(),
  1953.                                         'required' => $_Spec->getRequired(),
  1954.                                         'type' => $_Spec->getType(),
  1955.                                         'disabled' => true,
  1956.                                     ];
  1957.                                 }
  1958.                             }
  1959.                         }
  1960.                     }
  1961.                 }
  1962.             }
  1963.             $this->Timer->mark('Loaded: specs');
  1964.             $specAvailability = [];
  1965.             foreach($productsList as $Product){
  1966.                 if((!$Product->getVisible() && ($Product->getLinkedTo()->count() == 0 || (!$Product->getLinkedTo()->first()->getVisible() || !$Product->getLinkedTo()->first()->getEnabled()))) || !$Product->getEnabled()){
  1967.                     continue;
  1968.                 }
  1969.                 // dump($Product->getLabel());
  1970.                 foreach($groups as $_SpecGroup){
  1971.                     if(!$this->Webshop->getSpecGroups()->contains($_SpecGroup)) continue;
  1972.                     foreach($_SpecGroup->getSpecs() as $_Spec){
  1973.                         if(!$Webshop->getSpecs()->contains($_Spec)) continue;
  1974.                         // if($_Spec->getCode() != 'opslag') continue;
  1975.                         if($_Spec->getHidden() == true || $_Spec->getOptFilter() == false) continue;
  1976.                         if($_Spec->getType() == 'dropdown'){
  1977.                             $default = [];
  1978.                             $available = $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findBy(['spec' => $_Spec], ['position' => 'asc']);
  1979.                             $SpecValues = $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findValuesByProduct(
  1980.                                 $_Spec,
  1981.                                 $Product
  1982.                             );
  1983.                         }else{
  1984.                             $default = [];
  1985.                             $available = null;
  1986.                             $SpecValues = $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findValuesByProduct(
  1987.                                 $_Spec,
  1988.                                 $Product
  1989.                             );
  1990.                         }
  1991.                         if(!empty($SpecValues)){
  1992.                             if(!is_array($SpecValues)){
  1993.                                 $SpecValues = [$SpecValues];
  1994.                             }
  1995.                             $foundValues = 0;
  1996.                             if($_Spec->getCode() == 'color' && count($SpecValues) > 1){
  1997.                                 // Combine multi-color when spec has code 'color'
  1998.                                 $spec_values = [];
  1999.                                 $c_id = [];
  2000.                                 $c_value = [];
  2001.                                 $c_hex = [];
  2002.                                 foreach($SpecValues as $k => $v){
  2003.                                     if(!empty($v->getValue())){
  2004.                                         $c_id[] = $v->getId();
  2005.                                         $c_hex[] = $v->getHex();
  2006.                                         $c_value[] = $v->getValue();
  2007.                                         unset($SpecValues[$k]);
  2008.                                         $foundValues++;
  2009.                                     }
  2010.                                 }
  2011.                                 // dump(implode('-', $c_hex));
  2012.                                 $SpecValues[implode('-', $c_id)] = implode('-', $c_hex);
  2013.                             }else{
  2014.                                 foreach($SpecValues as $v){
  2015.                                     if(!empty($v->getValue())){
  2016.                                         // dump($v->getValue());
  2017.                                         $foundValues++;
  2018.                                     }
  2019.                                 }
  2020.                             }
  2021.                             if($foundValues == 0){
  2022.                                 continue;
  2023.                             }
  2024.                             // dump($SpecValues);
  2025.                             // dump($specs[5]['value']->toArray());die();
  2026.                             if(isset($specs[$_Spec->getId()])){
  2027.                                 $specs[$_Spec->getId()]['disabled'] = false;
  2028.                                 if(!is_array($specs[$_Spec->getId()]['value'])){
  2029.                                     $specs[$_Spec->getId()]['value'] = [$specs[$_Spec->getId()]['value']];
  2030.                                 }
  2031.                                 $specs[$_Spec->getId()]['value'] = array_unique(array_merge($specs[$_Spec->getId()]['value'], (!empty($SpecValues) ? $SpecValues : $default)));
  2032.                                 // }
  2033.                             }else{
  2034.                                 $specs[$_Spec->getId()] = [
  2035.                                     'id'    => $_Spec->getId(),
  2036.                                     'label'    => $this->trans($_Spec->getLabel(), 'webshop'),
  2037.                                     'value'    => (!empty($SpecValues) ? $SpecValues : $default),
  2038.                                     'available'    => $available,
  2039.                                     'multiple'  => $_Spec->getMultiple(),
  2040.                                     'required' => $_Spec->getRequired(),
  2041.                                     'type' => $_Spec->getType(),
  2042.                                 ];
  2043.                             }
  2044.                         }
  2045.                     }
  2046.                 }
  2047.                 // $this->Timer->mark('      FETCH PRODUCT');
  2048.             }
  2049.             */
  2050.             // sleep(1.6);
  2051.             $this->Timer->mark('Loaded: product list after specs');
  2052.             // dump($specs[5]);die();
  2053.             // Find favorite products
  2054.             $listIds = [];
  2055.             $WebshopUser $this->getDoctrine()->getRepository('TrinityWebshopBundle:User')->findOneByUser($this->getUser());
  2056.             if($WebshopUser){
  2057.                 foreach($WebshopUser->getProductList() as $ItemList){
  2058.                     foreach($ItemList->getProducts() as $p){
  2059.                         $listIds[] = $p->getId();
  2060.                     }
  2061.                 }
  2062.             }
  2063.             $this->Timer->mark('Loaded: id crap');
  2064.             /*foreach($specs as $id => $data){
  2065.                 $poslist = [];
  2066.                 foreach($data['value'] as $SV){
  2067.                     if(!empty($SV) && !is_string($SV)){
  2068.                         $poslist[$SV->getPosition()][] = $SV;
  2069.                     }
  2070.                 }
  2071.                 ksort($poslist);
  2072.                 foreach($data['value'] as $SV){
  2073.                     if(!empty($SV) && is_string($SV)){
  2074.                         $poslist[9999][] = $SV;
  2075.                     }
  2076.                 }
  2077.                 $rawList = [];
  2078.                 foreach($poslist as $l){
  2079.                     foreach($l as $SV){
  2080.                         $rawList[] = $SV;
  2081.                     }
  2082.                 }
  2083.                 $specs[$id]['value'] = $rawList;
  2084.             }*/
  2085.             $specs $Category->getSpecCache();
  2086.             foreach($specs as $k => $spec){
  2087.                 if($spec['type'] == 'range'){
  2088.                     // Walk values for sorting
  2089.                     $resort = [];
  2090.                     foreach($spec['value'] as $v){
  2091.                         $resort[$v['value']][] = $v;
  2092.                     }
  2093.                     ksort($resort);
  2094.                     $new = [];
  2095.                     foreach($resort as $vd){
  2096.                         foreach($vd as $v){
  2097.                             $new[] = $v;
  2098.                         }
  2099.                     }
  2100.                     $specs[$k]['value'] = $new;
  2101.                 }
  2102.             }
  2103.             $tmp_brand null;
  2104.             $tmp_model null;
  2105.             if(!empty($filters['q'])){
  2106.                 $f explode(' '$filters['q']);
  2107.                 if(!empty($f)){
  2108.                     foreach($f as $i => $fp){
  2109.                         // Search for brand
  2110.                         if(isset($brandAndModelArr[ucfirst($fp)])){
  2111.                             $tmp_brand ucfirst($fp);
  2112.                             unset($f[$i]);
  2113.                             break;
  2114.                         }
  2115.                     }
  2116.                     if(!empty($tmp_brand)){
  2117.                         foreach($f as $i => $fp){
  2118.                             // Search for brand
  2119.                             if(in_array($fp$brandAndModelArr[$tmp_brand])){
  2120.                                 $tmp_model $fp;
  2121.                                 unset($f[$i]);
  2122.                                 break;
  2123.                             }
  2124.                         }
  2125.                     }
  2126.                     $filters['q'] = implode(' '$f);
  2127.                 }
  2128.             }
  2129.             if(!empty($tmp_brand)){ $spec_filter['Merk'] = $tmp_brand; }
  2130.             if(!empty($tmp_model)){ $spec_filter['Model'] = $tmp_model; }
  2131.             
  2132.             $children_count = [];
  2133.             $children = [];
  2134.             $rootCategory $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findOneByLabel('Onderdelen');
  2135.             if(!empty($spec_filter_checked) && !empty($rootCategory)){
  2136.                 $doSearch true;
  2137.                 $redirectToId null;
  2138.                 $children = [];
  2139.                 $children_raw $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findCategoriesWithSpecs($rootCategory$spec_filter_checked'root');
  2140.                 // Check if only one category
  2141.                 /*if(count($children_raw) == 1 && !empty($children_raw[0])){
  2142.                     $tmp_id = $children_raw[0]['id'];
  2143.                     $redirectToId = $children_raw[0]['id'];
  2144.                     // Test sub
  2145.                     $sub_children_raw = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findCategoriesWithSpecs($tmp_id, $spec_filter_checked, 'sub');
  2146.                     if(count($sub_children_raw) == 1 && !empty($sub_children_raw[0])){
  2147.                         $redirectToId = $sub_children_raw[0]['id'];
  2148.                     }
  2149.                 }
  2150.                 if(!empty($redirectToId)){
  2151.                     // Redirect to category
  2152.                     $CatRedirect = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->find($redirectToId);
  2153.                     return $this->redirectToRoute($CatRedirect->getSlugKey());
  2154.                 }*/
  2155.                 foreach($children_raw as $c){
  2156.                     if($c['id']){
  2157.                         $children[] = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->find($c['id']);
  2158.                         $children_count[$c['id']] = $c['num'];
  2159.                     }
  2160.                 }
  2161.             }
  2162.             $paginationFilters $spec_filter;
  2163.             if(!empty($filters['q'])){
  2164.                 $paginationFilters['q'] = $filters['q'];
  2165.             }
  2166.             $Category $this->parseEntityPageUrls($Category);
  2167.             $this->Timer->mark('Loaded: before twig return');
  2168.             // $this->Timer->show();
  2169.             
  2170.             if($this->Meta && !empty($Category)){
  2171.                 $this->Meta->registerView($request'webshop_category'$Category->getId(), $Category->getLabel());
  2172.             }
  2173.             if($this->Meta && !empty($Category)){
  2174.                 $this->Meta->registerView($request'webshop_category'$Category->getId(), $Category->getLabel());
  2175.             }
  2176.             $response =  $this->render('@TrinityWebshop/front/category.html.twig'$this->attributes([
  2177.                 'Category'            => $Category,
  2178.                 'categories'          => $categories,
  2179.                 'Page'                => $Page,
  2180.                 'products'            => $products,
  2181.                 'specs'               => $specs,
  2182.                 'metatags'            => $metatags,
  2183.                 'sort'                => $sort,
  2184.                 'brandAndModel'       => $brandAndModel,
  2185.                 'brandAndModelArr'    => $brandAndModelArr,
  2186.                 'types'               => $types,
  2187.                 'typesArr'            => $typesArr,
  2188.                 'systemMetatags'      => $systemMetatags,
  2189.                 'spec_filter_checked' => $spec_filter_checked,
  2190.                 'filters_visual'      => $filters_visual,
  2191.                 'WebshopSettings'     => $Settings,
  2192.                 'licenseplate'        => $licenseplate,
  2193.                 'priceRange'          => $priceRange,
  2194.                 'catFix'              => $catFix,
  2195.                 'listIds'             => $listIds,
  2196.                 'products_data'       => $products_data,
  2197.                 'bodyClass'           => 'category-view',
  2198.                 'spec_filter'         => $spec_filter,
  2199.                 'filters'             => $filters,
  2200.                 'paginationFilters'   => $paginationFilters,
  2201.                 'custom_breadcrumbs'  => $custom_breadcrumbs,
  2202.                 'children'            => $children,
  2203.                 'children_count'      => $children_count,
  2204.                 'defaultSort'         => $defaultSort,
  2205.                 'allRootCategories'   => $allRootCategories,
  2206.                 'webshop_tags'        => $webshop_tags,
  2207.                 'RecipesPage' => $RecipesPage,
  2208.             ]));
  2209.             //$response = $this->responseRewriteOutput($response, false, false);
  2210.             return $response;
  2211.         }
  2212.     }
  2213.     /**
  2214.      * @Route("/webshop-main/categories/{parent}", name="webshop_front_categories")
  2215.      * @Template()
  2216.      */
  2217.     public function categoriesAction(Request $request$parent)
  2218.     {
  2219.         parent::init($request);
  2220.         $Parent $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->find($parent);
  2221.         $categories $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findByParent($Parent);
  2222.         return $this->attributes([
  2223.             'categories' => $categories
  2224.         ]);
  2225.     }
  2226.     /**
  2227.      * @Route("/webshop-main/review/{id}", name="webshop_review")
  2228.      * @Template()
  2229.      */
  2230.     public function reviewAction(Request $request$id)
  2231.     {
  2232.         parent::init($request);
  2233.         $post null;
  2234.         $saved false;
  2235.         if(!empty($_POST)){
  2236.             $post $_POST;
  2237.             $Product $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($id);
  2238.             $WebshopUser $this->getDoctrine()->getRepository('TrinityWebshopBundle:User')->findOneByUser($this->getUser());
  2239.             $rating 0;
  2240.             if(!empty($post['review']['rating'])){
  2241.                 $rating $post['review']['rating'];
  2242.             }
  2243.             $Review = new Review();
  2244.             $Review->setWebshop($this->Webshop);
  2245.             $Review->setLabel($post['review']['title']);
  2246.             $Review->setName($post['review']['name']);
  2247.             $Review->setReview($post['review']['body']);
  2248.             $Review->setRating((float)$rating);
  2249.             // $Review->setRecommend($post['review']['recommend'] == 1);
  2250.             $Review->setDate(new \DateTime());
  2251.             $Review->setProduct($Product);
  2252.             $Review->setUser($WebshopUser);
  2253.             $Review->setIp($request->getClientIp());
  2254.             if($this->WebshopSettings->getModerateReviews()){
  2255.                 $Review->setModerated(false);
  2256.             }else{
  2257.                 $Review->setModerated(true);
  2258.             }
  2259.             $em $this->getDoctrine()->getManager();
  2260.             $em->persist($Review);
  2261.             $em->flush();
  2262.             // clear product cache
  2263.             $Product->setCacheData(null);
  2264.             
  2265.             $saved true;
  2266.         }
  2267.         return $this->attributes([
  2268.             'saved' => $saved,
  2269.         ]);
  2270.     }
  2271.     /**
  2272.      * @Route("/webshop-main/ajax/productcount", name="mod_webshop_count")
  2273.      */
  2274.     public function productCountRequest $request )
  2275.     {
  2276.         // Initialize StorageController
  2277.         parent::init($request);
  2278.         $Products $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->countBy();
  2279.         dump($Products); die();
  2280.         return new JsonResponse(array('count' => $productcount));
  2281.     }
  2282.     /**
  2283.      * @Route("/webshop-main/configurable/{Product}", name="webshop_configurable")
  2284.      * @Template()
  2285.      */
  2286.     public function configurableProductAction(Request $request,$Product)
  2287.     {
  2288.         parent::init($request);
  2289.         $data $_POST;
  2290.         if(isset($_GET['spec'])){
  2291.             $data $_GET;
  2292.         }
  2293.         $svid null;
  2294.         $checkSpecValue null;
  2295.         $checkSpec null;
  2296.         if(!empty($_GET['svid']) && is_numeric($_GET['svid'])){
  2297.             $svid = (int)$_GET['svid'];
  2298.             $checkSpecValue $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->find($svid);
  2299.             $checkSpec $checkSpecValue->getSpec();
  2300.         }
  2301.         if(!empty($data['spec'])){
  2302.             foreach($data['spec'] as $k => $v){
  2303.                 if(empty($v)){
  2304.                     unset($data['spec'][$k]);
  2305.                 }
  2306.             }
  2307.         }
  2308.         $OriginalProduct $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($Product);
  2309.         
  2310.         $all_values = [];
  2311.         $enabled_values = [];
  2312.         $disabled_values = [];
  2313.         $all = [];
  2314.         $enabled = [];
  2315.         $disabled = [];
  2316.         $matching = [];
  2317.         $active = [];
  2318.         foreach($OriginalProduct->getLinkedProducts() as $ChildProduct){
  2319.             if($ChildProduct->getEnabled()){
  2320.                 foreach($ChildProduct->getSpecValues() as $SV){
  2321.                     if($svid){
  2322.                         if($SV->getId() == $svid){
  2323.                             $matching[] = $ChildProduct;
  2324.                         }else{
  2325.                             if($checkSpec != $SV->getSpec()){
  2326.                                 $all[$SV->getId()] = $SV->getId();
  2327.                                 $all_values[$SV->getId()] = $SV->getValue();
  2328.                             }
  2329.                         }
  2330.                     }else{
  2331.                         $matching[] = $ChildProduct;
  2332.                         $all[$SV->getId()] = $SV->getId();
  2333.                         $all_values[$SV->getId()] = $SV->getValue();
  2334.                     }
  2335.                 }
  2336.             }
  2337.         }
  2338.         // dump('checkSpec => ' . $checkSpec->getLabel());
  2339.         $selectedValues = [];
  2340.         if(!empty($data['spec'])){
  2341.             foreach($data['spec'] as $spec_id => $value_label){
  2342.                 $Spec $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->find($spec_id);
  2343.                 // dump($Spec->getLabel());
  2344.                 foreach($Spec->getValues() as $SV){
  2345.                     if($SV->getValue() == $value_label){
  2346.                         $selectedValues[] = $SV;
  2347.                     }
  2348.                 }
  2349.             }
  2350.         }
  2351.         $validProducts = [];
  2352.         foreach($matching as $ChildProduct){
  2353.             if($ChildProduct->canOrder()){
  2354.                 $productValues $ChildProduct->getSpecValues();
  2355.                 $simplified = [];
  2356.                 foreach($productValues as $SV){
  2357.                     $simplified[] = $SV->getId();
  2358.                 }
  2359.                 foreach($selectedValues as $SV){
  2360.                     // dump($SV->getValue() . ' - ' . $SV->getId());
  2361.                     if(!$productValues->contains($SV)){
  2362.                         // dump('fail');
  2363.                         if(isset($validProducts[$ChildProduct->getId()])){
  2364.                             unset($validProducts[$ChildProduct->getId()]);
  2365.                         }
  2366.                         continue(2);
  2367.                     }
  2368.                     // dump('pass');
  2369.                     $validProducts[$ChildProduct->getId()] = $ChildProduct;
  2370.                     // $enabled[$SV->getId()] = $SV->getId();
  2371.                     // $enabled_values[$SV->getId()] = $SV->getValue();
  2372.                 }
  2373.             }
  2374.         }
  2375.         // dump($validProducts); die();
  2376.         foreach($validProducts as $ChildProduct){
  2377.             foreach($ChildProduct->getSpecValues() as $SV){
  2378.                 $enabled[$SV->getId()] = $SV->getId();
  2379.                 $enabled_values[$SV->getId()] = $SV->getValue();
  2380.             }
  2381.         }
  2382.         $disabled array_diff($all$enabled);
  2383.         $disabled_values array_diff($all_values$enabled_values);
  2384.         $config_spec_filter = [
  2385.             'all'      => array_values($all),
  2386.             'enabled'  => array_values($enabled),
  2387.             'disabled' => array_values($disabled),
  2388.         ];
  2389.         $config_spec_filter_values = [
  2390.             'all'      => array_values($all_values),
  2391.             'enabled'  => array_values($enabled_values),
  2392.             'disabled' => array_values($disabled_values),
  2393.         ];
  2394.         $chosen = [];
  2395.         if(!empty($_GET['chosenid'])){
  2396.             $chosen explode('_'$_GET['chosenid']);
  2397.         }
  2398.         $products $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->findBySpecs($data$Product$this->containerInterface->getParameter('kernel.environment') == 'dev');
  2399.         $products_sort_done = [];
  2400.         $products_sort = [];
  2401.         // if($this->containerInterface->getParameter('kernel.environment') == 'dev'){
  2402.             if(!empty($data)){
  2403.                 // Sort based on spec_values
  2404.                 foreach($products as $p){
  2405.                     foreach($p->getSpecValues() as $sv){
  2406.                         if(!in_array($p->getId(), $products_sort_done) && !empty($sv->getSpec()) && (empty($data['spec']) || !array_key_exists($sv->getSpec()->getId(), $data['spec']))){
  2407.                             if(!isset($products_sort[$sv->getPosition()])){
  2408.                                 $products_sort[$sv->getPosition()] = [];
  2409.                             }
  2410.                             $products_sort[$sv->getPosition()][] = $p;
  2411.                             $products_sort_done[] = $p->getId();
  2412.                         }
  2413.                     }
  2414.                 }
  2415.             }
  2416.             if(!empty($products_sort)){
  2417.                 $products = [];
  2418.                 ksort($products_sort);
  2419.                 foreach($products_sort as $svpos => $prods){
  2420.                     foreach($prods as $p){
  2421.                         $products[] = $p;
  2422.                     }
  2423.                 }
  2424.             }
  2425.         // }
  2426.         if(empty($products)){
  2427.             // No products found by filter, find another by target spec
  2428.             $products $matching;
  2429.         }
  2430.         
  2431.         if(!empty($products)){
  2432.             $ChildProduct $products[0];
  2433.             foreach($ChildProduct->getSpecValues() as $SV){
  2434.                 $active[] = $SV->getId();
  2435.             }
  2436.         }
  2437.         $config_spec_filter['active'] = $active;
  2438.         $flatSpecs = [];
  2439.         $allSpecsRaw = [];
  2440.         $keyValue = [];
  2441.         foreach($OriginalProduct->getLinkedProducts() as $Product){
  2442.             $specs = [];
  2443.             foreach($Product->getSpecValues() as $SV){
  2444.                 if(!empty($SV->getSpec())){
  2445.                     if ($SV->getSpec()->getOptDetail()) {
  2446.                         $specs[$SV->getSpec()->getId()] = $SV->getValue();
  2447.                         if(!isset($filters[$SV->getSpec()->getId()])){
  2448.                             if(!isset($allSpecsRaw[$SV->getSpec()->getId()])) $allSpecsRaw[$SV->getSpec()->getId()] = [];
  2449.                             if(!in_array($SV->getValue(), $allSpecsRaw[$SV->getSpec()->getId()])){
  2450.                                 $allSpecsRaw[$SV->getSpec()->getId()][] = (int)$SV->getPosition() . '+' $SV->getValue();
  2451.                                 $keyValue[$SV->getSpec()->getId()][(int)$SV->getId()] =  $SV->getValue();
  2452.                                 sort($allSpecsRaw[$SV->getSpec()->getId()]);
  2453.                             }
  2454.                         }
  2455.                     }
  2456.                 }
  2457.             }
  2458.             $flatSpecs[$Product->getId()] = $specs;
  2459.         }
  2460.         $allSpecs = [];
  2461.         foreach($allSpecsRaw as $sid => $sv){
  2462.             foreach($sv as $svi => $svid){
  2463.                 $svid preg_replace('/^\d\+/'''$svid);
  2464.                 if(!isset($allSpecs[$sid]) || !in_array($svid$allSpecs[$sid])){
  2465.                     $allSpecs[$sid][] = $svid;
  2466.                 }
  2467.             }
  2468.         }
  2469.         $filters = [];
  2470.         if(!empty($data['spec'])){
  2471.             $filters $data['spec'];
  2472.             foreach($filters as $k => $v){
  2473.                 $filters[$k] = [$v];
  2474.             }
  2475.         }
  2476.         $matchedSpecs = [];
  2477.         $matchedOtherSpecs = [];
  2478.         foreach($products as $Product){
  2479.             if($Product->canOrder()){
  2480.                 $pid $Product->getId();
  2481.                 if(!empty($filters)){
  2482.                     // Filters required, product MUST HAVE filters
  2483.                     if(!empty($flatSpecs[$pid])){
  2484.                         $flatProdSpecs $flatSpecs[$pid];
  2485.                         $flatProdSpecsNotFiltered $flatSpecs[$pid];
  2486.                         $notFound false;
  2487.                         foreach($filters as $spec_id => $filter_values){
  2488.                             unset($flatProdSpecsNotFiltered[$spec_id]);
  2489.                             if(!array_key_exists($spec_id$flatProdSpecs)){
  2490.                                 $notFound true;
  2491.                             }elseif(!in_array($flatProdSpecs[$spec_id], $filter_values)){
  2492.                                 $notFound true;
  2493.                             }
  2494.                         }
  2495.                         if(!$notFound){
  2496.                             $matchedSpecs[$pid] = $flatProdSpecs;
  2497.                             $matchedOtherSpecs[$pid] = $flatProdSpecsNotFiltered;
  2498.                         }
  2499.                     }
  2500.                 }else{
  2501.                     if(!empty($flatSpecs[$pid])){
  2502.                         $matchedOtherSpecs[$pid] = $flatSpecs[$pid];
  2503.                         $matchedSpecs[$pid] = $flatSpecs[$pid];
  2504.                     }
  2505.                     // No active filters, allow product
  2506.                 }
  2507.             }
  2508.         }
  2509.         // Find other filters against currently selected
  2510.         $specsAvailableCurrentFilter = [];
  2511.         foreach($matchedOtherSpecs as $pid => $s){
  2512.             foreach($s as $specid => $val){
  2513.                 if(!isset($specsAvailableCurrentFilter[$specid])){
  2514.                     $specsAvailableCurrentFilter[$specid] = [];
  2515.                 }
  2516.                 if(!in_array($val$specsAvailableCurrentFilter[$specid])){
  2517.                     $specsAvailableCurrentFilter[$specid][] = $val;
  2518.                 }
  2519.             }
  2520.         }
  2521.         $returnSpecs = [];
  2522.         $returnSpecs['all_specs'] = $allSpecs;
  2523.         $returnSpecs['enabled_specs'] = $specsAvailableCurrentFilter;
  2524.         $disabled_specs = [];
  2525.         foreach($allSpecs as $k => $v){
  2526.             if(isset($specsAvailableCurrentFilter[$k])){
  2527.                 $disabled_specs[$k] = array_diff($v$specsAvailableCurrentFilter[$k]);
  2528.                 if(empty($disabled_specs[$k])){
  2529.                     unset($disabled_specs[$k]);
  2530.                 }
  2531.             }
  2532.         }
  2533.         $returnSpecs['disabled_specs'] = $disabled_specs;
  2534.         $list = [];
  2535.         foreach($products as $product){
  2536.             $media = [];
  2537.             $media_size = [];
  2538.             $media_thumb = [];
  2539.             if($product->getMedia()->count()){
  2540.                 foreach($product->getMedia() as $m){
  2541.                     $media_size[] = ($m->getWidth() > $m->getHeight() ? $m->getHeight() : $m->getWidth());
  2542.                     $media[] = $m->getWebPath();
  2543.                     $media_thumb[] = $m->getWebPath('thumb');
  2544.                 }
  2545.             }else if($OriginalProduct->getMedia()->count()){
  2546.                 foreach($OriginalProduct->getMedia() as $m){
  2547.                     $media_size[] = ($m->getWidth() > $m->getHeight() ? $m->getHeight() : $m->getWidth());
  2548.                     $media[] = $m->getWebPath();
  2549.                     $media_thumb[] = $m->getWebPath('thumb');
  2550.                 }
  2551.             }
  2552.             $priceblock '';
  2553.             if($product->hasPromotion()){
  2554.                 $priceblock '
  2555.                 <div class="price-wrapper">
  2556.                     <span class="price sale" data-price="' $product->getRealPriceIncl($this->WebshopSettingsfalsefalse$this->WebshopCustomer) . '">' $this->WebshopSettings->getCurrency()->getFormat($product->getRealPriceIncl($this->WebshopSettingsfalsefalse$this->WebshopCustomer)) . '</span>
  2557.                 </div><div class="price-wrapper">
  2558.                     <span class="price old">' $this->WebshopSettings->getCurrency()->getFormat($product->getPriceIncl($this->WebshopSettingsfalsefalse$this->WebshopCustomer)) . '</span>
  2559.                 </div>
  2560.                 <span class="tax-suffix">' . ($this->WebshopSettings->getPriceDisplay() != 'excl' 'incl. BTW' 'excl. BTW') . '</span>
  2561.                 ';
  2562.                 // $priceblock = '<span class="col-sm col-md-6 price old">&euro; ' . number_format($product->getPriceIncl($this->WebshopSettings), 2, ',', '.') . '</span>
  2563.                 // <span class="col-sm col-md-6 price sale">&euro; ' . number_format($product->getRealPriceIncl($this->WebshopSettings), 2, ',', '.') . '</span>';
  2564.             }elseif(!empty($product->getPriceSale()) && $product->getPriceSale() > 0){
  2565.                 $priceblock '
  2566.                 <div class="price-wrapper">
  2567.                     <span class="price sale" data-price="' $product->getRealPriceIncl($this->WebshopSettingsfalsefalse$this->WebshopCustomer) . '">' $this->WebshopSettings->getCurrency()->getFormat($product->getRealPriceIncl($this->WebshopSettingsfalsefalse$this->WebshopCustomer)) . '</span>
  2568.                 </div><div class="price-wrapper">
  2569.                     <span class="price old">' $this->WebshopSettings->getCurrency()->getFormat($product->getPriceIncl($this->WebshopSettingsfalsefalse$this->WebshopCustomer)) . '</span>
  2570.                 </div>
  2571.                     <span class="tax-suffix">' . ($this->WebshopSettings->getPriceDisplay() != 'excl' 'incl. BTW' 'excl. BTW') . '</span>';
  2572.             }else{
  2573.                 $priceblock '<div class="price-wrapper">
  2574.                     <span class="price sale" data-price="' $product->getRealPriceIncl($this->WebshopSettingsfalsefalse$this->WebshopCustomer) . '">' $this->WebshopSettings->getCurrency()->getFormat($product->getRealPriceIncl($this->WebshopSettingsfalsefalse$this->WebshopCustomer)) . '</span>
  2575.                     <span class="tax-suffix">' . ($this->WebshopSettings->getPriceDisplay() != 'excl' 'incl. BTW' 'excl. BTW') . '</span>
  2576.                 </div>';
  2577.             }
  2578.             if($this->WebshopSettings->getShowStockIndicator()){
  2579.                 $priceblock .= '<div class="stock-label">';
  2580.                 $lowStock 2;
  2581.                 $mediumStock 6;
  2582.                 $noStock 0;
  2583.                 if (!empty($this->WebshopSettings->getStockLevels())) {
  2584.                     $stcklevel $this->WebshopSettings->getStockLevels();
  2585.                     if (isset($stcklevel['low'])) {
  2586.                         $lowStock $stcklevel['low'];
  2587.                     }
  2588.                     if (isset($stcklevel['medium'])) {
  2589.                         $mediumStock $stcklevel['medium'];
  2590.                     }
  2591.                 }
  2592.                 if($this->WebshopSettings->getPicqerChoice() == && !empty($this->WebshopSettings->getPicqerApikey()) && !empty($this->WebshopSettings->getPicqerUrl())){
  2593.                     $Picqer = new Picqer($this->WebshopSettings->getPicqerApikey(), $this->WebshopSettings->getPicqerUrl());
  2594.                     
  2595.                     if($this->WebshopSettings->getPicqerFulfillment()){
  2596.                         if(!empty($this->WebshopSettings->getPicqerFulfillmentId())){
  2597.                             $fulfilment_id $this->WebshopSettings->getPicqerFulfillmentId();
  2598.                         } else {
  2599.                             $fulfilment_id null;
  2600.                         }
  2601.                     } else {
  2602.                         $fulfilment_id null;
  2603.                     }
  2604.                     $stock $Picqer::checkStock($product$fulfilment_id);
  2605.                     if($stock !== "Product not found in Picqer" && $stock !== "Product empty"){
  2606.                         if ($stock == 0) {
  2607.                             $priceblock .= '<div class="text-danger"><i class="fa fa-times"></i> ' $this->trans('Niet op voorraad', [], 'webshop') . '</div>';
  2608.                         }elseif((int)$stock >= (int)$product->getOutOfStockQuantity() && $stock $lowStock){
  2609.                             $priceblock .= '<div class="text-warning"><i class="fa fa-circle"></i> ' $this->trans('Zeer beperkt op voorraad', [], 'webshop') . '</div>';
  2610.                         }elseif((int)$stock >= (int)$product->getOutOfStockQuantity() && $stock $mediumStock){
  2611.                             $priceblock .= '<div class="text-warning"><i class="fa fa-check"></i> ' $this->trans('Beperkt op voorraad', [], 'webshop') . '</div>';
  2612.                         }elseif((int)$stock >= (int)$product->getOutOfStockQuantity()){
  2613.                             $priceblock .= '<div class="text-success"><i class="fa fa-check"></i> ' $this->trans('Op voorraad', [], 'webshop') . '</div>';
  2614.                         }else{
  2615.                             $priceblock .= '<div class="text-danger"><i class="fa fa-times"></i> ' $this->trans('Niet op voorraad', [], 'webshop') . '</div>';
  2616.                         }
  2617.                         $priceblock .= '</div>';
  2618.                     } else {
  2619.                         if($product->canOrder() && $product->getStockAmount() < $lowStock){
  2620.                             $priceblock .= '<div class="text-warning"><i class="fa fa-circle"></i> ' $this->trans('Zeer beperkt op voorraad', [], 'webshop') . '</div>';
  2621.                         }elseif($product->canOrder() && $product->getStockAmount() < $mediumStock){
  2622.                             $priceblock .= '<div class="text-warning"><i class="fa fa-check"></i> ' $this->trans('Beperkt op voorraad', [], 'webshop') . '</div>';
  2623.                         }elseif($product->canOrder()){
  2624.                             $priceblock .= '<div class="text-success"><i class="fa fa-check"></i> ' $this->trans('Op voorraad', [], 'webshop') . '</div>';
  2625.                         }else{
  2626.                             $priceblock .= '<div class="text-danger"><i class="fa fa-times"></i> ' $this->trans('Niet op voorraad', [], 'webshop') . '</div>';
  2627.                         }
  2628.                         $priceblock .= '</div>';    
  2629.                     }
  2630.                 } else {
  2631.                     if($product->canOrder() && $product->getStockAmount() < $lowStock && $product->getStock()){
  2632.                         $priceblock .= '<div class="text-warning"><i class="fa fa-circle"></i> ' $this->trans('Zeer beperkt op voorraad', [], 'webshop') . '</div>';
  2633.                     }elseif($product->canOrder() && $product->getStockAmount() < $mediumStock && $product->getStock()){
  2634.                         $priceblock .= '<div class="text-warning"><i class="fa fa-check"></i> ' $this->trans('Beperkt op voorraad', [], 'webshop') . '</div>';
  2635.                     }elseif($product->canOrder()){
  2636.                         $priceblock .= '<div class="text-success"><i class="fa fa-check"></i> ' $this->trans('Op voorraad', [], 'webshop') . '</div>';
  2637.                     }else{
  2638.                         $priceblock .= '<div class="text-danger"><i class="fa fa-times"></i> ' $this->trans('Niet op voorraad', [], 'webshop') . '</div>';
  2639.                     }
  2640.                     $priceblock .= '</div>';
  2641.                 }
  2642.             }
  2643.             // Prepare specs
  2644.             $specs = [];
  2645.             $groups = [];
  2646.             foreach($product->getCategory() as $_Category){
  2647.                 foreach($_Category->getCategory()->getSpecGroups() as $_SpecGroup){
  2648.                     if(!$this->Webshop->getSpecGroups()->contains($_SpecGroup)) continue;
  2649.                     $groups[$_SpecGroup->getId()] = $_SpecGroup;
  2650.                 }
  2651.             }
  2652.             foreach($product->getSpecGroups() as $_SpecGroup){
  2653.                 if(!$this->Webshop->getSpecGroups()->contains($_SpecGroup)) continue;
  2654.                 $groups[$_SpecGroup->getId()] = $_SpecGroup;
  2655.             }
  2656.             // dump($groups);
  2657.             // $productsList = [];
  2658.             // $productsList[] = $product;
  2659.             // foreach($product->getLinkedProducts() as $P){
  2660.             //     $productsList[] = $P;
  2661.             // }
  2662.             // foreach($productsList as $product){
  2663.                 // dump($product->getLabel());
  2664.                 if(!empty($product->getWeight())){
  2665.                     $specs['weight'] = [
  2666.                         'label' => 'Gewicht',
  2667.                         'value' => ($product->getWeight() >= 1000 $product->getWeight() . ' Kg.' $product->getWeight() . ' g'),
  2668.                         'type' => 'text',
  2669.                     ];
  2670.                 }
  2671.                 foreach($groups as $_SpecGroup){
  2672.                     if(!$this->Webshop->getSpecGroups()->contains($_SpecGroup)) continue;
  2673.                     foreach($_SpecGroup->getSpecs() as $_Spec){
  2674.                         if ($_Spec->getOptDetail()) {
  2675.                             // if($_Spec->getCode() != 'opslag') continue;
  2676.                             if($_Spec->getHidden() == true) continue;
  2677.                             if($_Spec->getType() == 'dropdown'){
  2678.                                 $default = [];
  2679.                                 $available $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findBy(['spec' => $_Spec], ['position' => 'asc']);
  2680.                                 $SpecValues $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findValuesByProduct(
  2681.                                     $_Spec,
  2682.                                     $product
  2683.                                 );
  2684.                             }else{
  2685.                                 $default = [];
  2686.                                 $available null;
  2687.                                 $SpecValues $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findValuesByProduct(
  2688.                                     $_Spec,
  2689.                                     $product
  2690.                                 );
  2691.                             }
  2692.                             if($_Spec->getCode() == 'bereidingswijze'){
  2693.                                 continue;
  2694.                             }
  2695.                             if(!empty($SpecValues)){
  2696.                                 if(!is_array($SpecValues)){
  2697.                                     $SpecValues = [$SpecValues];
  2698.                                 }
  2699.                                 $flatValues = [];
  2700.                                 $flatHex = [];
  2701.                                 foreach($SpecValues as $Value){
  2702.                                     $flatValues[] = $Value->getValue();
  2703.                                     $flatHex[] = $Value->getHex();
  2704.                                 }
  2705.                                 // dump($SpecValues);
  2706.                                 if(isset($specs[$_Spec->getId()])){
  2707.                                     if(!is_array($specs[$_Spec->getId()]['value'])){
  2708.                                         $specs[$_Spec->getId()]['value'] = [$specs[$_Spec->getId()]['value']];
  2709.                                     }
  2710.                                         $specs[$_Spec->getId()]['value'] = array_unique(array_merge($specs[$_Spec->getId()]['value'], (!empty($flatValues) ? $flatValues $default)));
  2711.                                     // }
  2712.                                 }else{
  2713.                                     $specs[$_Spec->getId()] = [
  2714.                                         'label'    => $_Spec->getLabel(),
  2715.                                         'value'    => implode(', ', (!empty($flatValues) ? $flatValues $default)),
  2716.                                         'hex'    => implode(', ', (!empty($flatHex) ? $flatHex : [])),
  2717.                                         'type' => $_Spec->getType(),
  2718.                                     ];
  2719.                                 }
  2720.                             }
  2721.                         }
  2722.                     }
  2723.                 }
  2724.             // }
  2725.             if($product->getType() != 2){
  2726.                 if(!empty($product->getSku())){
  2727.                     $specs['sku'] = [
  2728.                         'label' => 'SKU',
  2729.                         'value' => $product->getSku(),
  2730.                         'type' => 'text',
  2731.                     ];
  2732.                 }
  2733.                 if(!empty($product->getEan())){
  2734.                     $specs['ean'] = [
  2735.                         'label' => 'EAN',
  2736.                         'value' => $product->getEan(),
  2737.                         'type' => 'text',
  2738.                     ];
  2739.                 }
  2740.             }
  2741.             $pdata = [
  2742.                 'id'          => $product->getId(),
  2743.                 'can_order'   => $product->canOrder(),
  2744.                 'label'       => $product->getLabel(),
  2745.                 'sub_label'   => $product->getLabelSub(),
  2746.                 'number'      => $product->getNumber(),
  2747.                 'ean'         => $product->getEan(),
  2748.                 'sku'         => $product->getSku(),
  2749.                 'intro'       => $product->getIntro(),
  2750.                 'intro_stripped'    => strip_tags($product->getIntro()),
  2751.                 'description' => $product->getDescription(),
  2752.                 'price'       => $product->getPriceIncl($this->WebshopSettings),
  2753.                 'priceblock'  => $priceblock,
  2754.                 'specs'       => $specs,
  2755.                 'media'       => $media,
  2756.                 'media_size'  => $media_size,
  2757.                 'media_thumb' => $media_thumb,
  2758.             ];
  2759.             $list[] = $pdata;
  2760.         }
  2761.         return new JsonResponse(['specs' => $returnSpecs'keyValue' => $keyValue'spec_filter' => $config_spec_filter'spec_values' => $config_spec_filter_values'options' => $list]);
  2762.     }
  2763.     /**
  2764.      * @Route("/compare", name="webshop_compare")
  2765.      * @Template()
  2766.      */
  2767.     public function compareAction(Request $request)
  2768.     {
  2769.         $this->init($request);
  2770.         $Webshop $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($this->language$this->Settings);
  2771.         $Settings $Webshop->getSettings();
  2772.         $Page $Settings->getPage();
  2773.         if(empty($Page)){
  2774.             $Page = new \App\CmsBundle\Entity\Page();
  2775.             $Page->setOptionBreadcrumbs(false);
  2776.             $Page->setOptionSubnavigation(false);
  2777.             $Page->setOptionTitle(false);
  2778.         }
  2779.         $Page->setTitle($this->trans('Vergelijken', [], 'webshop'));
  2780.         $metatags       $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getBySystem(0, (int)$Page->getId(), true);
  2781.         $systemMetatags $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getBySystem(1falsefalse);
  2782.         $specData = [];
  2783.         $products = [];
  2784.         if(!empty($_GET['compare'])){
  2785.             foreach($_GET['compare'] as $id){
  2786.                 $p $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($id);
  2787.                 $products[] = $p;
  2788.                 foreach($p->getSpecValues() as $v){
  2789.                     $spec $v->getSpec();
  2790.                     if(!empty($spec)){
  2791.                         $specData[$spec->getLabel()][$id] = [
  2792.                             'value' => $v->getValue(),
  2793.                             'hex' => $v->getHex(),
  2794.                             'type' => $spec->getType(),
  2795.                         ];
  2796.                     }
  2797.                 }
  2798.             }
  2799.         }
  2800.         return $this->attributes([
  2801.             'Page'            => $Page,
  2802.             'metatags'        => $metatags,
  2803.             'systemMetatags'  => $systemMetatags,
  2804.             'WebshopSettings' => $Settings,
  2805.             'products'        => $products,
  2806.             'specData'        => $specData,
  2807.         ]);
  2808.     }
  2809.     /**
  2810.      * @Route("/webshop-main/reviews/{product_id}/{page}", name="webshop_reviews")
  2811.      * @Template()
  2812.      */
  2813.     public function reviewsAction(Request $request$product_id$page 1)
  2814.     {
  2815.         $this->init($request);
  2816.         $perpage 3;
  2817.         $Product $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($product_id);
  2818.         $moderate $this->WebshopSettings->getModerateReviews();
  2819.         $reviews_count $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->countReviews($product_id$page$perpage$moderate);
  2820.         $pages         ceil($reviews_count $perpage);
  2821.         $reviews       $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->fetchReviews($product_id$page$perpage$moderate);
  2822.         return ['reviews' => $reviews'reviews_count' => $reviews_count'Product' => $Product'product_id' => $product_id'WebshopSettings' => $this->WebshopSettings'User' => $this->getUser(), 'page' => $page'pages' => $pages];
  2823.     }
  2824.     /**
  2825.      * @Route("/profile/orders", name="profile_orders")
  2826.      * @Template()
  2827.      */
  2828.     public function ordersAction(Request $request)
  2829.     {
  2830.         $this->init($request);
  2831.         $Webshop $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($this->language$this->Settings);
  2832.         // $breadcrumbs = $this->get("white_october_breadcrumbs");
  2833.         // $breadcrumbs->addRouteItem($Webshop->getLabel(), "homepage");
  2834.         // $this->breadcrumbs->addRouteItem('Mijn Profiel', "profile");
  2835.         $this->breadcrumbs->addRouteItem('Mijn Bestellingen'"profile_orders");
  2836.         $orders $this->getDoctrine()->getRepository('TrinityWebshopBundle:Order')->findBy(array(
  2837.             'user' => $this->getUser(),
  2838.             'webshop' => $Webshop
  2839.         ), array(
  2840.             'date' => 'desc'
  2841.         ));
  2842.         if(!empty($_GET['pay'])){
  2843.             $Order $this->getDoctrine()->getRepository('TrinityWebshopBundle:Order')->find($_GET['pay']);
  2844.             $mollie = new \Mollie_API_Client;
  2845.             $mollie->setApiKey(($this->containerInterface->get('kernel')->getEnvironment() == 'dev' self::MOLLIE_API_DEV self::MOLLIE_API_LIVE));
  2846.             $Payment $mollie->payments->create(array(
  2847.                 "amount"      => $Order->getTotalPrice(),
  2848.                 "description" => "Order " $Order->getHash(),
  2849.                 "redirectUrl" => $this->generateUrl('cart_finish', array('hash' => $Order->getHash()), UrlGeneratorInterface::ABSOLUTE_URL),
  2850.                 "method"      => $Order->getPayment(),
  2851.             ));
  2852.             $em $this->getDoctrine()->getManager();
  2853.             $Order->setPaymentId($Payment->id);
  2854.             $Order->setPaymentStatus($Payment->status);
  2855.             $em->persist($Order);
  2856.             // Payment history
  2857.             $OrderPayment = new OrderPayment();
  2858.             $OrderPayment->setOrder($Order);
  2859.             $OrderPayment->setDate(new \Datetime());
  2860.             $OrderPayment->setPaymentId($Payment->id);
  2861.             $OrderPayment->setPaymentStatus($Payment->status);
  2862.             // Save order
  2863.             // Add to payment history
  2864.             $em->persist($OrderPayment);
  2865.             // Remove cart
  2866.             // $em->remove($Cart);
  2867.             $em->flush();
  2868.             header('Location:' $Payment->links->paymentUrl);
  2869.             exit;
  2870.         }
  2871.         return $this->attributes(['orders' => $orders]);
  2872.     }
  2873.     /**
  2874.      * @Route("/profile/orders/download-invoice/{id}", name="profile_orders_download_invoice", requirements={"id": "\d+"})
  2875.      */
  2876.     public function downloadInvoiceAction(Request $request$id)
  2877.     {
  2878.         parent::init($request);
  2879.         $Webshop $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($this->language$this->Settings);
  2880.         $Settings $Webshop->getSettings();
  2881.         $Invoice  $this->getDoctrine()->getRepository('TrinityWebshopBundle:Invoice')->find($id);
  2882.         if($Invoice && $Invoice->getOrder()->getUser()->getUser() == $this->getUser()){
  2883.             $tplPath '@TrinityWebshop/invoice_template.html.twig';
  2884.             $customTplPath preg_replace('/src\/.*?$/''templates/invoice_template.html.twig'__DIR__);
  2885.             if(file_exists($customTplPath)){
  2886.                 $tplPath '/invoice_template.html.twig';
  2887.             }
  2888.             $tpl $this->renderView($tplPath$this->attributes([
  2889.                 'Invoice'         => $Invoice,
  2890.             ]));
  2891.             $html $tpl;
  2892.             $pdf = new Pdf();
  2893.             // $pdf->setBrd(true);
  2894.             $pdf->setInvoice($Invoice);
  2895.             $pdf->setTranslator($this->translator);
  2896.             $pdf->setSettings($this->Settings);
  2897.             $pdf->setWebshopSettings($Settings);
  2898.             $pdf->setTitle($this->trans('FACTUUR #', [], 'webshop'$Webshop->getLanguage()->getLocale()) . $Invoice->getId());
  2899.             $pdf->setTitleRight($Invoice->getDate()->format('d-m-Y H:i:s'));
  2900.             // $pdf->create();
  2901.             $pdf->AddPage();
  2902.             $pdf->writeHTML($htmltruefalsetruefalse'');
  2903.             $pdf->Output($this->doSluggify($this->Settings->getLabel()) . '_' $this->trans('Factuur', [], 'webshop'$Webshop->getLanguage()->getLocale()) . '_' $Invoice->getId() . '.pdf''D');
  2904.             exit;
  2905.         }
  2906.         header('Location:/'); exit;
  2907.     }
  2908.     /**
  2909.      * @Route("/profile/orders/download-credit/{id}", name="profile_orders_download_credit", requirements={"id": "\d+"})
  2910.      */
  2911.     public function downloadCreditAction(Request $request$id)
  2912.     {
  2913.         parent::init($request);
  2914.         $Webshop $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($this->language$this->Settings);
  2915.         $Settings $Webshop->getSettings();
  2916.         $CmsSettings $Webshop->getCmsSettings();
  2917.         $language $CmsSettings->getLanguage();
  2918.         $Credit  $this->getDoctrine()->getRepository('TrinityWebshopBundle:Credit')->find($id);
  2919.         if($Credit && $Credit->getOrder()->getUser()->getUser() == $this->getUser()){
  2920.             $tplPath '@TrinityWebshop/credit_template.html.twig';
  2921.             $customTplPath preg_replace('/src\/.*?$/''templates/credit_template.html.twig'__DIR__);
  2922.             if(file_exists($customTplPath)){
  2923.                 $tplPath '/credit_template.html.twig';
  2924.             }
  2925.             $tpl $this->renderView($tplPath$this->attributes([
  2926.                 'Credit'         => $Credit,
  2927.                 'sitename' => $CmsSettings->getLabel(),
  2928.                 'locale'          => $language->getLocale(),
  2929.             ]));
  2930.             $html $tpl;
  2931.             $pdf = new Pdf();
  2932.             // $pdf->setBrd(true);
  2933.             $pdf->setCredit($Credit);
  2934.             $pdf->setTranslator($this->translator);
  2935.             $pdf->setSettings($this->Settings);
  2936.             $pdf->setWebshopSettings($Settings);
  2937.             $pdf->setTitle($this->trans('CREDITFACTUUR #', [], 'webshop'$Webshop->getLanguage()->getLocale()) . $Credit->getId());
  2938.             $pdf->setTitleRight($Credit->getDate()->format('d-m-Y H:i:s'));
  2939.             // $pdf->create();
  2940.             $pdf->AddPage();
  2941.             $pdf->writeHTML($htmltruefalsetruefalse'');
  2942.             $pdf->Output($this->doSluggify($this->Settings->getLabel()) . '_' $this->trans('Creditfactuur', [], 'webshop'$Webshop->getLanguage()->getLocale()) . '_' $Credit->getId() . '.pdf''D');
  2943.             exit;
  2944.         }
  2945.         header('Location:/'); exit;
  2946.     }
  2947.     private function doSluggify($str$replace=array(), $delimiter='-')
  2948.     {
  2949.         $str strtolower($str);
  2950.         if( !empty($replace) ) {
  2951.             $str str_replace((array)$replace' '$str);
  2952.         }
  2953.         $slugify = new \Cocur\Slugify\Slugify();
  2954.         return $slugify->slugify($str$delimiter);
  2955.     }
  2956.     /**
  2957.      * @Route("/profile/orders/view/{id}", name="profile_orders_view")
  2958.      * @Template()
  2959.      */
  2960.     public function orderViewAction(Request $request$id)
  2961.     {
  2962.         $this->init($request);
  2963.         $order $this->getDoctrine()->getRepository('TrinityWebshopBundle:Order')->find($id);
  2964.         $tax = [];
  2965.         $tax_total 0;
  2966.         /*if($order->getTotalDelivery() > 0){
  2967.             $tax[21] = (($order->getTotalDelivery() / 100) * 21);
  2968.         }*/
  2969.         if(!empty($order->getProducts())){
  2970.             foreach($order->getProducts() as $Product){
  2971.                 $Tax $Product->getProduct()->getTax();
  2972.                 if(empty($Tax)){
  2973.                     $Tax $this->getDoctrine()->getRepository('TrinityWebshopBundle:Tax')->findOneByPercent(21);
  2974.                 }
  2975.                 $percent $Tax->getPercent();
  2976.                 $price $Product->getTotalPrice();
  2977.                 // dump($price);
  2978.                 $_tax = (($price 100) * $percent);
  2979.                 if(!isset($tax[$percent])) $tax[$percent] = 0;
  2980.                 $tax[$percent] += $_tax;
  2981.                 $tax_total += $_tax;
  2982.             }
  2983.         }
  2984.         $delivery $order->getTotalDelivery();
  2985.         if(!empty($delivery)){
  2986.             $t = (($delivery 100) * 21);
  2987.             $tax[21] += $t;
  2988.             // $tax_total += $t;
  2989.         }
  2990.         return [
  2991.             'order' => $order,
  2992.             'tax' => $tax,
  2993.             'tax_total' => $tax_total
  2994.         ];
  2995.     }
  2996.     /**
  2997.      * @Route("/dropfilter/{specid}", name="drop_filter")
  2998.      * @Template()
  2999.      */
  3000.     public function dropFilter(Request $request$specid null){
  3001.         $this->init($request);
  3002.         if($specid == 'all'){
  3003.             $this->get('session')->set('ecomm_spec_query''');
  3004.             $this->get('session')->set('ecomm_spec_plate''');
  3005.             $this->get('session')->set('ecomm_spec_filter', []);
  3006.             return new JsonResponse([]);
  3007.         }
  3008.         $q '';
  3009.         if(preg_match('/_/'$specid)){
  3010.             $specid explode('_'$specid);
  3011.             $q explode(' '$this->get('session')->get('ecomm_spec_query'));
  3012.             foreach($q as $k => $v){
  3013.                 if($specid[1] == $k || empty($v)){
  3014.                     unset($q[$k]);
  3015.                 }
  3016.             }
  3017.             $q implode(' '$q);
  3018.             $this->get('session')->set('ecomm_spec_query'$q);
  3019.         }else{
  3020.             if($specid == 'q'){
  3021.                 $this->get('session')->set('ecomm_spec_query''');
  3022.             }else{
  3023.                 $filters $this->get('session')->get('ecomm_spec_filter');
  3024.                 if(!empty($filters)){
  3025.                     foreach($filters as $k => $v){
  3026.                         $Spec $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->findOneByLabel($k);
  3027.                         if($Spec){
  3028.                             if($Spec->getId() == $specid){
  3029.                                 unset($filters[$k]);
  3030.                             }
  3031.                         }
  3032.                     }
  3033.                 }
  3034.                 $this->get('session')->set('ecomm_spec_filter'$filters);
  3035.             }
  3036.         }
  3037.         return new JsonResponse(['q' => $q]);
  3038.     }
  3039.     /**
  3040.      * @Route("/profile/list/{listid}/{articleid}", name="profile_list")
  3041.      * @Template()
  3042.      */
  3043.     public function listAction(Request $request$listid 0$articleid null)
  3044.     {
  3045.         $this->init($request);
  3046.         $Product $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($articleid);
  3047.         $addedList false;
  3048.         $savedList false;
  3049.         $alreadyAdded false;
  3050.         $WebshopUser $this->getDoctrine()->getRepository('TrinityWebshopBundle:User')->findOneByUser($this->getUser());
  3051.         if(!empty($_POST['listid'])){
  3052.             if($_POST['listid'] == 'new'){
  3053.                 $ProductList = new \App\Trinity\WebshopBundle\Entity\ProductList();
  3054.                 $ProductList->setUser($WebshopUser);
  3055.                 $ProductList->setLabel($_POST['newList']);
  3056.             }else{
  3057.                 $ProductList $this->getDoctrine()->getRepository('TrinityWebshopBundle:ProductList')->find($_POST['listid']);
  3058.             }
  3059.             if($ProductList->hasProduct($Product)){
  3060.                 $alreadyAdded true;
  3061.             }else{
  3062.                 $Product->addProductlist($ProductList);
  3063.                 $em $this->getDoctrine()->getManager();
  3064.                 $em->persist($Product);
  3065.                 $em->persist($ProductList);
  3066.                 $em->flush();
  3067.                 if(empty($_POST['listid'])){
  3068.                     $addedList true;
  3069.                 }else{
  3070.                     $savedList true;
  3071.                 }
  3072.             }
  3073.         }
  3074.         $ProductLists $this->getDoctrine()->getRepository('TrinityWebshopBundle:ProductList')->findByUser($WebshopUser);
  3075.         return [
  3076.             'Product' => $Product,
  3077.             'alreadyAdded' => $alreadyAdded,
  3078.             'addedList' => $addedList,
  3079.             'savedList' => $savedList,
  3080.             'lists' => $ProductLists,
  3081.             'newList' => (!empty($_POST['newList']) ? $_POST['newList'] : '')
  3082.         ];
  3083.     }
  3084.     /**
  3085.      * @Route("/profile/orders/download/{id}", name="profile_orders_download")
  3086.      * @Template()
  3087.      */
  3088.     public function downloadAction(Request $request$id)
  3089.     {
  3090.         $this->init($request);
  3091.         $Order $this->getDoctrine()->getRepository('TrinityWebshopBundle:Order')->find($id);
  3092.         if($Order->getUser()->getId() != $this->getUser()->getId() && !$this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')){
  3093.             throw new AccessDeniedHttpException('Invalid order');
  3094.         }
  3095.         \App\Trinity\WebshopBundle\Classes\Invoice::generate($request$Order$this->container'D');
  3096.     }
  3097.     /**
  3098.      * @Route("/ajax/products/{webshopid}", name="products")
  3099.      */
  3100.     public function productsAction(Request $requestEnvironment $twigint $webshopid 0)
  3101.     {
  3102.         $this->init($request);
  3103.         if($webshopid 0){
  3104.             $Webshop $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->findOneBy(['id' => $webshopid]);
  3105.             if(empty($Webshop)){
  3106.                 $Webshop $this->Webshop;
  3107.             }
  3108.         }else{
  3109.             $Webshop $this->Webshop;
  3110.         }
  3111.         $Settings $Webshop->getSettings();
  3112.         $em $this->getDoctrine()->getManager();
  3113.         $return = ['count' => 0'products' => [], 'checked' => []];
  3114.         $postValues $_POST;
  3115.         if(!empty($_GET['c'])) $postValues $_GET;
  3116.         if(!isset($postValues['filter'])){
  3117.             $postValues['filter'] = [];
  3118.         }
  3119.         $this->get('session')->set('ecomm_spec_plate''');
  3120.         $this->get('session')->set('ecomm_spec_filter', []);
  3121.         // Hardwired for licenseplate check
  3122.         if(!empty($postValues['licenseplate'])){
  3123.             $api_url 'https://services.onderdelenlijn.nl/parts/v7.asmx?WSDL';
  3124.             $user 'info@beyonit.nl';
  3125.             $pass 'fUAJT6!XP';
  3126.             $Webshop $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($this->language$this->Settings);
  3127.             
  3128.             $SOAP_LOCATION_APP $api_url;
  3129.             $soapClient = new \SoapClient($SOAP_LOCATION_APP, ["trace" => 1"exception" => 0'cache_wsdl' => WSDL_CACHE_NONE'soap_version' => SOAP_1_2]);
  3130.             $soapMessage = [
  3131.                 'Credentials' => [
  3132.                     'Username' => $user,
  3133.                     'Password' => $pass,
  3134.                 ],
  3135.                 'Parameters' => [
  3136.                     'Culture' => "NL",
  3137.                     'TviRequest' => [
  3138.                         'Type' => 'LicensePlate',
  3139.                         'Value' => $postValues['licenseplate']
  3140.                     ]
  3141.                 ]
  3142.             ];
  3143.             $soapResult $soapClient->TviData($soapMessage);
  3144.             $res json_decode(json_encode($soapResult), true);
  3145.             if(!empty($res["TviDataResult"]["Result"])){
  3146.                 $array $res["TviDataResult"]["Result"];
  3147.                 /*if(isset($array["Aldoc"]["Models"]["AldocModel"]["Images"])){
  3148.                     $img_url = str_replace('demo.', '', $array["Aldoc"]["Models"]["AldocModel"]["Images"]["Root"]["Small"]) . $array["Aldoc"]["Models"]["AldocModel"]["Images"]["Filenames"]["string"][0];
  3149.                     dump($img_url);
  3150.                 } else {
  3151.                     dump("No Images");
  3152.                 }*/
  3153.                 $filters = [];
  3154.                 $model = (!empty($array["Basic"]["MakeModel"]["MakeName"]) ? $array["Basic"]["MakeModel"]["MakeName"] : null);
  3155.                 $type  = (!empty($array["Basic"]["MakeModel"]["ModelName"]) ? $array["Basic"]["MakeModel"]["ModelName"] : null);
  3156.                 $year  = (!empty($array["Basic"]["Constructed"]['Year']) ? $array["Basic"]["Constructed"]['Year'] : null);
  3157.                 $month = (!empty($array["Basic"]["Constructed"]['Month']) ? $array["Basic"]["Constructed"]['Month'] : null);
  3158.                 if($model){ $filters['Merk']      = $model; }
  3159.                 if($type){ $filters['Model']      = $type; }
  3160.                 if($year){ $filters['Bouwjaar']   = $year; }
  3161.                 // if($month){ $filters['Bouwmaand'] = $month; }
  3162.             }else{
  3163.                 // Fallback
  3164.                 $filters = [];
  3165.                 $model 'Mazda';
  3166.                 $type  'CX-3.';
  3167.                 $year  '2015';
  3168.                 $month '6';
  3169.                 if($model){ $filters['Merk']      = $model; }
  3170.                 if($type){ $filters['Model']      = $type; }
  3171.                 if($year){ $filters['Bouwjaar']   = $year; }
  3172.                 // if($month){ $filters['Bouwmaand'] = $month; }
  3173.             }
  3174.             $this->get('session')->set('ecomm_spec_plate'$postValues['licenseplate']);
  3175.             $this->get('session')->set('ecomm_spec_filter'$filters);
  3176.             if(!empty($filters)){
  3177.                 foreach($filters as $k => $v){
  3178.                     $postValues['spec'][$k] = $v;
  3179.                 }
  3180.             }
  3181.         }
  3182.         $filters_visual = [];
  3183.         if(!empty($postValues['spec'])){
  3184.             foreach($postValues['spec'] as $specLabel => $value){
  3185.                 if(!preg_match('/Alle/'$value)){
  3186.                     // TMP IGNORE
  3187.                     // if(in_array($specLabel, ['/Model', 'Bouwjaar', 'Bouwmaand'])) continue;
  3188.                     $Spec $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->findOneBy(['label' => $specLabel]);
  3189.                     if(!empty($Spec) && !empty($value)){
  3190.                         $postValues['filter'][$Spec->getId()] = $value;
  3191.                         $filters_visual[$Spec->getId()] = $value;
  3192.                     }
  3193.                 }
  3194.             }
  3195.         }
  3196.         unset($postValues['spec']);
  3197.         /*if(!empty($postValues['filter'])){
  3198.             foreach($postValues['filter'] as $id => $values){
  3199.                 foreach($values as $ind => $value){
  3200.                     if(strpos($value, '-') !== false){
  3201.                         unset($postValues['filter'][$id][$ind]);
  3202.                         $value = explode('-', $value);
  3203.                         foreach($value as $v){
  3204.                             $postValues['filter'][$id][] = $v;
  3205.                         }
  3206.                     }
  3207.                 }
  3208.                 if(empty($postValues['filter'][$id])){
  3209.                     unset($postValues['filter'][$id]);
  3210.                 }
  3211.             }
  3212.         }*/
  3213.         // die( "<pre>" . print_r( $_POST, 1 ) . "</pre>" );
  3214.         $filters = [
  3215.             // 'category' => $Category,
  3216.             // 'q' => 'red',
  3217.             /*'filters' => [
  3218.                 7 => [
  3219.                     'Nederland',
  3220.                     'Frankrijk',
  3221.                 ]
  3222.             ]*/
  3223.             'visible' => true
  3224.         ];
  3225.         if(!empty($postValues['c'])){
  3226.             $filters['category'] = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->find($postValues['c']);
  3227.         }
  3228.         if(!empty($postValues['q'])){
  3229.             // $this->get('session')->set('ecomm_spec_query', $postValues['q']);
  3230.             foreach(explode(' '$postValues['q']) as $q){
  3231.                 if(!isset($filters_visual['q'])){
  3232.                     $filters_visual['q'] = [];
  3233.                 }
  3234.                 $filters_visual['q'][] = '<strong>' $this->trans('Zoeken', [], 'webshop') . ':</strong> ' $q;
  3235.             }
  3236.             
  3237.             if ($Settings->getSearchMode() && $Settings->getSearchMode() == 'or')
  3238.             {
  3239.                 /*if(is_string($postValues['q']) && preg_match('/^([a-zA-Z]+)(\d+)$/', $postValues['q'], $m)){
  3240.                     $filters['q'] = [];
  3241.                     $filters['qo'] = [];
  3242.                     // if(strlen($m[1]) > 2){
  3243.                         $filters['q'][] = $m[1];
  3244.                     // }
  3245.                     // if(strlen($m[2]) > 2){
  3246.                         $filters['q'][] = $m[2];
  3247.                     // }
  3248.                     $filters['qo'][] = $m[1] . $m[2];
  3249.                     $filters['qo'][] = $m[1] . '-' . $m[2];
  3250.                     $filters['qo'][] = $m[1] . ' ' . $m[2];
  3251.                 }else{*/
  3252.                     $f explode(' '$postValues['q']);
  3253.                     $filters['q'] = [];
  3254.                     $filters['qo'] = [];
  3255.                     foreach($f as $v){
  3256.                         // if(strlen($v) > 2){
  3257.                             $filters['q'][] = $v;
  3258.                         // }
  3259.                     }
  3260.                     $filters['qo'][] = implode($f'-');
  3261.                     $filters['qo'][] = implode($f' ');
  3262.                 //}
  3263.             } else { 
  3264.                 $filters['q'] = explode(' '$postValues['q']);
  3265.             }
  3266.         }
  3267.         if(!empty($postValues['limit'])){
  3268.             $filters['limit'] = [
  3269.                 'start' => (!empty($postValues['start']) ? (int)$postValues['start'] : 0),
  3270.                 'limit' => $postValues['limit'],
  3271.             ];
  3272.         }
  3273.         if(!empty($postValues['page'])){
  3274.             $filters['page'] = (int)$postValues['page'];
  3275.         }else{
  3276.             $filters['page'] = 1;
  3277.         }
  3278.         /*if(!empty($postValues['order'])){
  3279.             $filters['order'] = $postValues['order'];
  3280.         }*/
  3281.         if(!empty($postValues['price']) && isset($postValues['price']['min']) && isset($postValues['price']['max'])){
  3282.             $filters['price'] = [(float)$postValues['price']['min'], (float)$postValues['price']['max']];
  3283.             $filters['ignore_pricing'] = ((int)$postValues['ignore_pricing'] == 1);
  3284.         }
  3285.         if(!empty($postValues['filter'])){
  3286.             foreach($postValues['filter'] as $spec_id => $values){
  3287.                 if(!is_array($values)){
  3288.                     $postValues['filter'][$spec_id] = [$values];
  3289.                 }
  3290.             }
  3291.         }
  3292.         $spec_value_link = [];
  3293.         
  3294.         if(!empty($postValues['filter'])){
  3295.             foreach($postValues['filter'] as $specid => $f){
  3296.                 $return['checked'] = array_merge($return['checked'], $f);
  3297.                 $spec_value_link[] = [$specid$f];
  3298.             }
  3299.             $filters['filters'] = $postValues['filter'];
  3300.         }
  3301.         foreach($spec_value_link as $k => $r){
  3302.             $Spec $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->find($r[0]);
  3303.             if(!empty($Spec)){
  3304.                 foreach($r[1] as $v){
  3305.                     $allow true;
  3306.                     if(is_array($v)){
  3307.                         $allow false;
  3308.                         if(!empty($v[0]) && !empty($v[1])){
  3309.                             $allow true;
  3310.                             $v implode(' - '$v);
  3311.                         }
  3312.                     }
  3313.                     if($allow){
  3314.                         $filters_visual[$Spec->getId()] = '<strong>' . ($Spec->getLabel() == 'Model compatibiliteit' 'Bouwjaar' $Spec->getLabel()) . ':</strong> ' $v;
  3315.                     }
  3316.                 }
  3317.             }
  3318.         }
  3319.         //$Webshop = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($this->language, $this->Settings);
  3320. // dump($filters);
  3321.         
  3322.         if(!empty($postValues['order'])){
  3323.             $postValues['order_full'] = $postValues['order'];
  3324.             if(preg_match('/^price_/'$postValues['order_full'])){
  3325.                 $dir preg_replace('/^.*? (.*?)$/''$1'$postValues['order_full']);
  3326.                 $postValues['order_full'] = 'sell_price_incl ' $dir;
  3327.                 // $postValues['order_full'] = 'price_sale ' . $dir . ', p.' . $postValues['order_full'];
  3328.                 // die( "<pre>" . print_r( $postValues['order_full'], 1 ) . "</pre>" );
  3329.             }
  3330.         }
  3331.         $perPage $Settings->getPerPage();
  3332.         if(!empty($postValues['pp'])){
  3333.             $perPage $postValues['pp'];
  3334.         }
  3335.         $sort = (!empty($postValues['order_full']) ? $postValues['order_full'] : null);
  3336.         if(preg_match('/price_incl.*?(asc|desc)/'$sort$m)){
  3337.             $sort 'sell_price ' $m[1];
  3338.         }
  3339.         $filters['sliders'] = [];
  3340.         $filters['sliders_range'] = [];
  3341.         if(!empty($filters['filters'])){
  3342.             foreach($filters['filters'] as $s_id => $f_values){
  3343.                 if(is_numeric($s_id)){
  3344.                     // dump($s_id);
  3345.                     $Spec $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->find($s_id);
  3346.                     // dump($Spec);die();
  3347.                     if($Spec->getType() == 'slider'){
  3348.                         $filters['sliders'][] = $s_id;
  3349.                     }
  3350.                     if($Spec->getType() == 'slider2'){
  3351.                         $filters['sliders_range'][] = $s_id;
  3352.                     }
  3353.                 }
  3354.             }
  3355.         }
  3356.         $filters['tags'] = [];
  3357.         if(!empty($postValues['tags']) && is_array($postValues['tags'])){
  3358.             $filters['tags'] = $postValues['tags'];
  3359.         }
  3360.         $products_data $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->search($Webshop$filters$sort'asc', ($this->WebshopSettings->getPagination() == 'none'), false1$perPage0true);
  3361.         if(empty($products_data['total']) && !empty($filters['category'])){
  3362.             // Try to find by underlying categories
  3363.             if($filters['category']->getChildren()->count()){
  3364.                 $catlist = [];
  3365.                 foreach($filters['category']->getChildren() as $c){
  3366.                     $catlist[] = $c->getId();
  3367.                 }
  3368.                 $filters['category'] = $catlist;
  3369.                 $products_data $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->search($Webshop$filters$sort'asc', ($Settings->getPagination() == 'none'), false, (!empty($_GET['page']) && is_numeric($_GET['page']) ? $_GET['page'] : 1), $perPage0true);
  3370.             }
  3371.         }
  3372.         // dump($products_data);die();
  3373.         $products $products_data['results'];
  3374.         $product_return = [];
  3375.         $product_return_childs = [];
  3376.         $product_list = [];
  3377.         // dump($products);
  3378.         // die();
  3379.         $prices = [];
  3380.         foreach ($products as $product) {
  3381.             $p $product->getRealPriceIncl($Settings);
  3382.             // if(!empty($p)){
  3383.                 $prices[] = $p;
  3384.             // }
  3385.         }
  3386.         if(!empty($prices)){
  3387.             $priceRange = [min($prices), max($prices)];
  3388.         }else{
  3389.             $priceRange = [00];
  3390.         }
  3391.         $return['count'] = count($products);
  3392.         $return['priceRange'] = $priceRange;
  3393.         $defaultImage $Settings->getDefaultProductImageObject();
  3394.         foreach($products as $Product){
  3395.             $Category null;
  3396.             if(!empty($Product->getCategory())){
  3397.                 foreach($Product->getCategory() as $_Category){
  3398.                     $Category $_Category;
  3399.                 }
  3400.             }
  3401.             $now = new \DateTime();
  3402.             $relatedChild null;
  3403.             $childProd null;
  3404.             $childProductSale false;
  3405.             $children = [];
  3406.             foreach($Product->getLinkedProducts() as $p){
  3407.                 $media $Product->getMedia()->first();
  3408.                 $secondMedia null;
  3409.                 if(empty($media)){
  3410.                     $media $defaultImage;
  3411.                 } else if ($this->WebshopSettings->getImageSwap() and $Product->getMedia()->count() >= 2){
  3412.                     $secondMedia $Product->getMedia()->next();
  3413.                 }
  3414.                 if(!empty($filters['category'])){
  3415.                     $Category $filters['category'];
  3416.                 }
  3417.                 if($Category instanceof \App\Trinity\WebshopBundle\Entity\CategoryProduct){
  3418.                     $Category $Category->getCategory();
  3419.                 }
  3420.                 $matchCount 0;
  3421.                 if(!empty($filters['filters'])){
  3422.                     foreach($p->getSpecValues() as $sv){
  3423.                         if($sv->getSpec()){
  3424.                             if(array_key_exists($sv->getSpec()->getId(), $filters['filters'])){
  3425.                                 $f $filters['filters'][$sv->getSpec()->getId()];
  3426.                                 if(in_array($sv->getValue(), $f)){
  3427.                                     $matchCount++;
  3428.                                 }
  3429.                             }
  3430.                         }
  3431.                     }
  3432.                 }
  3433.                 if(!empty($filters['filters']) && $matchCount >= count($filters['filters'])){
  3434.                     $relatedChild $p;
  3435.                 }
  3436.                 $product_list[] = $p;
  3437.                 $childProd = (float)$p->getRealPriceIncl($Settings);
  3438.                 if($p->hasPromotion() || (!empty($p->getPriceSale()) && $p->getPriceSale() > 0)){
  3439.                     $childProductSale true;
  3440.                 }
  3441.                 $prod = [
  3442.                     'id'               => $p->getId(),
  3443.                     'label'            => ($p->getBrand() ? $p->getBrand()->getLabel() . ' ' '') . $p->getLabel(),
  3444.                     'label_sub'        => $p->getLabelSub(),
  3445.                     'intro'            => $p->getIntro(),
  3446.                     'intro_stripped'   => strip_tags($p->getIntro()),
  3447.                     'number'           => $p->getNumber(),
  3448.                     'price'            => $Settings->getCurrency()->getFormat($p->getPriceIncl($Settings)),
  3449.                     'real_price'       => $Settings->getCurrency()->getFormat($p->getRealPriceIncl($Settings)),
  3450.                     'image'            => null,
  3451.                     'isNew'            => ($p->getNew() && (($p->getNewFrom() <= $now && $p->getNewTill() >= $now) || (empty($p->getNewTill()) && empty($p->getNewFrom())))),
  3452.                     'exclusive'        => $p->getExclusive(),
  3453.                     'priceSell'        => (float)$p->getSellPrice(),
  3454.                     'priceSellIncl'    => (float)$p->getSellPriceIncl(),
  3455.                     'priceSale'        => $p->getPriceSale(),
  3456.                     'priceSaleFloat'   => (float)$p->getPriceSale(),
  3457.                     'priceSalePercent' => $p->getPriceSalePercent(),
  3458.                     'category_id'      => $Category->getId(),
  3459.                     'hasSale'          => ((float)$p->getPriceSale() > || $p->hasPromotion()),
  3460.                     'hasPromotion'     => $p->hasPromotion(true),
  3461.                     'hasCombi'         => $p->hasCombi(),
  3462.                     'canOrder'         => $p->canOrder(),
  3463.                     'isChild'          => true,
  3464.                     'hasMedia'         => !empty($media),
  3465.                     'media'            => (!empty($media) ? $media->getWebPath() : 'bundles/trinitywebshop/img/no-product-image.png'),
  3466.                     'mediaWidth'       => (!empty($media) ? $media->getWidth() : 800),
  3467.                     'mediaHeight'      => (!empty($media) ? $media->getHeight() :  600),
  3468.                     'hasSecondMedia'   => !empty($secondMedia),
  3469.                     'secondMedia'      => (!empty($secondMedia) ? $secondMedia->getWebPath() : ''),
  3470.                     'secondMediaWidth' => (!empty($secondMedia) ? $secondMedia->getWidth() : ''),
  3471.                     'secondMediaHeight'=> (!empty($secondMedia) ? $secondMedia->getHeight() : ''),
  3472.                     'price_display'    => $p->getDisplayPrice($Settings$this->WebshopCustomer$this->getUser()),
  3473.                     'review_enabled'   => $this->WebshopSettings->getEnableCardReviews(),
  3474.                     'review_count'     => $p->getReviews()->count(),
  3475.                     'review_average'   => $p->getScore(),
  3476.                     'card_specs'       => $p->getProductCardSpecValues(),
  3477.                 ];
  3478.                 $children[] = $prod;
  3479.                 $product_return_childs[$p->getId()] = $prod;
  3480.             }
  3481.             $media $Product->getMedia()->first();
  3482.             $secondMedia null;
  3483.             if(empty($media)){
  3484.                 $media $defaultImage;
  3485.             } else if ($this->WebshopSettings->getImageSwap() and $Product->getMedia()->count() >= 2){
  3486.                 $secondMedia $Product->getMedia()->next();
  3487.             }
  3488.             if(!empty($filters['category'])){
  3489.                 $Category $filters['category'];
  3490.             }
  3491.             if($Category instanceof \App\Trinity\WebshopBundle\Entity\CategoryProduct){
  3492.                 $Category $Category->getCategory();
  3493.             }
  3494.             if(is_array($Category)){
  3495.                 $Category $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->find(reset($Category));
  3496.             }
  3497.             if(empty($Category)){
  3498.                 continue;
  3499.             }
  3500.             if(empty($Product->getLanguage())){
  3501.                 $locale 'nl';
  3502.             }else{
  3503.                 $locale $Product->getLanguage()->getLocale();
  3504.             }
  3505.             switch($locale)
  3506.             {
  3507.             case "de":
  3508.                 $productname 'produkt';
  3509.                 break;
  3510.                 case "fr":
  3511.                 $productname 'produit';
  3512.                 break;
  3513.             default:
  3514.                 $productname 'product';
  3515.             }
  3516.             if((int)$this->WebshopSettings->getUriType() == 1){
  3517.                 $productUrl '';
  3518.                 $productUrl .= ($Webshop->getSettings()->getUri() ? '/' $Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
  3519.                 $productUrl .= $productname;
  3520.                 $productUrl .= '/' $Product->getNumber();
  3521.                 $productUrl .= '/' $Product->getSlug();
  3522.             }else{
  3523.                 $productUrl '';
  3524.                 $productUrl .= ($Webshop->getSettings()->getUri() ? '/' $Webshop->getSettings()->getUri() : $this->generateUrl('homepage') . ($Webshop->getCmssettings()->getBaseUri() ? $Webshop->getCmssettings()->getBaseUri() . '/' ''));
  3525.                 //$productUrl .= ($Webshop->getSettings()->getUri() ? '/' . $Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
  3526.                 $productUrl .= $Category->getUri();
  3527.                 $productUrl .= '/' $Product->getSlug();
  3528.                 $productUrl str_replace('//''/'$productUrl);
  3529.             }
  3530.             if($Category){
  3531.                 $product_list[] = $Product;
  3532.                 $prod = [
  3533.                     'id'               => $Product->getId(),
  3534.                     'type'             => $Product->getType(),
  3535.                     'label'            => ($Product->getBrand() ? $Product->getBrand()->getLabel() . ' ' '') . $Product->getLabel(),
  3536.                     'label_sub'        => $Product->getLabelSub(),
  3537.                     'intro'            => $Product->getIntro(),
  3538.                     'intro_stripped'   => strip_tags($Product->getIntro()),
  3539.                     'number'           => $Product->getNumber(),
  3540.                     'url'              => $productUrl,
  3541.                     'price'            => $Settings->getCurrency()->getFormat((float)$Product->getPriceIncl($Settings)),
  3542.                     'real_price'       => ($childProd $childProd $Settings->getCurrency()->getFormat($Product->getRealPriceIncl($Settings))),
  3543.                     'image'            => null,
  3544.                     'isNew'            => ($Product->getNew() && (($Product->getNewFrom() <= $now && $Product->getNewTill() >= $now) || (empty($Product->getNewTill()) && empty($Product->getNewFrom())))),
  3545.                     'exclusive'        => $Product->getExclusive(),
  3546.                     'priceSell'        => (float)$Product->getSellPrice(),
  3547.                     'priceSellIncl'    => (float)$Product->getSellPriceIncl(),
  3548.                     'priceSale'        => $Product->getPriceSale(),
  3549.                     'priceSaleFloat'   => (float)$Product->getPriceSale(),
  3550.                     'priceSalePercent' => $Product->getPriceSalePercent(),
  3551.                     'category_id'    => $Product->getCategory()->first()->getCategory()->getId(),
  3552.                     'hasSale'        => ((float)$Product->getPriceSale() > || $Product->hasPromotion() || $childProductSale),
  3553.                     'hasPromotion'   => $Product->hasPromotion(true),
  3554.                     'hasCombi'       => $Product->hasCombi(),
  3555.                     'hasFeatured'    => $Product->getFeatured() ? true false,
  3556.                     'canOrder'       => $Product->canOrder(),
  3557.                     'isChild'        => false,
  3558.                     'hasMedia'       => !empty($media),
  3559.                     'media'          => (!empty($media) ? $media->getWebPath() : 'bundles/trinitywebshop/img/no-product-image.png'),
  3560.                     'mediaWidth'       => (!empty($media) ? $media->getWidth() : 800),
  3561.                     'mediaHeight'      => (!empty($media) ? $media->getHeight() :  600),
  3562.                     'hasSecondMedia' => !empty($secondMedia),
  3563.                     'secondMedia'    => (!empty($secondMedia) ? $secondMedia->getWebPath() : ''),
  3564.                     'secondMediaWidth' => (!empty($secondMedia) ? $secondMedia->getWidth() : ''),
  3565.                     'secondMediaHeight'=> (!empty($secondMedia) ? $secondMedia->getHeight() : ''),
  3566.                     'products'       => $children,
  3567.                     'products_count' => count($children),
  3568.                     'price_display'  => $Product->getDisplayPrice($Settings$this->WebshopCustomer$this->getUser()),
  3569.                     'review_enabled' => $this->WebshopSettings->getEnableCardReviews(),
  3570.                     'review_count'   => $Product->getReviews()->count(),
  3571.                     'review_average' => $Product->getScore(),
  3572.                     'card_specs'     => $Product->getProductCardSpecValues(),
  3573.                     // 'discountHtml' => $discountHtml,
  3574.                 ];
  3575.                 if(!empty($Product->getMedia())){
  3576.                     foreach($Product->getMedia() as $Media){
  3577.                         $prod['image'] = '/' $Media->getWebPath();
  3578.                         break;
  3579.                     }
  3580.                 }
  3581.                 if(!empty($relatedChild) && $relatedChild->getMedia()->count()){
  3582.                     $prod['image'] = '/' $relatedChild->getMedia()->first()->getWebPath();
  3583.                     $prod['media'] = $relatedChild->getMedia()->first()->getWebPath();
  3584.                 }
  3585.                 $product_return[$Product->getId()] = $prod;
  3586. //            }
  3587.             $return['products'][] = $prod;
  3588. //        }
  3589.             }
  3590.         }
  3591.         // dump(array_keys($product_return));
  3592.         $filter_type 'up';
  3593. // xxx hmmmm?
  3594.         //$return['products'] = [];
  3595.         $spec_response = [
  3596.             'enabled'  => [],
  3597.             'disabled' => [],
  3598.             'all'      => [],
  3599.         ];
  3600.         /*
  3601.             Filter products list based on filters
  3602.          */
  3603.         
  3604.         $specs_filters = (!empty($filters['filters']) ? $filters['filters'] : []);
  3605.         // Remove range filters
  3606.         foreach($specs_filters as $k => $v){ if(isset($v['range'])){ unset($specs_filters[$k]); } }
  3607.         if(!empty($filters['category'])){
  3608.             if(!empty($specs_filters)){
  3609.                 $compatible_specvalues $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->checkCompatibleValues($specs_filters, (!empty($filters['category']) ? $filters['category'] : null));
  3610.                 if(!is_array($filters['category'])){
  3611.                     $all_category_specs $filters['category']->getSpecCache();
  3612.                     foreach($all_category_specs as $spec_id => $sdata){
  3613.                         foreach($sdata['value'] as $vdata){
  3614.                             $v $vdata['value'];
  3615.                             // Capture for all
  3616.                             if(!isset($spec_response['all'][$spec_id])) $spec_response['all'][$spec_id] = [];
  3617.                             $spec_response['all'][$spec_id][] = $v;
  3618.                             if(!empty($compatible_specvalues[$spec_id])){
  3619.                                 // Found spec in compatible
  3620.                                 if(in_array($v$compatible_specvalues[$spec_id])){
  3621.                                     // Spec + value is compatible
  3622.                                     if(!isset($spec_response['enabled'][$spec_id])) $spec_response['enabled'][$spec_id] = [];
  3623.                                     $spec_response['enabled'][$spec_id][] = $v;
  3624.                                 }else{
  3625.                                     // Spec + value is not compatible
  3626.                                     if(!isset($spec_response['disabled'][$spec_id])) $spec_response['disabled'][$spec_id] = [];
  3627.                                     $spec_response['disabled'][$spec_id][] = $v;
  3628.                                 }
  3629.                             }else{
  3630.                                 // Spec at all not compatible
  3631.                                 if(!isset($spec_response['disabled'][$spec_id])) $spec_response['disabled'][$spec_id] = [];
  3632.                                 $spec_response['disabled'][$spec_id][] = $v;
  3633.                             }
  3634.                         }
  3635.                     }
  3636.                 }
  3637.             }
  3638.         }
  3639.         // dump($spec_response);die();
  3640.         /*
  3641.             Convert strings to SpecValue IDs
  3642.          */
  3643.         /*$specs_filters_ids = [];
  3644.         foreach($specs_filters as $spec_id => $strings){
  3645.             foreach($strings as $string){
  3646.                 $Spec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->find($spec_id);
  3647.                 $SpecValues = $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findBy(['spec' => $Spec, 'value' => $string]);
  3648.                 foreach($SpecValues as $SpecValue){
  3649.                     $specs_filters_ids[] = $spec_id . '+' . $SpecValue->getId();
  3650.                 }
  3651.             }
  3652.         }*/
  3653.         /*
  3654.             Collect strict list of spec -> spec_value -> product
  3655.          */
  3656.         
  3657.         /*foreach($product_list as $X){
  3658.             dump($X->getId() . ' | ' . $X->getLabel());
  3659.         }*/
  3660.         /*$checkMatchTarget = count($specs_filters_ids);
  3661.         // dump($specs_filters_ids);
  3662.         $filter_productsList = [];
  3663.         // $simple_productsList = [];
  3664.         foreach($product_list as $Product){
  3665.             if(empty($specs_filters_ids)){
  3666.                 if(!empty($product_return[$Product->getId()])){
  3667.                     $ProductObject = $product_return[$Product->getId()];
  3668.                     if(!in_array($ProductObject, $return['products'])){
  3669.                         $return['products'][] = $ProductObject;
  3670.                     }
  3671.                 }
  3672.             }else{
  3673.                 $checkMatchCount = 0;
  3674.                 foreach($Product->getSpecValues() as $SpecValue){
  3675.                     if($SpecValue instanceof \App\Trinity\WebshopBundle\Entity\SpecValue){
  3676.                         $Spec = $SpecValue->getSpec();
  3677.                         // dump('X ======:' . $Product->getId() . ' | ' . $Product->getLabel() . ' | ' . $Spec->getId() . '+' . $SpecValue->getId());
  3678.                         $checkMatchCount = 0;
  3679.                         if(empty($specs_filters_ids) || in_array($Spec->getId() . '+' . $SpecValue->getId(), $specs_filters_ids)){
  3680.                             $filter_productsList[] = $Product;
  3681.                             // dump('X ======:' . $Product->getId() . ' | ' . $Product->getLabel() . ' | ' . $Spec->getId() . '+' . $SpecValue->getId());
  3682.                             if(!empty($product_return_childs[$Product->getId()])){
  3683.                                 // dump('FOUND ======:' . $Product->getId() . ' | ' . $Product->getLabel() . ' | ' . $Spec->getId() . '+' . $SpecValue->getId());
  3684.                                 if($Product->getLinkedTo()->count() > 0){
  3685.                                     if($Product->getVisible()){
  3686.                                         // dump('CHILD VISIBLE =======: ' . $Product->getId() . ' | ' . $Product->getLabel() . ' | ' . $Spec->getId() . '+' . $SpecValue->getId());
  3687.                                         $ProductObject = $product_return_childs[$Product->getId()];
  3688.                                         if(!in_array($ProductObject, $return['products'])){
  3689.                                             $return['products'][] = $ProductObject;
  3690.                                         }
  3691.                                     }
  3692.                                     // dump('CHILD =======: ' . $Product->getId() . ' | ' . $Product->getLabel() . ' | ' . $Spec->getId() . '+' . $SpecValue->getId());
  3693.                                     foreach($Product->getLinkedTo() as $ParentProduct){
  3694.                                         if(!empty($product_return_childs[$ParentProduct->getId()])){
  3695.                                         $ProductObject = $product_return_childs[$ParentProduct->getId()];
  3696.                                         if(!in_array($ProductObject, $return['products'])){
  3697.                                             $return['products'][] = $ProductObject;
  3698.                                         }
  3699.                                     }
  3700.                                     }
  3701.                                 }else{
  3702.                                     // dump('ROOT =======: ' . $Product->getId() . ' | ' . $Product->getLabel() . ' | ' . $Spec->getId() . '+' . $SpecValue->getId());
  3703.                                     $ProductObject = $product_return_childs[$Product->getId()];
  3704.                                     if(!in_array($ProductObject, $return['products'])){
  3705.                                         $return['products'][] = $ProductObject;
  3706.                                     }
  3707.                                 }
  3708.                             }
  3709.                         }
  3710.                     }
  3711.                 }
  3712.             }
  3713.         }
  3714.         // die();
  3715.         $return['count'] = count($return['products']);
  3716.         $return['total'] = count($return['products']);
  3717.         $return['current'] = count($return['products']);
  3718.         // dump($return);die();
  3719.         // dump($return['products']);die();
  3720.         // die();
  3721.         // dump($simple_productsList);die();
  3722.         / *
  3723.             Setup new specs arrays
  3724.          * /
  3725.         $specs_groups           = [];
  3726.         $specs_id_to_obj        = [];
  3727.         $specs_all              = [];
  3728.         $specs_available        = [];
  3729.         $specs_disabled         = [];
  3730.         $specs_all_simple       = [];
  3731.         $specs_available_simple = [];
  3732.         $specs_disabled_simple  = [];
  3733.         // dump(count($filter_productsList) );die();
  3734.         foreach($filter_productsList as $Product){
  3735.             foreach($Product->getSpecValues() as $SpecValue){
  3736.                 if($SpecValue instanceof \App\Trinity\WebshopBundle\Entity\SpecValue){
  3737.                     $Spec = $SpecValue->getSpec();
  3738.                     foreach($Spec->getGroups() as $Group){
  3739.                         $specs_groups[$Group->getId()] = $Group;
  3740.                     }
  3741.                     if($Spec instanceof \App\Trinity\WebshopBundle\Entity\Spec){
  3742.                         $specs_id_to_obj[$SpecValue->getId()] = $SpecValue;
  3743.                         $specs_available_simple[$Spec->getId()][$SpecValue->getPosition() . '_' . $SpecValue->getId()] = $SpecValue->getId();
  3744.                         ksort($specs_available_simple[$Spec->getId()]);
  3745.                     }
  3746.                 }
  3747.             }
  3748.         }
  3749.         foreach($specs_groups as $SpecGroup){
  3750.             if($SpecGroup instanceof \App\Trinity\WebshopBundle\Entity\SpecGroup){
  3751.                 foreach($SpecGroup->getSpecs() as $Spec){
  3752.                     foreach($Spec->getValues() as $SpecValue){
  3753.                         $specs_id_to_obj[$SpecValue->getId()] = $SpecValue;
  3754.                         $specs_all_simple[$Spec->getId()][$SpecValue->getPosition() . '_' . $SpecValue->getId()] = $SpecValue->getId();
  3755.                         ksort($specs_all_simple[$Spec->getId()]);
  3756.                     }
  3757.                 }
  3758.             }
  3759.         }
  3760.         foreach($specs_all_simple as $spec_id => $values){
  3761.             if(!isset($specs_available_simple[$spec_id])){
  3762.                 $specs_disabled_simple[$spec_id] = $values;
  3763.             }else{
  3764.                 $diff = array_diff($values, $specs_available_simple[$spec_id]);
  3765.                 if(!empty($diff)){
  3766.                     $specs_disabled_simple[$spec_id] = $diff;
  3767.                 }
  3768.             }
  3769.         }
  3770.         foreach($specs_all_simple as $spec_id => $values){
  3771.             foreach($values as $value_id){
  3772.                 $SpecValue = $specs_id_to_obj[$value_id];
  3773.                 $sv_data = [
  3774.                     'id' => $SpecValue->getId(),
  3775.                     'value' => $SpecValue->getValue(),
  3776.                     'hex' => $SpecValue->getHex(),
  3777.                 ];
  3778.                 $specs_all[$spec_id][] = $sv_data;
  3779.             }
  3780.         }
  3781.         foreach($specs_available_simple as $spec_id => $values){
  3782.             foreach($values as $value_id){
  3783.                 $SpecValue = $specs_id_to_obj[$value_id];
  3784.                 $sv_data = [
  3785.                     'id' => $SpecValue->getId(),
  3786.                     'value' => $SpecValue->getValue(),
  3787.                     'hex' => $SpecValue->getHex(),
  3788.                 ];
  3789.                 $specs_available[$spec_id][] = $sv_data;
  3790.             }
  3791.         }
  3792.         foreach($specs_disabled_simple as $spec_id => $values){
  3793.             foreach($values as $value_id){
  3794.                 $SpecValue = $specs_id_to_obj[$value_id];
  3795.                 $sv_data = [
  3796.                     'id' => $SpecValue->getId(),
  3797.                     'value' => $SpecValue->getValue(),
  3798.                     'hex' => $SpecValue->getHex(),
  3799.                 ];
  3800.                 $specs_disabled[$spec_id][] = $sv_data;
  3801.             }
  3802.         }
  3803.         $return['specs_all']              = $specs_all;
  3804.         $return['specs_available']        = $specs_available;
  3805.         $return['specs_disabled']         = $specs_disabled;*/
  3806.         // New
  3807.         $return['specs_disabled']  = $spec_response['disabled'];
  3808.         $return['specs_available'] = $spec_response['enabled'];
  3809.         $return['specs_all']       = $spec_response['all'];
  3810.         if(empty($postValues['order'])){
  3811.             $postValues['order'] = 'pos asc';
  3812.         }
  3813.         $order_pos explode(' '$postValues['order']);
  3814.         /*if($order_pos[0] != 'pos'){
  3815.             // Sort
  3816.             $sorted = [];
  3817.             $new_list = [];
  3818.             foreach($return['products'] as $prod){
  3819.                 if($order_pos[0] == 'label'){
  3820.                     $sorted[$prod['label']][] = $prod;
  3821.                 }elseif($order_pos[0] == 'price_incl'){
  3822.                     $sorted[$prod['real_price']][] = $prod;
  3823.                 }else{
  3824.                     // $sorted[$prod['pos']][] = $prod;
  3825.                 }
  3826.                 if($order_pos[1] == 'asc'){
  3827.                     ksort($sorted);
  3828.                 }else{
  3829.                     krsort($sorted);
  3830.                 }
  3831.             }
  3832.             // dump($sorted);die();
  3833.             // Reset to list
  3834.             foreach($sorted as $prods){
  3835.                 foreach($prods as $p){
  3836.                     $new_list[] = $p;
  3837.                 }
  3838.             }
  3839.             $return['products'] = $new_list;
  3840.         }*/
  3841.         // dump($return['specs']);die();
  3842.         // Prepare specs for json
  3843.         /*foreach($return['specs'] as $specId => $spec){
  3844.             if(is_array($spec['value'])){
  3845.                 $list = [];
  3846.                 foreach($spec['value'] as $v){
  3847.                     $list[] = [
  3848.                         'id' => $v->getId(),
  3849.                         'value' => $v->getValue(),
  3850.                     ];
  3851.                 }
  3852.                 $return['specs'][$specId]['value'] = $list;
  3853.             }
  3854.             if(is_array($spec['available'])){
  3855.                 $list = [];
  3856.                 foreach($spec['available'] as $v){
  3857.                     $list[] = [
  3858.                         'id' => $v->getId(),
  3859.                         'value' => $v->getValue(),
  3860.                     ];
  3861.                 }
  3862.                 $return['specs'][$specId]['available'] = $list;
  3863.             }
  3864.         }*/
  3865.         $return['total']          = $products_data['total'];
  3866.         $return['current']        = $products_data['current'];
  3867.         $return['start']          = $products_data['start'];
  3868.         $return['limit']          = $products_data['limit'];
  3869.         $return['pages']          = $products_data['pages'];
  3870.         $return['page']           = $products_data['page'];
  3871.         $return['filters_visual'] = $filters_visual;
  3872.         $return['hasmore']        = ($products_data['page'] < $return['pages']);
  3873.         
  3874.         $return['filters']        = (!empty($postValues['filter']) ? $postValues['filter'] : []);
  3875.         $allFilters = [];
  3876.         if(!empty($postValues['q'])){
  3877.             $allFilters['q'] = $postValues['q'];
  3878.         }
  3879.         foreach($return['filters'] as $spec_id => $data){
  3880.             if(!empty($data['range'])){
  3881.                 if(empty($data['range'][0]) && empty($data['range'][1])){
  3882.                     unset($return['filters'][$spec_id]);
  3883.                 }else{
  3884.                     if(!empty($data[0])){
  3885.                         $Spec $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->find($spec_id);
  3886.                         $allFilters[$Spec->getLabel()] = $data[0];
  3887.                     }
  3888.                 }
  3889.             }else{
  3890.                 if(!empty($data[0])){
  3891.                     $Spec $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->find($spec_id);
  3892.                     $allFilters[$Spec->getLabel()] = $data[0];
  3893.                 }
  3894.             }
  3895.         }
  3896.         $route = (!empty($postValues['route']) ? $postValues['route'] : 'homepage');
  3897.         $return['pagination'] = '<div class="js-pag">' $twig->render(
  3898.             '@Cms/pagination_bootstrap.html.twig',
  3899.             [
  3900.                 'currentFilters' => $allFilters,
  3901.                 'currentPage' => $return['page'],
  3902.                 'paginationPath' => $route,
  3903.                 'lastPage' => $return['pages'],
  3904.                 'showAlwaysFirstAndLast' => true
  3905.             ]
  3906.         ) . '</div>';
  3907.         // Render pagination HTML
  3908.         /*{% include '@Cms/pagination_bootstrap.html.twig' with {
  3909.           currentPage : products_data.page,
  3910.           paginationPath: app.request.attributes.get('_route'),
  3911.           lastPage: products_data.pages,
  3912.           showAlwaysFirstAndLast: true
  3913.         }
  3914.         only %}*/
  3915.         // dump($return['specs']);die();
  3916.         // Try to find grouped values
  3917.         /*foreach($return['specs'] as $id => $spec){
  3918.             foreach($spec['value'] as $n => $value){
  3919.                 $return['specs'][$id]['value'][$n] = explode(' / ', $value);
  3920.             }
  3921.         }*/
  3922.         return new JsonResponse($return);
  3923.         // return $this->render('@TrinityWebshop/default/category.html.twig', array(
  3924.         //     'Category' => $Category,
  3925.         //     'products' => $products,
  3926.         //     'specs' => $specs,
  3927.         // ));
  3928.     }
  3929.     private function parseEntityPageUrls($entity)
  3930.     {
  3931.         if ($entity instanceof \App\Trinity\WebshopBundle\Entity\Product)
  3932.         {
  3933.             $intro $this->parseCmsUrls($entity->getIntro());
  3934.             $entity->setIntro($intro);
  3935.             $description $this->parseCmsUrls($entity->getDescription());
  3936.             $entity->setDescription($description);
  3937.         }
  3938.         if ($entity instanceof \App\Trinity\WebshopBundle\Entity\Category)
  3939.         {
  3940.             $description $this->parseCmsUrls($entity->getDescription());
  3941.             $entity->setDescription($description);
  3942.             $blocktext $this->parseCmsUrls($entity->getBlockText());
  3943.             $entity->setBlockText($blocktext);
  3944.         }
  3945.         return $entity;
  3946.     }
  3947.     private function parseSettingsPageUrls($Settings)
  3948.     {
  3949.         $intro $this->parseCmsUrls($Settings->getInfo());
  3950.         $Settings->setInfo($intro);
  3951.         $c1 $this->parseCmsUrls($Settings->getCustom1());
  3952.         $Settings->setCustom1($c1);
  3953.         $c2 $this->parseCmsUrls($Settings->getCustom2());
  3954.         $Settings->setCustom2($c2);
  3955.         $c3 $this->parseCmsUrls($Settings->getCustom3());
  3956.         $Settings->setCustom3($c3);
  3957.         $c4 $this->parseCmsUrls($Settings->getCustom4());
  3958.         $Settings->setCustom4($c4);
  3959.         $c5 $this->parseCmsUrls($Settings->getCustom5());
  3960.         $Settings->setCustom5($c5);
  3961.         $c6 $this->parseCmsUrls($Settings->getCustom6());
  3962.         $Settings->setCustom6($c6);
  3963.         $usp $this->parseCmsUrls($Settings->getUsps());
  3964.         $Settings->setUsps($usp);
  3965.         return $Settings;
  3966.     }
  3967. }