<?php
namespace App\Trinity\WebshopBundle\Controller;
use App\CmsBundle\Controller\StorageController;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Trinity\WebshopBundle\Entity\Category;
use App\Trinity\WebshopBundle\Entity\Invoice;
use App\Trinity\WebshopBundle\Entity\OrderPayment;
use App\Trinity\WebshopBundle\Entity\Review;
use App\Trinity\WebshopBundle\Entity\SavedSearch;
use App\Trinity\WebshopBundle\Entity\InvoiceProduct;
use App\Trinity\WebshopBundle\Classes\Pdf;
use App\Trinity\WebshopBundle\Entity\Tag;
use App\Trinity\WebshopBundle\Classes\Picqer;
use Twig\Environment;
class FrontController extends StorageController
{
/**
* @Route("/webshop-main/save/search", name="save_search")
* @Template()
*/
public function savesearchAction(Request $request)
{
$this->init($request);
$validCaptcha = $this->Settings->validateGoogleRecaptcha($request->request->get('g-recaptcha-response'));
if(($validCaptcha)){
if(!empty($_POST['email'])){
$SavedSearch = new SavedSearch();
$SavedSearch->setWebshop($this->Webshop);
$SavedSearch->setEmail($_POST['email']);
$SavedSearch->setDateStart(new \DateTime());
$SavedSearch->setParameters($_POST);
$em = $this->getDoctrine()->getManager();
$em->persist($SavedSearch);
$em->flush();
}else{
$spec_query = '';
$spec_filter = [];
$licenseplate = null;
if(!empty($this->get('session')->get('ecomm_spec_filter'))){
$spec_filter = $this->get('session')->get('ecomm_spec_filter');
}
if(!empty($this->get('session')->get('ecomm_spec_plate'))){
$licenseplate = $this->get('session')->get('ecomm_spec_plate');
}
/*if(!empty($this->get('session')->get('ecomm_spec_query'))){
$spec_query = $this->get('session')->get('ecomm_spec_query');
}*/
$data = [
'spec_filter' => $spec_filter,
'licenseplate' => $licenseplate,
'spec_query' => $spec_query,
];
$SavedSearch = new SavedSearch();
$SavedSearch->setWebshop($this->Webshop);
$SavedSearch->setEmail($_POST['filter-email']);
$SavedSearch->setDateStart(new \DateTime());
$SavedSearch->setParameters($data);
$em = $this->getDoctrine()->getManager();
$em->persist($SavedSearch);
$em->flush();
}
return new JsonResponse(['success' => true]);
}else{
return new JsonResponse(['success' => false, 'message' => 'Ongeldige captcha.']);
}
}
public function check_diff_multi($array1, $array2){
$result = array();
foreach($array1 as $key => $val) {
if(isset($array2[$key])){
if(is_array($val) && $array2[$key]){
$result[$key] = $this->check_diff_multi($val, $array2[$key]);
}
} else {
$result[$key] = $val;
}
}
return $result;
}
public function initPaging(Request $request){
$em = $this->getDoctrine()->getManager();
$this->Settings = $em->getRepository('CmsBundle:Settings')->findByLanguage($this->language, str_replace('www.', '', $request->getHttpHost()));
if(is_null($this->Settings)) $this->Settings = new \App\CmsBundle\Entity\Settings();
$this->absoluteUrl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
$this->FirstPage = null;
$tmp_pages = $this->getDoctrine()->getRepository('CmsBundle:Page')->findBy(array('language' => $this->Settings->getLanguage(), 'page' => null, 'base' => null, 'enabled' => true), array('sort' => 'ASC'), 1);
if(!empty($tmp_pages)){
$this->FirstPage = $tmp_pages[0];
}
}
public function parse( $tpl, $args = array() ){
$args[ 'Settings' ] = $this->Settings;
$args[ 'languages' ] = $this->getDoctrine()->getRepository('CmsBundle:Language')->findAll();
if( !isset($args[ 'bodyClass' ]) ) $args[ 'bodyClass' ] = 'sub';
return $this->render($tpl . '.html.twig', $args);
}
/**
* Load dynamic category as defined in WebshopBundle
*
* @param Request $request
* @Template()
*/
public function loadAction(Request $request)
{
$this->init($request);
$params = array();
$params[] = $request->get('param1');
$params[] = $request->get('param2');
$params[] = $request->get('param3');
// Find recipes page
$RecipesPage = null;
$blocks = $this->getDoctrine()->getRepository('CmsBundle:PageBlock')->findByData('TrinityRecipesBundle');
foreach($blocks as $Block){
$p = $Block->getWrapper()->getPage();
if($p->getLanguage() == $this->language){
$RecipesPage = $p;
break;
}
}
$this->initPaging($request);
$this->init($request);
$Webshop = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($this->language, $this->Settings);
$Settings = $Webshop->getSettings();
$custom_breadcrumbs = [];
$custom_breadcrumbs[] = [
'name' => $this->trans('home', [], 'webshop_backend'),
'url' => $this->generateUrl('homepage') . substr($this->Settings->getBaseUri(),1)
];
// VALIDATE HOMEPAGE AS HIGHEST LEVEL
$access = $this->FirstPage->getAccess();
if($access != null){
// Validate permissions
if($access == 'login'){
$checkRoles = $this->FirstPage->getAccessRoles();
if($checkRoles){
if(!is_array($checkRoles)) $checkRoles = [$checkRoles];
$hasRoleAccess = false;
foreach($checkRoles as $role){
if($this->get('security.authorization_checker')->isGranted($role)){
$hasRoleAccess = true;
break;
}
}
if(!$hasRoleAccess){
if ($this->FirstPage->getAccessAllowLogin()) {
// LOGIN FORM
$hasLoginInvalidRoles = false;
if($this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')){
$hasLoginInvalidRoles = true;
}
$metatags = $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getBySystem(0, (int)$this->FirstPage->getId(), true);
$systemMetatags = $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getBySystem(1, false, false);
$lastUsername = '';
$error = null;
$this->FirstPage->setTitle('Inloggen');
$this->FirstPage->setLabel('Inloggen');
$this->FirstPage->requireAuth = true;
return $this->parse( 'CmsBundle:Page:page', $this->attributes([
'loginform' => true,
'bodyClass' => 'dynamic',
'Page' => $this->FirstPage,
'metatags' => $metatags,
'systemMetatags' => $systemMetatags,
'error' => $error,
'last_username' => $lastUsername,
'hasLoginInvalidRoles' => $hasLoginInvalidRoles,
]));
}else{
throw $this->createAccessDeniedException('Permission denied');
}
}
}
}elseif($access == 'no-login'){
if($this->get('security.authorization_checker')->isGranted('ROLE_USER')){
throw $this->createAccessDeniedException('Permission denied');
}
}
}
$this->get('session')->set('last-route', $request->get('_route'));
$Page = $Settings->getPage();
if(empty($Page)){
$Page = new \App\CmsBundle\Entity\Page();
$Page->setOptionBreadcrumbs(false);
$Page->setOptionSubnavigation(false);
$Page->setOptionTitle(false);
}
$metatags = $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getBySystem(0, (int)$Page->getId(), true);
$systemMetatags = $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getBySystem(1, false, false);
$all_products = null;
$price_range = null;
$catFix = false;
$Product = null;
$Category = null;
if ($request->get('categoryId')) {
$Category = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findOneBy(['webshop' => $Webshop, 'id' => $request->get('categoryId')]);
if(empty($Category)){
$_Category = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findOneBy(['id' => $request->get('categoryId')]);
if($_Category->getWebshop() != $Webshop){
// Webshop mismatch
// Try to find one based on the same slug and webshop
$Category = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findOneBy(['webshop' => $Webshop, 'slug' => $_Category->getSlug()]);
}
if(empty($Category)){
throw $this->createNotFoundException('Category ' . $request->get('categoryId') . ' not found');
}
}
// Parsed wrong language category
if($Category->getWebshop() && ($Category->getWebshop()->getLanguage() != $this->language || $Category->getWebshop() != $this->Webshop)){
$TmpCategory = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findOneBy([ 'slug' => $Category->getSlug(), 'webshop' => $this->Webshop ]);
if($TmpCategory) {
$Category = $TmpCategory;
}
}
if(!empty($params[1])){
$Product = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->findByCategoryAndSlug($Category, $params[1], true);
}else if(!empty($params[0])){
$Product = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->findByCategoryAndSlug($Category, $params[0], true);
} else if($request->get('productId')){
$Product = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->findOneBy(['webshop' => $Webshop, 'id' => $request->get('productId')]);
}
// if($this->containerInterface->getParameter('kernel.environment') == 'dev'){
if(empty($Product)){
// Fix for dynamic assigned products based on promotions
if(!empty($params[1])){
$FoundProduct = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->findOneBySlug($params[1]);
}elseif(!empty($params[0])){
$FoundProduct = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->findOneBySlug($params[0]);
}
// Found product itself, try look for dynamic promotion link
if(!empty($FoundProduct) && !empty($FoundProduct->getCategory())){
$CategoryProduct = $FoundProduct->getCategory()->first();
if((int)$this->WebshopSettings->getUriType() == 1){
$productUrl = '';
$productUrl .= ($this->Webshop->getSettings()->getUri() ? '/' . $this->Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
// $productUrl .= $productname;
// $productUrl .= '/' . $FoundProduct->getNumber();
$productUrl .= $CategoryProduct->getCategory()->getUri();
$productUrl .= '/' . $FoundProduct->getSlug();
}else{
$productUrl = '';
$productUrl .= ($this->Webshop->getSettings()->getUri() ? '/' . $this->Webshop->getSettings()->getUri() : $this->generateUrl('homepage') . ($this->Webshop->getCmssettings()->getBaseUri() ? $this->Webshop->getCmssettings()->getBaseUri() . '/' : ''));
//$productUrl .= ($Webshop->getSettings()->getUri() ? '/' . $Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
$productUrl .= $CategoryProduct->getCategory()->getUri();
$productUrl .= '/' . $FoundProduct->getSlug();
$productUrl = str_replace('//', '/', $productUrl);
}
header('Location:' . $productUrl);
exit;
}
}
// }
}
// pelikan
if (is_numeric($params[0])) {
$Product = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->findOneBy(['number' => $params[0], 'language' => $this->language]);
$Category = $Product->getCategory()->first()->getCategory();
}
if(!empty($_GET['q'])){
$res = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->search($this->Webshop, ['q' => $_GET['q']], 'id', 'asc');
if(!empty($res['total'])){
$FoundProduct = $res['results'][0];
if(!empty($FoundProduct->getTemplateKey())){
if((int)$this->WebshopSettings->getUriType() == 1){
$productUrl = '';
$productUrl .= ($this->Webshop->getSettings()->getUri() ? '/' . $this->Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
// $productUrl .= $productname;
// $productUrl .= '/' . $FoundProduct->getNumber();
$productUrl .= $FoundProduct->getCategory()->first()->getCategory()->getUri();
$productUrl .= '/' . $FoundProduct->getSlug();
}else{
$productUrl = '';
$productUrl .= ($this->Webshop->getSettings()->getUri() ? '/' . $this->Webshop->getSettings()->getUri() : $this->generateUrl('homepage') . ($this->Webshop->getCmssettings()->getBaseUri() ? $this->Webshop->getCmssettings()->getBaseUri() . '/' : ''));
//$productUrl .= ($Webshop->getSettings()->getUri() ? '/' . $Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
$productUrl .= $FoundProduct->getCategory()->first()->getCategory()->getUri();
$productUrl .= '/' . $FoundProduct->getSlug();
$productUrl = str_replace('//', '/', $productUrl);
}
header('Location:' . $productUrl);
exit;
}
}
}
$sort = null;
$sort_dir = 'asc';
$defaultSort = $this->WebshopSettings->getDefaultSort();
if(!empty($defaultSort)){
$defaultSort = str_replace('-', ' ', $defaultSort);
$sort = $defaultSort;
}
/**
*
*
* ==============================================================================================================
* ==============================================================================================================
* ==============================================================================================================
* ==============================================================================================================
*
* PRODUCT DETAIL
*
* ==============================================================================================================
* ==============================================================================================================
* ==============================================================================================================
* ==============================================================================================================
*
*
*/
if($Product){
//$this->Timer->break('Found product: ' . $Product->getLabel() . ', start product display');
// Check from parameters if caching must be enabled
$allowCache = false;
if ($this->containerInterface->hasParameter('trinity_cache') && ($this->containerInterface->getParameter('trinity_cache') == 'true' || $this->containerInterface->getParameter('trinity_cache'))) {
$allowCache = true;
}
if(!empty($_GET['nocache']) || !empty($_GET['resetcache']) || !empty($_GET['timer']) || $this->containerInterface->getParameter('kernel.environment') == 'dev' || $Settings->getB2b()){
$allowCache = false;
}
/* if ($allowCache) {
$cachedData = $Product->getCacheData();
if(!empty($cachedData)){
// Return cached data
echo $cachedData;
exit;
}
} */
$Product->activeCategory = $Category;
$recipes = [];
if(!empty($Product->getBundleLinkdata())){
$bld = $Product->getBundleLinkdata();
if(!empty($bld['RecipesBundle'])){
foreach($bld['RecipesBundle'] as $recipe_id){
$Recipe = $this->getDoctrine()->getRepository(\App\Trinity\RecipesBundle\Entity\Recipe::class)->find($recipe_id);
if(!empty($Recipe)){
$recipes[] = $Recipe;
}
}
}
}
/*if($this->containerInterface->getParameter('kernel.environment') == 'dev'){
dump($Product->getId());
$displayPrice = $Product->getDisplayPrice($this->WebshopSettings, $this->WebshopCustomer, $this->getUser(), true);
die($displayPrice);
}*/
if($Product->getType() == 1 || $Product->getType() == 2){
// if($this->containerInterface->getParameter('kernel.environment') == 'dev'){
if(empty($Product->getLinkedProductsSorted()) && empty($Product->getSuper())){
throw $this->createNotFoundException('Product ' . $Product->getId() . ' not found');
}
// }
}
// $Product = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($request->get('productId'));
$current_productViewHistory = $this->get('session')->get('product-view-history');
$productHistory = [$Product->getId()];
if(!empty($current_productViewHistory)){
foreach($current_productViewHistory as $id){
$historyProd = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($id);
if($historyProd){
if($id != $Product->getId() && $historyProd->getVisible() && $historyProd->getEnabled()){
if(!in_array($id, $productHistory)){
if(count($productHistory) < 5){
$productHistory[] = $id;
}
}
}
}
}
}
// Sign-up for restock messages
if(!empty($_POST['signupstock'])){
$receipients = $Product->getRestockNotify();
$receipients[] = $_POST['signupstock'];
$Product->setRestockNotify($receipients);
$em = $this->getDoctrine()->getManager();
$em->persist($Product);
$em->flush();
header('Location:' . $request->getUri() . '?notify-restock=true');
exit;
}
$this->get('session')->set('product-view-history', $productHistory);
$firstAvailable = null;
$firstAvailablePrice = 100000000000;
if ($Product->getLinkedProducts()->count() > 0) {
foreach($Product->getLinkedProducts() as $LP){
if($LP->canOrder()){
if($LP->getRealPriceIncl() < $firstAvailablePrice){
$firstAvailable = $LP;
$firstAvailablePrice = $LP->getRealPriceIncl();
}
}
}
}
$productHistoryObjects = [];
foreach($productHistory as $id){
if($id != $Product->getId()){
$productHistoryObjects[$id] = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->findOneById($id);
}
}
/*$productRelatedObjects = [];
$limit = 10;
$count = 0;
$CatProds = $Product->getCategory()[0]->getCategory()->getProducts();
foreach($CatProds as $CatProd){
if($count <= $limit){
if($CatProd->getProduct()->getId() != $Product->getId()){
$productRelatedObjects[$CatProd->getProduct()->getId()] = $CatProd->getProduct();
$count++;
}
} else {
break;
}
}*/
// Cleaner way and directly filtered by brand and model
$f = [];
$BrandsSpec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->findOneBy(['label' => 'Merk']);
$ModelsSpec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->findOneBy(['label' => 'Model']);
$specData = $Product->getSimplifiedSpecValues();
foreach($specData as $k => $v){
if(!empty($BrandsSpec) && $k == $BrandsSpec->getId()){ $f[$k] = $v; }
if(!empty($ModelsSpec) && $k == $ModelsSpec->getId()){ $f[$k] = $v; }
}
$productRelatedObjects_raw = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->search(
$this->Webshop,
[
'category' => $Product->getCategory()->first()->getCategory(),
'visible' => 1,
'filters' => $f,
'ignore_ids' => [$Product->getId()],
], null, 'asc', ($this->WebshopSettings->getPagination() == 'none'), false, 1, 10, 0
);
$productRelatedObjects = $productRelatedObjects_raw['results'];
$country = $Settings->getMapZoomCountry();
if (empty($Settings->getMapZoomCountry())) {
$country = '';
}
switch ($country)
{
case 'nl':
$center_lat = 52.307963;
$center_lng = 5.551342;
$center_zoom = 7;
break;
case 'be':
$center_lat = 50.683057;
$center_lng = 4.731317;
$center_zoom = 8;
break;
case 'gb':
$center_lat = 54.121844;
$center_lng = -2.767957;
$center_zoom = 6;
break;
case 'de':
$center_lat = 51.085295;
$center_lng = 10.027864;
$center_zoom = 6;
break;
case 'fr':
$center_lat = 47.091676;
$center_lng = 2.791095;
$center_zoom = 6;
break;
case 'it':
$center_lat = 43.095551;
$center_lng = 12.306936;
$center_zoom = 5;
break;
case 'ch':
$center_lat = 46.911197;
$center_lng = 8.297312;
$center_zoom = 8;
break;
case 'cz':
$center_lat = 49.832784;
$center_lng = 15.493717;
$center_zoom = 7.5;
break;
default:
$center_lat = 50.626387;
$center_lng = 9.889074;
$center_zoom = 4;
break;
}
$custom_breadcrumbs[] = [
'name' => $Category->getLabel(),
'url' => ($Settings->getUri() ? '/' . $Settings->getUri() : $this->generateUrl('homepage')) . $Category->getUri()
];
if($Product->getTemplateKey() == 'printer_types.html.twig' || $Product->getTemplateKey() == 'printer_cartridges.html.twig'){
$custom_breadcrumbs[] = [
'name' => $Product->getFullLabel(),
'url' => ($Settings->getUri() ? '/' . $Settings->getUri() : $this->generateUrl('homepage')) . 'printers/' . $Product->getSlug()
];
}else{
$custom_breadcrumbs[] = [
'name' => $Product->getFullLabel(),
'url' => ($Settings->getUri() ? '/' . $Settings->getUri() : $this->generateUrl('homepage')) . 'product/' . $Product->getNumber() . '/' . $Product->getSlug()
];
}
$this->breadcrumbs->addItem($Category->getLabel(), ($Settings->getUri() ? $Settings->getUri() : $this->generateUrl('homepage') . (!empty($this->Settings->getBaseUri()) ? substr($this->Settings->getBaseUri(),1) . '/' : '')) . $Category->getUri());
$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());
// Validate
if(!$Product->getEnabled()){
throw $this->createNotFoundException('Product ' . $Product->getId() . ' not found');
}
$Page->setTitle($Product->getLabel());
// Prepare specs
$specsList = [];
$specs = [];
foreach($Product->getCategory() as $_Category){
foreach($_Category->getCategory()->getSpecGroups() as $_SpecGroup){
if(!$this->Webshop->getSpecGroups()->contains($_SpecGroup)) continue;
foreach($_SpecGroup->getSpecs() as $_Spec){
if(!$Webshop->getSpecs()->contains($_Spec)) continue;
$specsList[] = $_Spec;
}
}
}
foreach($Product->getSpecGroups() as $_SpecGroup){
if(!$this->Webshop->getSpecGroups()->contains($_SpecGroup)) continue;
foreach($_SpecGroup->getSpecs() as $_Spec){
if(!$Webshop->getSpecs()->contains($_Spec)) continue;
$specsList[] = $_Spec;
}
}
/*foreach($Product->getLinkedProducts()->first()->getSpecGroups() as $_SpecGroup){
if(!$this->Webshop->getSpecGroups()->contains($_SpecGroup)) continue;
foreach($_SpecGroup->getSpecs() as $_Spec){
if(!$Webshop->getSpecs()->contains($_Spec)) continue;
$specsList[] = $_Spec;
}
}*/
$selectSpecs = [];
$specsSorted = [];
foreach($specsList as $_Spec){
if($_Spec->getHidden() == true) { continue; }
if($_Spec->getOptDetail() != true) { continue; }
if($_Spec->getType() == 'dropdown'){
$default = [];
$available = $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findBy(['spec' => $_Spec], ['position' => 'asc']);
$SpecValues = $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findValuesByProduct(
$_Spec,
$Product
);
}else{
$default = '';
$available = null;
$SpecValues = $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findValuesByProduct(
$_Spec,
$Product
);
}
if($_Spec->getMultiple() && $_Spec->getChooseMultiple() && !empty($SpecValues)){
$selectSpecs[$_Spec->getId()] = ['Spec' => $_Spec, 'values' => $SpecValues];
}
$groups = [];
$lastGroup = null;
if($_Spec->getGroups()->count()){
foreach($_Spec->getGroups() as $_SpecGroup){
$lastGroup = $_SpecGroup;
$groups[] = $_SpecGroup->getLabel();
}
}
$spdata = [
'id' => $_Spec->getId(),
'label' => $_Spec->getLabel(),
'code' => $_Spec->getCode(),
'value' => (!empty($SpecValues) ? $SpecValues : $default),
'available' => $available,
'groups' => $groups,
'multiple' => $_Spec->getMultiple(),
'choose' => $_Spec->getChooseMultiple(),
'required' => $_Spec->getRequired(),
'type' => $_Spec->getType(),
'hidden' => $_Spec->getHidden(),
'opt_filter' => $_Spec->getOptFilter(),
'opt_detail' => $_Spec->getOptDetail(),
];
$specs[$_Spec->getId()] = $spdata;
if($lastGroup){
$specsSorted[$lastGroup->getLabel()][$_Spec->getId()] = $spdata;
}
}
// dump($specs);die();
$MatchLinked = null;
$FirstLinked = null;
$OriginalProduct = $Product;
$filterTarget = [];
$filterTarget_readable = [];
if(!empty($_GET['filter'])){
foreach($_GET['filter'] as $spec_id => $options){
$Spec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->find($spec_id);
foreach($options as $v){
$SpecValue = $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findOneBy(['spec' => $Spec, 'value' => $v]);
if(!empty($SpecValue)){
$filterTarget[] = $spec_id . '+' . $SpecValue->getId();
$filterTarget_readable[] = $Spec->getLabel() . '(' . $spec_id . ')+' . $SpecValue->getValue() . '(' . $SpecValue->getId() . ')';
}
}
}
}
$configHex = [];
$configSpecs = [];
$configSpecs_alt = [];
$configSpecs_done = [];
$configSpecs_data = [];
$configSpecsObjects = [];
$usedSpecIds = [];
if($Product->getType() == 1){
// Prepare specs
$configSpecs = [];
$configSpecs_pos = [];
foreach($Product->getLinkedProducts() as $LinkedProduct){
if($LinkedProduct->getEnabled()){
foreach($LinkedProduct->getSpecValues() as $SpecValue){
$configHex[$SpecValue->getValue()] = $SpecValue->getHex();
/* if($FirstLinked == null){
$FirstLinked = $LinkedProduct;
} */
$Spec = $SpecValue->getSpec();
if(!is_null($Spec) && ($Spec->getType() == 'dropdown' || $Spec->getType() == 'color')){
if(!$Spec->getChooseMultiple()){
if($Spec->getOptFilter() != true) { continue; }
$configSpecs_pos[$Spec->getId()] = $Spec->getPosition();
$groups = [];
if($Spec->getGroups()->count()){
foreach($Spec->getGroups() as $_SpecGroup){
$groups[] = $_SpecGroup->getLabel();
}
}
// Required for parent
$specs[$Spec->getId()] = [
'id' => $Spec->getId(),
'label' => $Spec->getLabel(),
'code' => $Spec->getCode(),
'value' => null,
'available' => null,
'groups' => $groups,
'multiple' => $Spec->getMultiple(),
'choose' => $Spec->getChooseMultiple(),
'required' => $Spec->getRequired(),
'type' => $Spec->getType(),
'opt_filter' => $Spec->getOptFilter(),
'opt_detail' => $Spec->getOptDetail(),
// 'hidden' => $Spec->getHidden(),
];
/*if($Spec->getMultiple() && $Spec->getChooseMultiple()){
$selectSpecs[$Spec->getId()] = $Spec;
}*/
$configSpecsObjects[$SpecValue->getId()] = $SpecValue;
// if($Spec->getOptDetail()){
if(!isset($configSpecs[$Spec->getId()][$SpecValue->getPosition() . '+' . $SpecValue->getId()])){
$configSpecs[$Spec->getId()][$SpecValue->getPosition() . '+' . $SpecValue->getId()] = [];
}
$configSpecs[$Spec->getId()][$SpecValue->getPosition() . '+' . $SpecValue->getId()][] = $LinkedProduct->getId();
$configSpecs_alt[$Spec->getId() . '+' . $SpecValue->getId()][] = $LinkedProduct->getId();
//ksort($configSpecs[$Spec->getId()]);
$usedSpecIds[] = $Spec->getId();
// }
}
}
}
}
}
}
$sorted = [];
if(!empty($configSpecs_pos)){
asort($configSpecs_pos);
foreach($configSpecs_pos as $k => $pos){
$sorted[$k] = [];
}
}
// Sort configSpecs afterwards
foreach($configSpecs as $specid => $values){
foreach($values as $k => $v){
$k = explode('+', $k);
$sorted[$specid][$k[0]][$k[1]] = $v;
ksort($sorted[$specid]);
}
}
$configSpecs = [];
foreach($sorted as $specid => $d1){
foreach($d1 as $sort => $d2){
foreach($d2 as $svid => $vs){
$configSpecs[$specid][$sort . '+' . $svid] = $vs;
}
}
}
// Find child product by filters
$foundCount = [];
foreach($filterTarget as $targetSpec){
if(!empty($configSpecs_alt[$targetSpec])){
// dump($configSpecs_alt[$targetSpec]);die();
if(count($configSpecs_alt[$targetSpec]) > 0){
foreach($configSpecs_alt[$targetSpec] as $id){
if(empty($foundCount[$id])) $foundCount[$id] = 0;
$foundCount[$id]++;
}
// $FirstLinked = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($configSpecs_alt[$targetSpec][0]);
}
}
}
foreach($foundCount as $id => $count){
if($count == count($filterTarget)){
$FirstLinked = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($id);
}
}
foreach($configSpecs as $spec_id => $values){
foreach($values as $pos_data => $links){
$pos_data = explode('+', $pos_data);
$configSpecs_done[$spec_id][$configSpecsObjects[$pos_data[1]]->getValue()] = $links;
$configSpecs_data[$spec_id][$configSpecsObjects[$pos_data[1]]->getValue()] = $configSpecsObjects[$pos_data[1]]->getId();
}
}
/*foreach($usedSpecIds as $id){
ksort($configSpecs[$id]);
}*/
// dump($configSpecs);die();
// Update views
$em = $this->getDoctrine()->getManager();
$Product->setViews((int)$Product->getViews() + 1);
// Update real selling price
/*if($this->containerInterface->getParameter('kernel.environment') == 'dev'){
dump($Product->getRealPrice());
dump($Product->getRealPriceIncl());
die();
}*/
/* if($FirstLinked){
if($Product->getSellPrice() != $FirstLinked->getSellPrice()){
$Product->setSellPrice($FirstLinked->getSellPrice());
}
if($Product->getSellPriceIncl() != $FirstLinked->getSellPriceIncl()){
$Product->setSellPriceIncl($FirstLinked->getSellPriceIncl());
}
}else{
$Product->setSellPrice($Product->getRealPrice());
$Product->setSellPriceIncl($Product->getRealPriceIncl());
} */
$em->persist($Product);
$em->flush();
if($FirstLinked){
$Alt = $Product;
if($this->WebshopSettings->getInitializeConfigurable()){
// Keep configurable global
$Alt = $FirstLinked;
}else{
$Product = $FirstLinked;
}
// Prepare specs
$specsList = [];
$specs = [];
foreach($FirstLinked->getCategory() as $_Category){
foreach($_Category->getCategory()->getSpecGroups() as $_SpecGroup){
if(!$this->Webshop->getSpecGroups()->contains($_SpecGroup)) continue;
foreach($_SpecGroup->getSpecs() as $_Spec){
if(!$Webshop->getSpecs()->contains($_Spec)) continue;
$specsList[] = $_Spec;
}
}
}
foreach($FirstLinked->getSpecGroups() as $_SpecGroup){
if(!$this->Webshop->getSpecGroups()->contains($_SpecGroup)) continue;
foreach($_SpecGroup->getSpecs() as $_Spec){
if(!$Webshop->getSpecs()->contains($_Spec)) continue;
$specsList[] = $_Spec;
}
}
// dump($specsList);die();
$selectSpecs = [];
foreach($specsList as $_Spec){
if($_Spec->getHidden() == true) continue;
if($_Spec->getType() == 'dropdown'){
$default = [];
$available = $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findBy(['spec' => $_Spec], ['position' => 'asc']);
$SpecValues = $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findValuesByProduct(
$_Spec,
$Product
);
}else{
$default = '';
$available = null;
$SpecValues = $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findValuesByProduct(
$_Spec,
$Product
);
}
if($_Spec->getMultiple() && $_Spec->getChooseMultiple() && !empty($SpecValues)){
$selectSpecs[$_Spec->getId()] = ['Spec' => $_Spec, 'values' => $SpecValues];
}
$groups = [];
if($_Spec->getGroups()->count()){
foreach($_Spec->getGroups() as $_SpecGroup){
$groups[] = $_SpecGroup->getLabel();
}
}
$specs[$_Spec->getId()] = [
'id' => $_Spec->getId(),
'label' => $_Spec->getLabel(),
'code' => $_Spec->getCode(),
'value' => (!empty($SpecValues) ? $SpecValues : $default),
'available' => $available,
'groups' => $groups,
'multiple' => $_Spec->getMultiple(),
'choose' => $_Spec->getChooseMultiple(),
'required' => $_Spec->getRequired(),
'type' => $_Spec->getType(),
'opt_filter' => $_Spec->getOptFilter(),
'opt_detail' => $_Spec->getOptDetail(),
'hidden' => $_Spec->getHidden(),
];
}
}
// dump($specs); die();
// Find favorite products
$isLinked = false;
$WebshopUser = $this->getDoctrine()->getRepository('TrinityWebshopBundle:User')->findOneByUser($this->getUser());
if($WebshopUser){
foreach($WebshopUser->getProductList() as $ItemList){
foreach($ItemList->getProducts() as $p){
if($p == $Product){
$isLinked = true;
}
}
}
}
$metatags = $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getBySystem(0, (int)$Page->getId(), true);
$systemMetatags = $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getBySystem(1, false, false);
$children_count = [];
$children = [];
$carFilterName = ['merk' => '', 'model' => '', 'bouwjaar' => ''];
$rootCategory = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findOneByLabel('Onderdelen');
if(!empty($rootCategory)){
$spec_filter_checked = [];
foreach($Product->getSpecValues() as $SV){
$Spec = $SV->getSpec();
if(!empty($Spec) && in_array($Spec->getId(), [265, 266, 267])){
if($Spec->getId() == 265){
$carFilterName['merk'] = $SV->getValue();
}
if($Spec->getId() == 266){
$carFilterName['model'] = $SV->getValue();
}
if($Spec->getId() == 267){
$carFilterName['bouwjaar'] = $SV->getValue();
}
$spec_filter_checked[$Spec->getId()] = $SV->getValue();
}
}
if(!empty($spec_filter_checked)){
$children_raw = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findCategoriesWithSpecs($rootCategory, $spec_filter_checked, 'root');
foreach($children_raw as $c){
if($c['id']){
$children[] = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->find($c['id']);
$children_count[$c['id']] = $c['num'];
}
}
}
}
$category_view_query = '?merk=' . $carFilterName['merk'] . '&model=' . $carFilterName['model'] . '&bouwjaar=' . $carFilterName['bouwjaar'] . '';
$carFilterName = implode(' ', $carFilterName);
$total_rating = ['total' => 0, 'rating_total' => 0, 'avg' => 0];
$total_rating_raw = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Review')->productTotal($Product->getId());
$total_rating_rawTwo = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Review')->countTotalByProduct($Product->getId());
if(!empty($total_rating_raw[0])){
$total_rating = $total_rating_raw[0];
}
if(!empty($total_rating_rawTwo)){
$total_rating['total'] = $total_rating_rawTwo;
}
$total_rating['avg_up'] = (ceil($total_rating['avg'] * 2) / 2);
$specs_disabled_format = [];
$simpSpec = $Product->getSimplifiedSpecValues(true);
if(!empty($simpSpec)){
$svid = $simpSpec['svid'];
$checkSpec = $simpSpec['Spec'];
$tmp_all = [];
$tmp_enabled = [];
$tmp_disabled = [];
$tmp_matching = [];
$sv_obj = [];
foreach($OriginalProduct->getLinkedProducts() as $ChildProduct){
foreach($ChildProduct->getSpecValues() as $SV){
if($svid){
if($SV->getId() == $svid){
$tmp_matching[] = $ChildProduct;
}else{
if($checkSpec != $SV->getSpec()){
$tmp_all[$SV->getId()] = $SV->getValue();
$sv_obj[$SV->getId()] = $SV;
}
}
}else{
$tmp_matching[] = $ChildProduct;
$tmp_all[$SV->getId()] = $SV->getValue();
$sv_obj[$SV->getId()] = $SV;
}
}
}
foreach($tmp_matching as $ChildProduct){
foreach($ChildProduct->getSpecValues() as $SV){
if($checkSpec != $SV->getSpec() && $ChildProduct->canOrder()){
$tmp_enabled[$SV->getId()] = $SV->getValue();
$sv_obj[$SV->getId()] = $SV;
}
}
}
$tmp_disabled = array_diff($tmp_all, $tmp_enabled);
foreach($tmp_disabled as $svid => $svlabel){
if(!empty($sv_obj[$svid]->getSpec())){
$specs_disabled_format[$sv_obj[$svid]->getSpec()->getId()][] = $svlabel;
}
}
}
if($Settings->getPicqerChoice() == 1 && !empty($Settings->getPicqerApikey()) && !empty($Settings->getPicqerUrl())){
$Picqer = new Picqer($Settings->getPicqerApikey(), $Settings->getPicqerUrl());
if($Settings->getPicqerFulfillment()){
if(!empty($Settings->getPicqerFulfillmentId())){
$fulfilment_id = $Settings->getPicqerFulfillmentId();
} else {
$fulfilment_id = null;
}
} else {
$fulfilment_id = null;
}
$stock = $Picqer::checkStock($Product, $fulfilment_id);
if($stock !== "Product not found in Picqer" && $stock !== "Product empty"){
if($Product->getStockAmount() != $stock){
$Product->setStockAmount($stock);
}
}
}
if(preg_match('/price_incl.*?(asc|desc)/', $sort, $m)){
$sort = 'sell_price ' . $m[1];
}
$products_data = [];
$priceRange = [(int)$Product->getMin(),(int)$Product->getMax()];
if($Product->getTemplateKey() == 'printer_cartridges.html.twig'){
// Currently Pelikan specific
$spec_filter_checked = [];
$get_q = '';
$get_qo = '';
$products_data = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->search(null, array(
'spec_filter_checked' => $spec_filter_checked,
'relation' => $Product,
'visible' => true,
'page' => 1,
/*'limit' => [
'start' => 0,
'limit' => 9
],*/
'q' => $get_q,
'qo' => $get_qo,
'filters' => $spec_filter_checked,
), $sort, $sort_dir, ($Settings->getPagination() == 'none'), false, (!empty($_GET['page']) && is_numeric($_GET['page']) ? $_GET['page'] : 1), $this->WebshopSettings->getPerPage());
}
$activeRelations = [];
foreach($Product->getRelations() as $Relation){
if($Relation->getEnabled() && $Relation->getVisible()){
$activeRelations[] = $Relation;
}
}
//dump($Product->getId());
//dump($Product->getRelations()->count());
//dump($activeRelations);die();
$canonical_url = '';
$foundCategory = null;
foreach ($Product->getCategory() as $catProd)
{
if (empty($foundCategory)) {
$foundCategory = $catProd->getCategory();
} else if ($Settings->getCanonicalType() == 'first-main-cat') {
if (!empty($foundCategory->getParent()) && $foundCategory->getParent()->getId() == $catProd->getCategory()->getId()) {
$foundCategory = $catProd->getCategory();
}
} else if (is_null($Settings->getCanonicalType()) || $Settings->getCanonicalType() == 'first-sub-cat') {
$subCat = $catProd->getCategory();
$tempCat = null;
$subLoop = true;
do {
if (!empty($subCat->getParent()) &&
$subCat->getParent()->getId() == $foundCategory->getId()) {
$tempCat = $subCat;
} else if (!empty($subCat->getParent()) &&
!empty($subCat->getParent()->getParent()) &&
$subCat->getParent()->getParent()->getId() == $foundCategory->getId()) {
$tempCat = $subCat;
} else if (!empty($subCat->getParent()) &&
!empty($subCat->getParent()->getParent()) &&
!empty($subCat->getParent()->getParent()->getParent()) &&
$subCat->getParent()->getParent()->getParent()->getId() == $foundCategory->getId()) {
$tempCat = $subCat;
} else {
$subLoop = false;
}
$subCat = $subCat->getParent();
} while ($subLoop);
if (!empty($tempCat)) {
$foundCategory = $tempCat;
}
}
}
if (!empty($foundCategory)) {
$canonical_url = $foundCategory->getUri() . '/' . $Product->getSlug();
}
$Product = $this->parseEntityPageUrls($Product);
$Settings = $this->parseSettingsPageUrls($Settings);
$specsByGroup = [];
foreach($specs as $id => $spec){
if(!empty($spec['groups'])){
foreach($spec['groups'] as $g){
$specsByGroup[$g][$id] = $spec;
}
}else{
$specsByGroup['Default'][$id] = $spec;
}
}
if($this->Meta && !empty($Product)){
$this->Meta->registerView($request, 'webshop_product', $Product->getId(), $Product->getLabel());
}
$response = $this->render('@TrinityWebshop/front/product.html.twig', $this->attributes([
'Category' => $Category,
'Product' => $Product,
'OriginalProduct' => $OriginalProduct,
'firstAvailable' => $firstAvailable,
'configHex' => $configHex,
'specs' => $specs,
'specsSorted' => $specsSorted,
'specsByGroup' => $specsByGroup,
'configSpecs' => $configSpecs_done,
'configSpecsIds' => $configSpecs_data,
'selectSpecs' => $selectSpecs,
'metatags' => $metatags,
'systemMetatags' => $systemMetatags,
'Page' => $Page,
'usedSpecIds' => $usedSpecIds,
'products_data' => $products_data,
'priceRange' => $priceRange,
'sort' => $sort,
'productHistoryObjects' => (array)$productHistoryObjects,
'productRelatedObjects' => (array)$productRelatedObjects,
'WebshopSettings' => $Settings,
'isLinked' => $isLinked,
'bodyClass' => 'product-detail',
'custom_breadcrumbs' => $custom_breadcrumbs,
'locale' => '',
'center_lat' => $center_lat,
'center_lng' => $center_lng,
'center_zoom' => $center_zoom,
'specs_disabled' => $specs_disabled_format,
'category_view' => $children,
'category_view_count' => $children_count,
'category_view_query' => $category_view_query,
'canonical_url' => $canonical_url,
'carFilterName' => $carFilterName,
'total_rating' => $total_rating,
'activeRelations' => $activeRelations,
'recipes' => $recipes,
'RecipesPage' => $RecipesPage,
]));
if ($allowCache) {
$Product->setCacheData($response->getContent());
}
//$response = $this->responseRewriteOutput($response, false, false);
return $response;
}
/**
*
*
* ==============================================================================================================
* ==============================================================================================================
* ==============================================================================================================
* ==============================================================================================================
*
* ROOT CATEGORY OVERVIEW
*
* ==============================================================================================================
* ==============================================================================================================
* ==============================================================================================================
* ==============================================================================================================
*
*
*/
elseif($Category != null && $Category->getShowSubCategories()){
/*
Categorie shows sub categories, not products
*/
$Category = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->find($request->get('categoryId'));
$Page->setTitle($Category->getLabel());
$allRootCategories = [];
if($Category->getShowAll()){
$allRootCategories = $this->getDoctrine()->getRepository(Category::class)->findBy(['parent' => null], ['position' => 'asc']);
}
$children = [];
$doSearch = false;
$noResults = false;
if(!empty($_GET['r']) && $_GET['r'] == 'no-results'){
$noResults = true;
}
$brandAndModelArr = [];
$brandAndModel = '[]';
$cachedir = preg_replace('/src\/.*?$/', '', __DIR__) . 'var/cache/';
if(file_exists($cachedir . 'brands_sorted.json')){
$brandAndModelArr_tmp = json_decode(file_get_contents($cachedir . 'brands_sorted.json'), true);
$brandAndModelArr = [];
if(!is_array($brandAndModelArr_tmp)) $brandAndModelArr_tmp = [];
else{
if(!empty($brandAndModelArr_tmp[$Category->getId()])){
$brandAndModelArr = $brandAndModelArr_tmp[$Category->getId()];
}
}
$brandAndModel = json_encode($brandAndModelArr);
}
$typesArr = [];
$types = '[]';
$cachedir = preg_replace('/src\/.*?$/', '', __DIR__) . 'var/cache/';
if(file_exists($cachedir . 'types_sorted.json')){
$typesArr_tmp = json_decode(file_get_contents($cachedir . 'types_sorted.json'), true);
$typesArr = [];
if(!is_array($typesArr_tmp)) $typesArr_tmp = [];
else{
if(!empty($typesArr_tmp[$Category->getId()])){
$typesArr = $typesArr_tmp[$Category->getId()];
}
}
$types = json_encode($typesArr);
}
$spec_query = '';
$spec_filter = [];
$licenseplate = null;
if (!$Settings->getDisableRememberSearch()) {
if(!empty($this->get('session')->get('ecomm_spec_filter'))){
$spec_filter = $this->get('session')->get('ecomm_spec_filter');
}
if(!empty($this->get('session')->get('ecomm_spec_plate'))){
$licenseplate = $this->get('session')->get('ecomm_spec_plate');
}
/*if(!empty($this->get('session')->get('ecomm_spec_query'))){
$spec_query = $this->get('session')->get('ecomm_spec_query');
}*/
}
if(!empty($_GET['clearplate'])){
$licenseplate = '';
$spec_filter = [];
$this->get('session')->set('ecomm_spec_plate', '');
$this->get('session')->set('ecomm_spec_filter', []);
}
/*$BrandsSpec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->findOneBy(['label' => 'Merk']);
$ModelsSpec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->findOneBy(['label' => 'Model']);*/
$category_label = '';
if(!empty($_GET['c'])){
$C = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->find($_GET['c']);
$category_label = $C->getLabel();
}
if(!empty($_GET['q']) && $_GET['q'] != 'undefined'){
$spec_query = $_GET['q'];
// $this->get('session')->set('ecomm_spec_query', $_GET['q']);
}else{
if(isset($_GET['q'])){
// $this->get('session')->set('ecomm_spec_query', '');
}
}
if(!empty($spec_query)){
$spec_query_tmp = explode(' ', $spec_query);
$modelsToSearch = [];
foreach($spec_query_tmp as $qpi => $qp){
foreach($brandAndModelArr as $brand => $models){
if(strtolower($brand) == strtolower($qp)){
$spec_filter['Merk'] = $brand;
unset($spec_query_tmp[$qpi]);
$modelsToSearch = $models;
break;
}
}
}
foreach($spec_query_tmp as $qpi => $qp){
foreach($modelsToSearch as $model){
if(strtolower($model) == strtolower($qp)){
$spec_filter['Model'] = $model;
unset($spec_query_tmp[$qpi]);
break;
}
}
}
$spec_query = implode(' ', $spec_query_tmp);
}
if($spec_query == 'undefined'){
$spec_query = '';
// $this->get('session')->set('ecomm_spec_query', '');
}
if(!empty($_GET['merk'])){
$spec_filter['Merk'] = $_GET['merk'];
if(!empty($_GET['model'])){
$spec_filter['Model'] = $_GET['model'];
if(!empty($_GET['bouwjaar'])){
$spec_filter['Bouwjaar'] = $_GET['bouwjaar'];
}
}
$this->get('session')->set('ecomm_spec_filter', $spec_filter);
}
if(!empty($_GET['type']) && $_GET['type'] != 'Alle onderdelen'){
$spec_filter['Type Onderdeel'] = $_GET['type'];
$this->get('session')->set('ecomm_spec_filter', $spec_filter);
}else{
if(isset($_GET['type']) && isset($spec_filter['Type Onderdeel'])){
unset($spec_filter['Type Onderdeel']);
$this->get('session')->set('ecomm_spec_filter', $spec_filter);
}
}
if(!empty($_GET['licenseplate'])){
$licenseplate = $_GET['licenseplate'];
}
$model = null;
$type = null;
$year = null;
if(!empty($licenseplate)){
$api_url = 'https://services.onderdelenlijn.nl/parts/v7.asmx?WSDL';
$user = 'info@beyonit.nl';
$pass = 'fUAJT6!XP';
$Webshop = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($this->language, $this->Settings);
$SOAP_LOCATION_APP = $api_url;
$soapClient = new \SoapClient($SOAP_LOCATION_APP, ["trace" => 1, "exception" => 0, 'cache_wsdl' => WSDL_CACHE_NONE, 'soap_version' => SOAP_1_2]);
$soapMessage = [
'Credentials' => [
'Username' => $user,
'Password' => $pass,
],
'Parameters' => [
'Culture' => "NL",
'TviRequest' => [
'Type' => 'LicensePlate',
'Value' => $licenseplate
]
]
];
$soapResult = $soapClient->TviData($soapMessage);
$res = json_decode(json_encode($soapResult), true);
if(!empty($res["TviDataResult"]["Result"])){
$array = $res["TviDataResult"]["Result"];
$model = (!empty($array["Basic"]["MakeModel"]["MakeName"]) ? $array["Basic"]["MakeModel"]["MakeName"] : null);
$type = (!empty($array["Basic"]["MakeModel"]["ModelName"]) ? $array["Basic"]["MakeModel"]["ModelName"] : null);
$year = (!empty($array["Basic"]["Constructed"]['Year']) ? $array["Basic"]["Constructed"]['Year'] : null);
$month = (!empty($array["Basic"]["Constructed"]['Month']) ? $array["Basic"]["Constructed"]['Month'] : null);
$spec_filter['Merk'] = $model;
$spec_filter['Model'] = $type;
$spec_filter['Bouwjaar'] = $year;
}
}
if(!empty($spec_filter['Merk']) && $spec_filter['Merk'] == 'Alle merken'){
if($model){
$spec_filter['Merk'] = $model;
$this->get('session')->set('ecomm_spec_filter', $spec_filter);
}else{
unset($spec_filter['Merk']);
}
}
if(!empty($spec_filter['Model']) && $spec_filter['Model'] == 'Alle modellen'){
if($type){
$spec_filter['Model'] = $type;
$this->get('session')->set('ecomm_spec_filter', $spec_filter);
}else{
unset($spec_filter['Model']);
}
}
if(!empty($spec_filter['Type Onderdeel']) && $spec_filter['Type Onderdeel'] == 'Alle onderdelen'){
unset($spec_filter['Type Onderdeel']);
}
if(!empty($_GET['drop'])){
if($_GET['drop'] == 'all'){
// $this->get('session')->set('ecomm_spec_query', '');
$spec_query = '';
$spec_filter = [];
$this->get('session')->set('ecomm_spec_filter', []);
$this->get('session')->set('ecomm_spec_plate', '');
}else if(preg_match('/_/', $_GET['drop'])){
$_GET['drop'] = explode('_', $_GET['drop']);
// $q = explode(' ', $this->get('session')->get('ecomm_spec_query'));
foreach($q as $k => $v){
if($_GET['drop'][1] == $k){
unset($q[$k]);
}
}
$q = implode(' ', $q);
// $this->get('session')->set('ecomm_spec_query', $q);
$spec_query = $q;
}else{
if($_GET['drop'] == 'q'){
// Drop search filter
// $this->get('session')->set('ecomm_spec_query', '');
$spec_query = '';
}else{
// Drop spec filter
$spec_id = $_GET['drop'];
$Spec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->find($spec_id);
if(!empty($Spec) && isset($spec_filter[$Spec->getLabel()])){
unset($spec_filter[$Spec->getLabel()]);
$this->get('session')->set('ecomm_spec_filter', $spec_filter);
$this->get('session')->set('ecomm_spec_plate', '');
}
}
}
}
$spec_filter_checked = [];
$filters_visual = [];
if(!empty($spec_filter) && is_array($spec_filter)){
foreach($spec_filter as $specLabel => $value){
// TMP IGNORE
if(in_array($specLabel, ['Bouwmaand'])) continue;
$Spec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->findOneBy(['label' => $specLabel]);
if(!empty($Spec)){
$spec_filter_checked[$Spec->getId()] = $value;
$filters_visual[$Spec->getId()] = ['label' => ($Spec->getLabel() == 'Model compatibiliteit' ? 'Bouwjaar' : $Spec->getLabel()), 'value' => $value];
}
}
}
if(!empty($spec_query)){
$spec_filter_checked['q'] = explode(' ', $spec_query);
// $filters_visual['q'] = ['label' => 'Zoeken', 'value' => implode(', ', $spec_filter_checked['q'])];
foreach($spec_filter_checked['q'] as $qpart){
if(!isset($filters_visual['q'])){
$filters_visual['q'] = [];
}
$filters_visual['q'][] = ['label' => 'Zoeken', 'value' => $qpart];
}
}
$level = 'root';
if(count($Category->getParents()) > 0){
$level = 'sub';
}
if($level == 'sub'){
$custom_breadcrumbs[] = [
'name' => $Category->getParent()->getLabel(),
'url' => ($Settings->getUri() ? '/' . $Settings->getUri() : $this->generateUrl('homepage')) . $Category->getParent()->getUri()
];
}
$custom_breadcrumbs[] = [
'name' => $Category->getLabel(),
'url' => ($Settings->getUri() ? '/' . $Settings->getUri() : $this->generateUrl('homepage')) . $Category->getUri()
];
$children_count = [];
if(!empty($spec_filter_checked)){
$doSearch = true;
$redirectToId = null;
$children = [];
$children_raw = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findCategoriesWithSpecs($Category, $spec_filter_checked, $level);
// Check if only one category
if(count($children_raw) == 1 && !empty($children_raw[0])){
$tmp_id = $children_raw[0]['id'];
$redirectToId = $children_raw[0]['id'];
// Test sub
$sub_children_raw = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findCategoriesWithSpecs($tmp_id, $spec_filter_checked, 'sub');
if(count($sub_children_raw) == 1 && !empty($sub_children_raw[0])){
$redirectToId = $sub_children_raw[0]['id'];
}
}
if(!empty($redirectToId)){
// Redirect to category
$CatRedirect = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->find($redirectToId);
return $this->redirectToRoute($CatRedirect->getSlugKey());
}
foreach($children_raw as $c){
if($c['id']){
$children[] = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->find($c['id']);
$children_count[$c['id']] = $c['num'];
}
}
}
if(!$doSearch){
// No search, show categories index
$children = $Category->getChildren();
/*if($this->containerInterface->getParameter('kernel.environment') == 'dev'){
dump($children->last());die();
}*/
if($level == 'root'){
foreach($children as $Child){
if($Child->getHidden()) continue;
$children_count[$Child->getId()] = 0;
foreach($Child->getChildren() as $SubChild){
$children_count[$Child->getId()] += $SubChild->getProducts()->count();
}
}
}else{
foreach($children as $Child){
if($Child->getHidden()) continue;
$children_count[$Child->getId()] = $Child->getProducts()->count();
}
}
}
$Category = $this->parseEntityPageUrls($Category);
$response = $this->render('@TrinityWebshop/front/root_category.html.twig', $this->attributes([
'Category' => $Category,
'Page' => $Page,
'children' => $children,
'noResults' => $noResults,
'systemMetatags' => $systemMetatags,
'licenseplate' => $licenseplate,
'brandAndModel' => $brandAndModel,
'brandAndModelArr' => $brandAndModelArr,
'types' => $types,
'typesArr' => $typesArr,
'category_label' => $category_label,
'custom_breadcrumbs' => $custom_breadcrumbs,
'children_count' => $children_count,
'filters_visual' => $filters_visual,
'spec_filter' => $spec_filter,
'merk' => (!empty($spec_filter['Merk']) ? $spec_filter['Merk'] : ''),
'model' => (!empty($spec_filter['Model']) ? $spec_filter['Model'] : ''),
'bouwjaar' => (!empty($spec_filter['Bouwjaar']) ? $spec_filter['Bouwjaar'] : ''),
'type' => (!empty($spec_filter['Type']) ? $spec_filter['Type'] : ''),
'q' => $spec_query,
'licensepate' => (!empty($spec_filter['licensepate']) ? $spec_filter['licensepate'] : ''),
'bodyClass' => 'root-category-view',
'allRootCategories' => $allRootCategories,
'RecipesPage' => $RecipesPage,
]));
//$response = $this->responseRewriteOutput($response, false, false);
return $response;
}
/**
*
*
* ==============================================================================================================
* ==============================================================================================================
* ==============================================================================================================
* ==============================================================================================================
*
* CATEGORY DETAIL / PRODUCT OVERVIEW
*
* ==============================================================================================================
* ==============================================================================================================
* ==============================================================================================================
* ==============================================================================================================
*
*
*/
else{
$filters = [];
if ($request->query->get('q')) {
$filters['q'] = $request->query->get('q');
}
if ($request->query->get('category')) {
$filters['category'] = $request->query->get('category');
}
$webshop_tags = $this->getDoctrine()->getRepository(Tag::class)->findAll();
if (empty($_GET['q']) && !empty($_GET['brand']) && isset($_GET['model'])) {
$brand_prod = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($_GET['brand']);
$model_prod = null;
if(!empty($_GET['model'])){
$model_prod = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($_GET['model']);
}
if(!empty($brand_prod)){
if(!empty($model_prod)){
if((int)$this->WebshopSettings->getUriType() == 1){
$productUrl = '';
$productUrl .= ($Webshop->getSettings()->getUri() ? '/' . $Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
// $productUrl .= $productname;
// $productUrl .= '/' . $model_prod->getNumber();
$productUrl .= $model_prod->getCategory()->first()->getCategory()->getUri();
$productUrl .= '/' . $model_prod->getSlug();
}else{
$productUrl = '';
$productUrl .= ($Webshop->getSettings()->getUri() ? '/' . $Webshop->getSettings()->getUri() : $this->generateUrl('homepage') . ($Webshop->getCmssettings()->getBaseUri() ? $Webshop->getCmssettings()->getBaseUri() . '/' : ''));
//$productUrl .= ($Webshop->getSettings()->getUri() ? '/' . $Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
$productUrl .= $model_prod->getCategory()->first()->getCategory()->getUri();
$productUrl .= '/' . $model_prod->getSlug();
$productUrl = str_replace('//', '/', $productUrl);
}
}else{
if((int)$this->WebshopSettings->getUriType() == 1){
$productUrl = '';
$productUrl .= ($Webshop->getSettings()->getUri() ? '/' . $Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
// $productUrl .= $productname;
// $productUrl .= '/' . $model_prod->getNumber();
$productUrl .= $brand_prod->getCategory()->first()->getCategory()->getUri();
$productUrl .= '/' . $brand_prod->getSlug();
}else{
$productUrl = '';
$productUrl .= ($Webshop->getSettings()->getUri() ? '/' . $Webshop->getSettings()->getUri() : $this->generateUrl('homepage') . ($Webshop->getCmssettings()->getBaseUri() ? $Webshop->getCmssettings()->getBaseUri() . '/' : ''));
//$productUrl .= ($Webshop->getSettings()->getUri() ? '/' . $Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
$productUrl .= $brand_prod->getCategory()->first()->getCategory()->getUri();
$productUrl .= '/' . $brand_prod->getSlug();
$productUrl = str_replace('//', '/', $productUrl);
}
}
header('Location: ' . $productUrl);
exit;
}
}
/*$brandAndModel = [];
$cachedir = preg_replace('/src\/.*?$/', '', __DIR__) . 'var/cache/';
if(file_exists($cachedir . 'brands.json')){
$brandAndModelArr = json_decode(file_get_contents($cachedir . 'brands.json'), true);
if(!is_array($brandAndModelArr)) $brandAndModelArr = [];
$brandAndModel = json_encode($brandAndModelArr);
}*/
$brandAndModelArr = [];
$brandAndModel = '[]';
if(!empty($Category)){
$cachedir = preg_replace('/src\/.*?$/', '', __DIR__) . 'var/cache/';
if(file_exists($cachedir . 'brands_sorted.json')){
$brandAndModelArr = json_decode(file_get_contents($cachedir . 'brands_sorted.json'), true);
if(!is_array($brandAndModelArr)) $brandAndModelArr = [];
else{
if(!empty($brandAndModelArr[$Category->getId()])){
$brandAndModelArr = $brandAndModelArr[$Category->getId()];
}
}
$brandAndModel = json_encode($brandAndModelArr);
}
}
$typesArr = [];
$types = '[]';
if(!empty($Category)){
$cachedir = preg_replace('/src\/.*?$/', '', __DIR__) . 'var/cache/';
if(file_exists($cachedir . 'types_sorted.json')){
$typesArr = json_decode(file_get_contents($cachedir . 'types_sorted.json'), true);
if(!is_array($typesArr)) $typesArr = [];
else{
if(!empty($typesArr[$Category->getId()])){
$typesArr = $typesArr[$Category->getId()];
}
}
$types = json_encode($typesArr);
}
}
if(!empty($request->get('categoryId')) && is_numeric($request->get('categoryId'))){
$Category = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->find($request->get('categoryId'));
}else{
throw $this->createNotFoundException('Category not found');
}
$allRootCategories = [];
if($Category->getShowAll()){
$allRootCategories = $this->getDoctrine()->getRepository(Category::class)->findBy(['parent' => null], ['position' => 'asc']);
}
if($Category->getId() == 4872 || $Category->getId() == 4871){
$this->get('session')->set('ecomm_spec_filter', []);
$this->get('session')->set('ecomm_spec_plate', '');
// $this->get('session')->set('ecomm_spec_query', '');
}
if ($Category->getHidden()) {
throw $this->createNotFoundException('Category ' . $request->get('categoryId') . ' not found [hidden]');
}
$spec_filter = [];
$spec_query = null;
$licenseplate = null;
if (!$Settings->getDisableRememberSearch()) {
if(!empty($this->get('session')->get('ecomm_spec_filter'))){
$spec_filter = $this->get('session')->get('ecomm_spec_filter');
}
if(!empty($this->get('session')->get('ecomm_spec_plate'))){
$licenseplate = $this->get('session')->get('ecomm_spec_plate');
}
/*if(!empty($this->get('session')->get('ecomm_spec_query'))){
$spec_query = $this->get('session')->get('ecomm_spec_query');
}*/
}
if(!empty($_GET['Merk'])){
$spec_filter['Merk'] = $_GET['Merk'];
$this->get('session')->set('ecomm_spec_filter', $spec_filter);
}
if(!empty($_GET['Model'])){
$spec_filter['Model'] = $_GET['Model'];
$this->get('session')->set('ecomm_spec_filter', $spec_filter);
}
if(!empty($_GET['spec'])){
foreach($_GET['spec'] as $sid => $v){
// if($sid == 11){
$spec_filter[$sid] = $v;
// }
}
}
if(isset($spec_filter['Merk']) && $spec_filter['Merk'] == 'Alle merken'){
unset($spec_filter['Merk']);
$this->get('session')->set('ecomm_spec_filter', $spec_filter);
}
if(isset($spec_filter['Model']) && $spec_filter['Model'] == 'Alle modellen'){
unset($spec_filter['Model']);
$this->get('session')->set('ecomm_spec_filter', $spec_filter);
}
if(!empty($spec_query)){
$spec_query_tmp = explode(' ', $spec_query);
$modelsToSearch = [];
foreach($spec_query_tmp as $qpi => $qp){
foreach($brandAndModelArr as $brand => $models){
if(strtolower($brand) == strtolower($qp)){
$spec_filter['Merk'] = $brand;
unset($spec_query_tmp[$qpi]);
$modelsToSearch = $models;
break;
}
}
}
foreach($spec_query_tmp as $qpi => $qp){
foreach($modelsToSearch as $model){
if(strtolower($model) == strtolower($qp)){
$spec_filter['Model'] = $model;
unset($spec_query_tmp[$qpi]);
break;
}
}
}
$spec_query = implode(' ', $spec_query_tmp);
}
$filters_visual = [];
$spec_filter_checked = [];
if(!empty($spec_filter) && is_array($spec_filter)){
foreach($spec_filter as $specLabel => $value){
// TMP IGNORE
// if(in_array($specLabel, ['Bouwjaar'])) continue;
if(is_numeric($specLabel)){
$Spec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->findOneBy(['id' => $specLabel]);
}else{
$Spec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->findOneBy(['label' => $specLabel]);
}
if(!empty($Spec)){
$spec_filter_checked[$Spec->getId()] = $value;
$filters_visual[$Spec->getId()] = ['label' => ($Spec->getLabel() == 'Model compatibiliteit' ? 'Bouwjaar' : $Spec->getLabel()), 'value' => $value];
}
}
}
if(empty($filters['q']) && !empty($spec_query)){
$filters['q'] = $spec_query;
}
if(!empty($spec_query)){
$spec_filter_checked['q'] = explode(' ', $spec_query);
// $filters_visual['q'] = ['label' => 'Zoeken', 'value' => implode(', ', $spec_filter_checked['q'])];
foreach($spec_filter_checked['q'] as $qpart){
if(!isset($filters_visual['q'])){
$filters_visual['q'] = [];
}
$filters_visual['q'][] = ['label' => 'Zoeken', 'value' => $qpart];
}
}
/*$brands = [];
$BrandsSpec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->findOneBy(['label' => 'Merk']);
$ModelsSpec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->findOneBy(['label' => 'Model']);
foreach($BrandsSpec->getValues() as $SpecValue){
if(!in_array($SpecValue->getValue(), $brands)){
$brands[] = $SpecValue->getValue();
sort($brands);
dump($SpecValue->getValue());
if($SpecValue->getProducts()->count() > 0){
foreach($ModelsSpec->getValues() as $ModelSpecValue){
if($ModelSpecValue)
}
}
}
}
dump($brands);die();*/
$this->Timer->reset();
$cats = array_reverse($Category->getParents());
foreach($cats as $cr){
$custom_breadcrumbs[] = [
'name' => $cr->getLabel(),
'url' => ($Settings->getUri() ? '/' . $Settings->getUri() : $this->generateUrl('homepage')) . $cr->getUri()
];
}
$this->Timer->mark('Load category');
$categories = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findBy(['parent' => null]);
$this->Timer->mark('Load categories');
if(empty($Category)){
return $this->redirectToRoute('homepage');
}
// Parsed wrong language category
if($Category->getWebshop() && $Category->getWebshop()->getLanguage() != $this->language){
$TmpCategory = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findOneBy([ 'slug' => $Category->getSlug(), 'webshop' => $this->Webshop ]);
if($TmpCategory){$Category = $TmpCategory; }
}
// Parsed wrong webshop
if($Category->getWebshop() != $this->Webshop){
$TmpCategory = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findOneBy([ 'slug' => $Category->getSlug(), 'webshop' => $this->Webshop ]);
if($TmpCategory){$Category = $TmpCategory; }
}
if(($Category->getWebshop() && $Category->getWebshop()->getLanguage() != $this->language) || ($Category->getWebshop() != $this->Webshop)){
return $this->redirectToRoute('homepage');
}
$Page->setTitle($Category->getLabel());
$custom_breadcrumbs[] = [
'name' => $Category->getLabel(),
'url' => ($Settings->getUri() ? '/' . $Settings->getUri() : $this->generateUrl('homepage')) . $Category->getUri()
];
$this->breadcrumbs->addItem($Category->getLabel(), ($Settings->getUri() ? '/' . $Settings->getUri() : $this->generateUrl('homepage')) . $Category->getUri());
$this->Timer->mark('Before products');
$get_q = null;
$get_qo = null;
if ($Settings->getSearchMode() && $Settings->getSearchMode() == 'or')
{
if(!empty($request->query->get('q'))){
$get_q = $request->query->get('q');
/*if(preg_match('/^([a-zA-Z]+)(\d+)$/', $get_q, $m)){
$get_q = $m[1] . ' ' . $m[2];
}
$get_q = explode(' ', $get_q);*/
if(!empty($get_q)){
/*if(preg_match('/^([a-zA-Z]+)(\d+)$/', $get_q, $m)){
$get_q = [];
$get_qo = [];
$get_qo = [];
// if(strlen($m[1]) > 2){
$get_q[] = $m[1];
// }
// if(strlen($m[2]) > 2){
$get_q[] = $m[2];
// }
$get_qo[] = $m[1] . $m[2];
$get_qo[] = $m[1] . '-' . $m[2];
$get_qo[] = $m[1] . ' ' . $m[2];
}else{*/
$f = explode(' ', $get_q);
$get_q = [];
$get_qo = [];
foreach($f as $v){
// if(strlen($v) > 2){
$get_q[] = $v;
// }
}
$get_qo[] = implode($f, '-');
$get_qo[] = implode($f, ' ');
//}
}
}
} else {
if (isset($filters['q'])) {
$get_q = $filters['q'];
}
}
if(preg_match('/price_incl.*?(asc|desc)/', $sort, $m)){
$sort = 'sell_price_incl ' . $m[1];
}
$SearchCategory = $Category;
if(!empty($SearchCategory) && ($SearchCategory->getSlug() == 'category' || $SearchCategory->getSlug() == 'categorie' || $SearchCategory->getSlug() == 'kategorie')){
$SearchCategory = null;
}
$relationProduct = null;
if(!empty($_GET['brand'])){
$brand_prod = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($_GET['brand']);
$model_prod = null;
if(!empty($_GET['model'])){
$model_prod = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($_GET['model']);
}
if(!empty($brand_prod)){
$relationProduct = $brand_prod;
}
if(!empty($model_prod)){
$relationProduct = $model_prod;
}
}
$dev = false;
if($this->containerInterface->getParameter('kernel.environment') == 'dev'){
$dev = true;
}
$products_data = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->search($this->Webshop, array(
'spec_filter_checked' => $spec_filter_checked,
'category' => $SearchCategory,
'relation' => $relationProduct,
'visible' => true,
'page' => 1,
/*'limit' => [
'start' => 0,
'limit' => 9
],*/
'q' => $get_q,
'qo' => $get_qo,
'dev' => $dev,
'filters' => $spec_filter_checked,
// 'debug' => ($dev ? true : false),
), $sort, $sort_dir, ($Settings->getPagination() == 'none'), false, (!empty($_GET['page']) && is_numeric($_GET['page']) ? $_GET['page'] : 1), $this->WebshopSettings->getPerPage());
$this->Timer->mark('Products loaded');
/*if($this->containerInterface->getParameter('kernel.environment') == 'dev'){
dump($products_data);die();
}*/
if (empty($products_data['total']) && !empty($_GET['brand']) && isset($_GET['model'])) {
$brand_prod = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($_GET['brand']);
$model_prod = null;
if(!empty($_GET['model'])){
$model_prod = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($_GET['model']);
}
if(!empty($brand_prod)){
if(!empty($model_prod)){
if((int)$this->WebshopSettings->getUriType() == 1){
$productUrl = '';
$productUrl .= ($Webshop->getSettings()->getUri() ? '/' . $Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
// $productUrl .= $productname;
// $productUrl .= '/' . $model_prod->getNumber();
$productUrl .= $model_prod->getCategory()->first()->getCategory()->getUri();
$productUrl .= '/' . $model_prod->getSlug();
}else{
$productUrl = '';
$productUrl .= ($Webshop->getSettings()->getUri() ? '/' . $Webshop->getSettings()->getUri() : $this->generateUrl('homepage') . ($Webshop->getCmssettings()->getBaseUri() ? $Webshop->getCmssettings()->getBaseUri() . '/' : ''));
//$productUrl .= ($Webshop->getSettings()->getUri() ? '/' . $Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
$productUrl .= $model_prod->getCategory()->first()->getCategory()->getUri();
$productUrl .= '/' . $model_prod->getSlug();
$productUrl = str_replace('//', '/', $productUrl);
}
}else{
if((int)$this->WebshopSettings->getUriType() == 1){
$productUrl = '';
$productUrl .= ($Webshop->getSettings()->getUri() ? '/' . $Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
// $productUrl .= $productname;
// $productUrl .= '/' . $model_prod->getNumber();
$productUrl .= $brand_prod->getCategory()->first()->getCategory()->getUri();
$productUrl .= '/' . $brand_prod->getSlug();
}else{
$productUrl = '';
$productUrl .= ($Webshop->getSettings()->getUri() ? '/' . $Webshop->getSettings()->getUri() : $this->generateUrl('homepage') . ($Webshop->getCmssettings()->getBaseUri() ? $Webshop->getCmssettings()->getBaseUri() . '/' : ''));
//$productUrl .= ($Webshop->getSettings()->getUri() ? '/' . $Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
$productUrl .= $brand_prod->getCategory()->first()->getCategory()->getUri();
$productUrl .= '/' . $brand_prod->getSlug();
$productUrl = str_replace('//', '/', $productUrl);
}
}
// dump($productUrl);die();
header('Location: ' . $productUrl);
exit;
}
}elseif(empty($products_data['total']) && !empty($_GET['q'])){
// dump($_GET['q']);die();
}
if(empty($products_data['total']) && $Settings->getFillEmptyCat()){
// Try to find by underlying categories
if($Category->getChildren()->count()){
$catlist = [];
foreach($Category->getChildren() as $c){
$catlist[] = $c->getId();
}
$products_data = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->search($this->Webshop, array(
'spec_filter_checked' => $spec_filter_checked,
'category' => $catlist,
'visible' => true,
'page' => 1,
'q' => $get_q,
'qo' => $get_qo,
'filters' => $spec_filter_checked,
), $sort, $sort_dir, ($Settings->getPagination() == 'none'), false, (!empty($_GET['page']) && is_numeric($_GET['page']) ? $_GET['page'] : 1), $this->WebshopSettings->getPerPage());
//$all_products = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->gatherProducts($catlist);
// $price_range = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->getPriceRange($Webshop, $catlist);
$catFix = true;
}
$this->Timer->mark('Products (fill underlying) loaded');
}
$this->Timer->mark('Stuff loaded');
$products = $products_data['results'];
foreach($products as $i => $p){
$p->activeCategory = $Category;
$products[$i] = $p;
}
// $prices = [];
// foreach ($products as $i => $product) {
// // check if this is the right function to get the right price, should doe sales, promotions etc.
// $p = $product->getRealPriceIncl($this->WebshopSettings);
// if(!empty($p)){
// $prices[] = $p;
// }
// }
if(!empty($Category->getMin()) && !empty($Category->getMax())){
$priceRange = [$Category->getMin(), $Category->getMax()];
// $priceRange = [0, 1];
}else{
if(empty($price_range)){
$price_range = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->getPriceRange($Webshop, $Category);
}
if(!empty($price_range)){
$pr = $price_range[0];
$priceRange = [floor($pr['min_price']), ceil($pr['max_price'])];
}else{
$priceRange = [0, 0];
if(!empty($prices)){
$priceRange = [floor(min($prices)), ceil(max($prices))];
}
}
}
$this->Timer->mark('Price range');
// Prepare specs
$specs = [];
$groups = [];
/*
if(empty($all_products)){
$all_products = $Category->getProducts(); //$this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->findAll();
}
foreach($all_products as $Product){
$Product = $Product->getProduct();
foreach($Product->getCategory() as $_Category){
foreach($_Category->getCategory()->getSpecGroups() as $_SpecGroup){
if(!$this->Webshop->getSpecGroups()->contains($_SpecGroup)) continue;
$groups[$_SpecGroup->getId()] = $_SpecGroup;
}
}
foreach($Product->getSpecGroups() as $_SpecGroup){
if(!$this->Webshop->getSpecGroups()->contains($_SpecGroup)) continue;
$groups[$_SpecGroup->getId()] = $_SpecGroup;
}
}
$this->Timer->mark('Loaded: specs');
// dump($groups);
$productsList = [];
foreach($all_products as $Product){
$Product = $Product->getProduct();
if($Product->getVisible() && $Product->getEnabled()){
$productsList[] = $Product;
}
if($Product->getType() > 0){
foreach($Product->getLinkedProducts() as $P){
$productsList[] = $P;
}
}
}
// dump(count($productsList));die();
$this->Timer->mark('Loaded: productslist');
// dump($productsList);die();
if($this->WebshopSettings->getShowUnusedSpecs()){
foreach($groups as $_SpecGroup){
if(!$this->Webshop->getSpecGroups()->contains($_SpecGroup)) continue;
foreach($_SpecGroup->getSpecs() as $_Spec){
if(!$Webshop->getSpecs()->contains($_Spec)) continue;
if($_Spec->getHidden() == true || $_Spec->getOptFilter() == false) continue;
if($_Spec->getType() == 'dropdown'){
$available = $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findBy(['spec' => $_Spec], ['position' => 'asc']);
$SpecValues = $_Spec->getValues();
if(!empty($SpecValues)){
$foundValues = 0;
foreach($SpecValues as $v){
if(!empty($v->getValue())){
$foundValues++;
}
}
if($foundValues == 0){
continue;
}
if(isset($specs[$_Spec->getId()])){
if(!is_array($specs[$_Spec->getId()]['value'])){
$specs[$_Spec->getId()]['value'] = [$specs[$_Spec->getId()]['value']];
}
$specs[$_Spec->getId()]['value'] = array_unique(array_merge($specs[$_Spec->getId()]['value'], (!empty($SpecValues) ? $SpecValues : $default)));
// }
}else{
$specs[$_Spec->getId()] = [
'id' => $_Spec->getId(),
'label' => $this->trans($_Spec->getLabel(), 'webshop'),
'value' => (!empty($SpecValues) ? $SpecValues : $default),
'available' => $available,
'multiple' => $_Spec->getMultiple(),
'required' => $_Spec->getRequired(),
'type' => $_Spec->getType(),
'disabled' => true,
];
}
}
}
}
}
}
$this->Timer->mark('Loaded: specs');
$specAvailability = [];
foreach($productsList as $Product){
if((!$Product->getVisible() && ($Product->getLinkedTo()->count() == 0 || (!$Product->getLinkedTo()->first()->getVisible() || !$Product->getLinkedTo()->first()->getEnabled()))) || !$Product->getEnabled()){
continue;
}
// dump($Product->getLabel());
foreach($groups as $_SpecGroup){
if(!$this->Webshop->getSpecGroups()->contains($_SpecGroup)) continue;
foreach($_SpecGroup->getSpecs() as $_Spec){
if(!$Webshop->getSpecs()->contains($_Spec)) continue;
// if($_Spec->getCode() != 'opslag') continue;
if($_Spec->getHidden() == true || $_Spec->getOptFilter() == false) continue;
if($_Spec->getType() == 'dropdown'){
$default = [];
$available = $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findBy(['spec' => $_Spec], ['position' => 'asc']);
$SpecValues = $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findValuesByProduct(
$_Spec,
$Product
);
}else{
$default = [];
$available = null;
$SpecValues = $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findValuesByProduct(
$_Spec,
$Product
);
}
if(!empty($SpecValues)){
if(!is_array($SpecValues)){
$SpecValues = [$SpecValues];
}
$foundValues = 0;
if($_Spec->getCode() == 'color' && count($SpecValues) > 1){
// Combine multi-color when spec has code 'color'
$spec_values = [];
$c_id = [];
$c_value = [];
$c_hex = [];
foreach($SpecValues as $k => $v){
if(!empty($v->getValue())){
$c_id[] = $v->getId();
$c_hex[] = $v->getHex();
$c_value[] = $v->getValue();
unset($SpecValues[$k]);
$foundValues++;
}
}
// dump(implode('-', $c_hex));
$SpecValues[implode('-', $c_id)] = implode('-', $c_hex);
}else{
foreach($SpecValues as $v){
if(!empty($v->getValue())){
// dump($v->getValue());
$foundValues++;
}
}
}
if($foundValues == 0){
continue;
}
// dump($SpecValues);
// dump($specs[5]['value']->toArray());die();
if(isset($specs[$_Spec->getId()])){
$specs[$_Spec->getId()]['disabled'] = false;
if(!is_array($specs[$_Spec->getId()]['value'])){
$specs[$_Spec->getId()]['value'] = [$specs[$_Spec->getId()]['value']];
}
$specs[$_Spec->getId()]['value'] = array_unique(array_merge($specs[$_Spec->getId()]['value'], (!empty($SpecValues) ? $SpecValues : $default)));
// }
}else{
$specs[$_Spec->getId()] = [
'id' => $_Spec->getId(),
'label' => $this->trans($_Spec->getLabel(), 'webshop'),
'value' => (!empty($SpecValues) ? $SpecValues : $default),
'available' => $available,
'multiple' => $_Spec->getMultiple(),
'required' => $_Spec->getRequired(),
'type' => $_Spec->getType(),
];
}
}
}
}
// $this->Timer->mark(' FETCH PRODUCT');
}
*/
// sleep(1.6);
$this->Timer->mark('Loaded: product list after specs');
// dump($specs[5]);die();
// Find favorite products
$listIds = [];
$WebshopUser = $this->getDoctrine()->getRepository('TrinityWebshopBundle:User')->findOneByUser($this->getUser());
if($WebshopUser){
foreach($WebshopUser->getProductList() as $ItemList){
foreach($ItemList->getProducts() as $p){
$listIds[] = $p->getId();
}
}
}
$this->Timer->mark('Loaded: id crap');
/*foreach($specs as $id => $data){
$poslist = [];
foreach($data['value'] as $SV){
if(!empty($SV) && !is_string($SV)){
$poslist[$SV->getPosition()][] = $SV;
}
}
ksort($poslist);
foreach($data['value'] as $SV){
if(!empty($SV) && is_string($SV)){
$poslist[9999][] = $SV;
}
}
$rawList = [];
foreach($poslist as $l){
foreach($l as $SV){
$rawList[] = $SV;
}
}
$specs[$id]['value'] = $rawList;
}*/
$specs = $Category->getSpecCache();
foreach($specs as $k => $spec){
if($spec['type'] == 'range'){
// Walk values for sorting
$resort = [];
foreach($spec['value'] as $v){
$resort[$v['value']][] = $v;
}
ksort($resort);
$new = [];
foreach($resort as $vd){
foreach($vd as $v){
$new[] = $v;
}
}
$specs[$k]['value'] = $new;
}
}
$tmp_brand = null;
$tmp_model = null;
if(!empty($filters['q'])){
$f = explode(' ', $filters['q']);
if(!empty($f)){
foreach($f as $i => $fp){
// Search for brand
if(isset($brandAndModelArr[ucfirst($fp)])){
$tmp_brand = ucfirst($fp);
unset($f[$i]);
break;
}
}
if(!empty($tmp_brand)){
foreach($f as $i => $fp){
// Search for brand
if(in_array($fp, $brandAndModelArr[$tmp_brand])){
$tmp_model = $fp;
unset($f[$i]);
break;
}
}
}
$filters['q'] = implode(' ', $f);
}
}
if(!empty($tmp_brand)){ $spec_filter['Merk'] = $tmp_brand; }
if(!empty($tmp_model)){ $spec_filter['Model'] = $tmp_model; }
$children_count = [];
$children = [];
$rootCategory = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findOneByLabel('Onderdelen');
if(!empty($spec_filter_checked) && !empty($rootCategory)){
$doSearch = true;
$redirectToId = null;
$children = [];
$children_raw = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findCategoriesWithSpecs($rootCategory, $spec_filter_checked, 'root');
// Check if only one category
/*if(count($children_raw) == 1 && !empty($children_raw[0])){
$tmp_id = $children_raw[0]['id'];
$redirectToId = $children_raw[0]['id'];
// Test sub
$sub_children_raw = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findCategoriesWithSpecs($tmp_id, $spec_filter_checked, 'sub');
if(count($sub_children_raw) == 1 && !empty($sub_children_raw[0])){
$redirectToId = $sub_children_raw[0]['id'];
}
}
if(!empty($redirectToId)){
// Redirect to category
$CatRedirect = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->find($redirectToId);
return $this->redirectToRoute($CatRedirect->getSlugKey());
}*/
foreach($children_raw as $c){
if($c['id']){
$children[] = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->find($c['id']);
$children_count[$c['id']] = $c['num'];
}
}
}
$paginationFilters = $spec_filter;
if(!empty($filters['q'])){
$paginationFilters['q'] = $filters['q'];
}
$Category = $this->parseEntityPageUrls($Category);
$this->Timer->mark('Loaded: before twig return');
// $this->Timer->show();
if($this->Meta && !empty($Category)){
$this->Meta->registerView($request, 'webshop_category', $Category->getId(), $Category->getLabel());
}
if($this->Meta && !empty($Category)){
$this->Meta->registerView($request, 'webshop_category', $Category->getId(), $Category->getLabel());
}
$response = $this->render('@TrinityWebshop/front/category.html.twig', $this->attributes([
'Category' => $Category,
'categories' => $categories,
'Page' => $Page,
'products' => $products,
'specs' => $specs,
'metatags' => $metatags,
'sort' => $sort,
'brandAndModel' => $brandAndModel,
'brandAndModelArr' => $brandAndModelArr,
'types' => $types,
'typesArr' => $typesArr,
'systemMetatags' => $systemMetatags,
'spec_filter_checked' => $spec_filter_checked,
'filters_visual' => $filters_visual,
'WebshopSettings' => $Settings,
'licenseplate' => $licenseplate,
'priceRange' => $priceRange,
'catFix' => $catFix,
'listIds' => $listIds,
'products_data' => $products_data,
'bodyClass' => 'category-view',
'spec_filter' => $spec_filter,
'filters' => $filters,
'paginationFilters' => $paginationFilters,
'custom_breadcrumbs' => $custom_breadcrumbs,
'children' => $children,
'children_count' => $children_count,
'defaultSort' => $defaultSort,
'allRootCategories' => $allRootCategories,
'webshop_tags' => $webshop_tags,
'RecipesPage' => $RecipesPage,
]));
//$response = $this->responseRewriteOutput($response, false, false);
return $response;
}
}
/**
* @Route("/webshop-main/categories/{parent}", name="webshop_front_categories")
* @Template()
*/
public function categoriesAction(Request $request, $parent)
{
parent::init($request);
$Parent = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->find($parent);
$categories = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findByParent($Parent);
return $this->attributes([
'categories' => $categories
]);
}
/**
* @Route("/webshop-main/review/{id}", name="webshop_review")
* @Template()
*/
public function reviewAction(Request $request, $id)
{
parent::init($request);
$post = null;
$saved = false;
if(!empty($_POST)){
$post = $_POST;
$Product = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($id);
$WebshopUser = $this->getDoctrine()->getRepository('TrinityWebshopBundle:User')->findOneByUser($this->getUser());
$rating = 0;
if(!empty($post['review']['rating'])){
$rating = $post['review']['rating'];
}
$Review = new Review();
$Review->setWebshop($this->Webshop);
$Review->setLabel($post['review']['title']);
$Review->setName($post['review']['name']);
$Review->setReview($post['review']['body']);
$Review->setRating((float)$rating);
// $Review->setRecommend($post['review']['recommend'] == 1);
$Review->setDate(new \DateTime());
$Review->setProduct($Product);
$Review->setUser($WebshopUser);
$Review->setIp($request->getClientIp());
if($this->WebshopSettings->getModerateReviews()){
$Review->setModerated(false);
}else{
$Review->setModerated(true);
}
$em = $this->getDoctrine()->getManager();
$em->persist($Review);
$em->flush();
// clear product cache
$Product->setCacheData(null);
$saved = true;
}
return $this->attributes([
'saved' => $saved,
]);
}
/**
* @Route("/webshop-main/ajax/productcount", name="mod_webshop_count")
*/
public function productCount( Request $request )
{
// Initialize StorageController
parent::init($request);
$Products = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->countBy();
dump($Products); die();
return new JsonResponse(array('count' => $productcount));
}
/**
* @Route("/webshop-main/configurable/{Product}", name="webshop_configurable")
* @Template()
*/
public function configurableProductAction(Request $request,$Product)
{
parent::init($request);
$data = $_POST;
if(isset($_GET['spec'])){
$data = $_GET;
}
$svid = null;
$checkSpecValue = null;
$checkSpec = null;
if(!empty($_GET['svid']) && is_numeric($_GET['svid'])){
$svid = (int)$_GET['svid'];
$checkSpecValue = $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->find($svid);
$checkSpec = $checkSpecValue->getSpec();
}
if(!empty($data['spec'])){
foreach($data['spec'] as $k => $v){
if(empty($v)){
unset($data['spec'][$k]);
}
}
}
$OriginalProduct = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($Product);
$all_values = [];
$enabled_values = [];
$disabled_values = [];
$all = [];
$enabled = [];
$disabled = [];
$matching = [];
$active = [];
foreach($OriginalProduct->getLinkedProducts() as $ChildProduct){
if($ChildProduct->getEnabled()){
foreach($ChildProduct->getSpecValues() as $SV){
if($svid){
if($SV->getId() == $svid){
$matching[] = $ChildProduct;
}else{
if($checkSpec != $SV->getSpec()){
$all[$SV->getId()] = $SV->getId();
$all_values[$SV->getId()] = $SV->getValue();
}
}
}else{
$matching[] = $ChildProduct;
$all[$SV->getId()] = $SV->getId();
$all_values[$SV->getId()] = $SV->getValue();
}
}
}
}
// dump('checkSpec => ' . $checkSpec->getLabel());
$selectedValues = [];
if(!empty($data['spec'])){
foreach($data['spec'] as $spec_id => $value_label){
$Spec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->find($spec_id);
// dump($Spec->getLabel());
foreach($Spec->getValues() as $SV){
if($SV->getValue() == $value_label){
$selectedValues[] = $SV;
}
}
}
}
$validProducts = [];
foreach($matching as $ChildProduct){
if($ChildProduct->canOrder()){
$productValues = $ChildProduct->getSpecValues();
$simplified = [];
foreach($productValues as $SV){
$simplified[] = $SV->getId();
}
foreach($selectedValues as $SV){
// dump($SV->getValue() . ' - ' . $SV->getId());
if(!$productValues->contains($SV)){
// dump('fail');
if(isset($validProducts[$ChildProduct->getId()])){
unset($validProducts[$ChildProduct->getId()]);
}
continue(2);
}
// dump('pass');
$validProducts[$ChildProduct->getId()] = $ChildProduct;
// $enabled[$SV->getId()] = $SV->getId();
// $enabled_values[$SV->getId()] = $SV->getValue();
}
}
}
// dump($validProducts); die();
foreach($validProducts as $ChildProduct){
foreach($ChildProduct->getSpecValues() as $SV){
$enabled[$SV->getId()] = $SV->getId();
$enabled_values[$SV->getId()] = $SV->getValue();
}
}
$disabled = array_diff($all, $enabled);
$disabled_values = array_diff($all_values, $enabled_values);
$config_spec_filter = [
'all' => array_values($all),
'enabled' => array_values($enabled),
'disabled' => array_values($disabled),
];
$config_spec_filter_values = [
'all' => array_values($all_values),
'enabled' => array_values($enabled_values),
'disabled' => array_values($disabled_values),
];
$chosen = [];
if(!empty($_GET['chosenid'])){
$chosen = explode('_', $_GET['chosenid']);
}
$products = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->findBySpecs($data, $Product, $this->containerInterface->getParameter('kernel.environment') == 'dev');
$products_sort_done = [];
$products_sort = [];
// if($this->containerInterface->getParameter('kernel.environment') == 'dev'){
if(!empty($data)){
// Sort based on spec_values
foreach($products as $p){
foreach($p->getSpecValues() as $sv){
if(!in_array($p->getId(), $products_sort_done) && !empty($sv->getSpec()) && (empty($data['spec']) || !array_key_exists($sv->getSpec()->getId(), $data['spec']))){
if(!isset($products_sort[$sv->getPosition()])){
$products_sort[$sv->getPosition()] = [];
}
$products_sort[$sv->getPosition()][] = $p;
$products_sort_done[] = $p->getId();
}
}
}
}
if(!empty($products_sort)){
$products = [];
ksort($products_sort);
foreach($products_sort as $svpos => $prods){
foreach($prods as $p){
$products[] = $p;
}
}
}
// }
if(empty($products)){
// No products found by filter, find another by target spec
$products = $matching;
}
if(!empty($products)){
$ChildProduct = $products[0];
foreach($ChildProduct->getSpecValues() as $SV){
$active[] = $SV->getId();
}
}
$config_spec_filter['active'] = $active;
$flatSpecs = [];
$allSpecsRaw = [];
$keyValue = [];
foreach($OriginalProduct->getLinkedProducts() as $Product){
$specs = [];
foreach($Product->getSpecValues() as $SV){
if(!empty($SV->getSpec())){
if ($SV->getSpec()->getOptDetail()) {
$specs[$SV->getSpec()->getId()] = $SV->getValue();
if(!isset($filters[$SV->getSpec()->getId()])){
if(!isset($allSpecsRaw[$SV->getSpec()->getId()])) $allSpecsRaw[$SV->getSpec()->getId()] = [];
if(!in_array($SV->getValue(), $allSpecsRaw[$SV->getSpec()->getId()])){
$allSpecsRaw[$SV->getSpec()->getId()][] = (int)$SV->getPosition() . '+' . $SV->getValue();
$keyValue[$SV->getSpec()->getId()][(int)$SV->getId()] = $SV->getValue();
sort($allSpecsRaw[$SV->getSpec()->getId()]);
}
}
}
}
}
$flatSpecs[$Product->getId()] = $specs;
}
$allSpecs = [];
foreach($allSpecsRaw as $sid => $sv){
foreach($sv as $svi => $svid){
$svid = preg_replace('/^\d\+/', '', $svid);
if(!isset($allSpecs[$sid]) || !in_array($svid, $allSpecs[$sid])){
$allSpecs[$sid][] = $svid;
}
}
}
$filters = [];
if(!empty($data['spec'])){
$filters = $data['spec'];
foreach($filters as $k => $v){
$filters[$k] = [$v];
}
}
$matchedSpecs = [];
$matchedOtherSpecs = [];
foreach($products as $Product){
if($Product->canOrder()){
$pid = $Product->getId();
if(!empty($filters)){
// Filters required, product MUST HAVE filters
if(!empty($flatSpecs[$pid])){
$flatProdSpecs = $flatSpecs[$pid];
$flatProdSpecsNotFiltered = $flatSpecs[$pid];
$notFound = false;
foreach($filters as $spec_id => $filter_values){
unset($flatProdSpecsNotFiltered[$spec_id]);
if(!array_key_exists($spec_id, $flatProdSpecs)){
$notFound = true;
}elseif(!in_array($flatProdSpecs[$spec_id], $filter_values)){
$notFound = true;
}
}
if(!$notFound){
$matchedSpecs[$pid] = $flatProdSpecs;
$matchedOtherSpecs[$pid] = $flatProdSpecsNotFiltered;
}
}
}else{
if(!empty($flatSpecs[$pid])){
$matchedOtherSpecs[$pid] = $flatSpecs[$pid];
$matchedSpecs[$pid] = $flatSpecs[$pid];
}
// No active filters, allow product
}
}
}
// Find other filters against currently selected
$specsAvailableCurrentFilter = [];
foreach($matchedOtherSpecs as $pid => $s){
foreach($s as $specid => $val){
if(!isset($specsAvailableCurrentFilter[$specid])){
$specsAvailableCurrentFilter[$specid] = [];
}
if(!in_array($val, $specsAvailableCurrentFilter[$specid])){
$specsAvailableCurrentFilter[$specid][] = $val;
}
}
}
$returnSpecs = [];
$returnSpecs['all_specs'] = $allSpecs;
$returnSpecs['enabled_specs'] = $specsAvailableCurrentFilter;
$disabled_specs = [];
foreach($allSpecs as $k => $v){
if(isset($specsAvailableCurrentFilter[$k])){
$disabled_specs[$k] = array_diff($v, $specsAvailableCurrentFilter[$k]);
if(empty($disabled_specs[$k])){
unset($disabled_specs[$k]);
}
}
}
$returnSpecs['disabled_specs'] = $disabled_specs;
$list = [];
foreach($products as $product){
$media = [];
$media_size = [];
$media_thumb = [];
if($product->getMedia()->count()){
foreach($product->getMedia() as $m){
$media_size[] = ($m->getWidth() > $m->getHeight() ? $m->getHeight() : $m->getWidth());
$media[] = $m->getWebPath();
$media_thumb[] = $m->getWebPath('thumb');
}
}else if($OriginalProduct->getMedia()->count()){
foreach($OriginalProduct->getMedia() as $m){
$media_size[] = ($m->getWidth() > $m->getHeight() ? $m->getHeight() : $m->getWidth());
$media[] = $m->getWebPath();
$media_thumb[] = $m->getWebPath('thumb');
}
}
$priceblock = '';
if($product->hasPromotion()){
$priceblock = '
<div class="price-wrapper">
<span class="price sale" data-price="' . $product->getRealPriceIncl($this->WebshopSettings, false, false, $this->WebshopCustomer) . '">' . $this->WebshopSettings->getCurrency()->getFormat($product->getRealPriceIncl($this->WebshopSettings, false, false, $this->WebshopCustomer)) . '</span>
</div><div class="price-wrapper">
<span class="price old">' . $this->WebshopSettings->getCurrency()->getFormat($product->getPriceIncl($this->WebshopSettings, false, false, $this->WebshopCustomer)) . '</span>
</div>
<span class="tax-suffix">' . ($this->WebshopSettings->getPriceDisplay() != 'excl' ? 'incl. BTW' : 'excl. BTW') . '</span>
';
// $priceblock = '<span class="col-sm col-md-6 price old">€ ' . number_format($product->getPriceIncl($this->WebshopSettings), 2, ',', '.') . '</span>
// <span class="col-sm col-md-6 price sale">€ ' . number_format($product->getRealPriceIncl($this->WebshopSettings), 2, ',', '.') . '</span>';
}elseif(!empty($product->getPriceSale()) && $product->getPriceSale() > 0){
$priceblock = '
<div class="price-wrapper">
<span class="price sale" data-price="' . $product->getRealPriceIncl($this->WebshopSettings, false, false, $this->WebshopCustomer) . '">' . $this->WebshopSettings->getCurrency()->getFormat($product->getRealPriceIncl($this->WebshopSettings, false, false, $this->WebshopCustomer)) . '</span>
</div><div class="price-wrapper">
<span class="price old">' . $this->WebshopSettings->getCurrency()->getFormat($product->getPriceIncl($this->WebshopSettings, false, false, $this->WebshopCustomer)) . '</span>
</div>
<span class="tax-suffix">' . ($this->WebshopSettings->getPriceDisplay() != 'excl' ? 'incl. BTW' : 'excl. BTW') . '</span>';
}else{
$priceblock = '<div class="price-wrapper">
<span class="price sale" data-price="' . $product->getRealPriceIncl($this->WebshopSettings, false, false, $this->WebshopCustomer) . '">' . $this->WebshopSettings->getCurrency()->getFormat($product->getRealPriceIncl($this->WebshopSettings, false, false, $this->WebshopCustomer)) . '</span>
<span class="tax-suffix">' . ($this->WebshopSettings->getPriceDisplay() != 'excl' ? 'incl. BTW' : 'excl. BTW') . '</span>
</div>';
}
if($this->WebshopSettings->getShowStockIndicator()){
$priceblock .= '<div class="stock-label">';
$lowStock = 2;
$mediumStock = 6;
$noStock = 0;
if (!empty($this->WebshopSettings->getStockLevels())) {
$stcklevel = $this->WebshopSettings->getStockLevels();
if (isset($stcklevel['low'])) {
$lowStock = $stcklevel['low'];
}
if (isset($stcklevel['medium'])) {
$mediumStock = $stcklevel['medium'];
}
}
if($this->WebshopSettings->getPicqerChoice() == 1 && !empty($this->WebshopSettings->getPicqerApikey()) && !empty($this->WebshopSettings->getPicqerUrl())){
$Picqer = new Picqer($this->WebshopSettings->getPicqerApikey(), $this->WebshopSettings->getPicqerUrl());
if($this->WebshopSettings->getPicqerFulfillment()){
if(!empty($this->WebshopSettings->getPicqerFulfillmentId())){
$fulfilment_id = $this->WebshopSettings->getPicqerFulfillmentId();
} else {
$fulfilment_id = null;
}
} else {
$fulfilment_id = null;
}
$stock = $Picqer::checkStock($product, $fulfilment_id);
if($stock !== "Product not found in Picqer" && $stock !== "Product empty"){
if ($stock == 0) {
$priceblock .= '<div class="text-danger"><i class="fa fa-times"></i> ' . $this->trans('Niet op voorraad', [], 'webshop') . '</div>';
}elseif((int)$stock >= (int)$product->getOutOfStockQuantity() && $stock < $lowStock){
$priceblock .= '<div class="text-warning"><i class="fa fa-circle"></i> ' . $this->trans('Zeer beperkt op voorraad', [], 'webshop') . '</div>';
}elseif((int)$stock >= (int)$product->getOutOfStockQuantity() && $stock < $mediumStock){
$priceblock .= '<div class="text-warning"><i class="fa fa-check"></i> ' . $this->trans('Beperkt op voorraad', [], 'webshop') . '</div>';
}elseif((int)$stock >= (int)$product->getOutOfStockQuantity()){
$priceblock .= '<div class="text-success"><i class="fa fa-check"></i> ' . $this->trans('Op voorraad', [], 'webshop') . '</div>';
}else{
$priceblock .= '<div class="text-danger"><i class="fa fa-times"></i> ' . $this->trans('Niet op voorraad', [], 'webshop') . '</div>';
}
$priceblock .= '</div>';
} else {
if($product->canOrder() && $product->getStockAmount() < $lowStock){
$priceblock .= '<div class="text-warning"><i class="fa fa-circle"></i> ' . $this->trans('Zeer beperkt op voorraad', [], 'webshop') . '</div>';
}elseif($product->canOrder() && $product->getStockAmount() < $mediumStock){
$priceblock .= '<div class="text-warning"><i class="fa fa-check"></i> ' . $this->trans('Beperkt op voorraad', [], 'webshop') . '</div>';
}elseif($product->canOrder()){
$priceblock .= '<div class="text-success"><i class="fa fa-check"></i> ' . $this->trans('Op voorraad', [], 'webshop') . '</div>';
}else{
$priceblock .= '<div class="text-danger"><i class="fa fa-times"></i> ' . $this->trans('Niet op voorraad', [], 'webshop') . '</div>';
}
$priceblock .= '</div>';
}
} else {
if($product->canOrder() && $product->getStockAmount() < $lowStock && $product->getStock()){
$priceblock .= '<div class="text-warning"><i class="fa fa-circle"></i> ' . $this->trans('Zeer beperkt op voorraad', [], 'webshop') . '</div>';
}elseif($product->canOrder() && $product->getStockAmount() < $mediumStock && $product->getStock()){
$priceblock .= '<div class="text-warning"><i class="fa fa-check"></i> ' . $this->trans('Beperkt op voorraad', [], 'webshop') . '</div>';
}elseif($product->canOrder()){
$priceblock .= '<div class="text-success"><i class="fa fa-check"></i> ' . $this->trans('Op voorraad', [], 'webshop') . '</div>';
}else{
$priceblock .= '<div class="text-danger"><i class="fa fa-times"></i> ' . $this->trans('Niet op voorraad', [], 'webshop') . '</div>';
}
$priceblock .= '</div>';
}
}
// Prepare specs
$specs = [];
$groups = [];
foreach($product->getCategory() as $_Category){
foreach($_Category->getCategory()->getSpecGroups() as $_SpecGroup){
if(!$this->Webshop->getSpecGroups()->contains($_SpecGroup)) continue;
$groups[$_SpecGroup->getId()] = $_SpecGroup;
}
}
foreach($product->getSpecGroups() as $_SpecGroup){
if(!$this->Webshop->getSpecGroups()->contains($_SpecGroup)) continue;
$groups[$_SpecGroup->getId()] = $_SpecGroup;
}
// dump($groups);
// $productsList = [];
// $productsList[] = $product;
// foreach($product->getLinkedProducts() as $P){
// $productsList[] = $P;
// }
// foreach($productsList as $product){
// dump($product->getLabel());
if(!empty($product->getWeight())){
$specs['weight'] = [
'label' => 'Gewicht',
'value' => ($product->getWeight() >= 1000 ? $product->getWeight() . ' Kg.' : $product->getWeight() . ' g'),
'type' => 'text',
];
}
foreach($groups as $_SpecGroup){
if(!$this->Webshop->getSpecGroups()->contains($_SpecGroup)) continue;
foreach($_SpecGroup->getSpecs() as $_Spec){
if ($_Spec->getOptDetail()) {
// if($_Spec->getCode() != 'opslag') continue;
if($_Spec->getHidden() == true) continue;
if($_Spec->getType() == 'dropdown'){
$default = [];
$available = $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findBy(['spec' => $_Spec], ['position' => 'asc']);
$SpecValues = $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findValuesByProduct(
$_Spec,
$product
);
}else{
$default = [];
$available = null;
$SpecValues = $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findValuesByProduct(
$_Spec,
$product
);
}
if($_Spec->getCode() == 'bereidingswijze'){
continue;
}
if(!empty($SpecValues)){
if(!is_array($SpecValues)){
$SpecValues = [$SpecValues];
}
$flatValues = [];
$flatHex = [];
foreach($SpecValues as $Value){
$flatValues[] = $Value->getValue();
$flatHex[] = $Value->getHex();
}
// dump($SpecValues);
if(isset($specs[$_Spec->getId()])){
if(!is_array($specs[$_Spec->getId()]['value'])){
$specs[$_Spec->getId()]['value'] = [$specs[$_Spec->getId()]['value']];
}
$specs[$_Spec->getId()]['value'] = array_unique(array_merge($specs[$_Spec->getId()]['value'], (!empty($flatValues) ? $flatValues : $default)));
// }
}else{
$specs[$_Spec->getId()] = [
'label' => $_Spec->getLabel(),
'value' => implode(', ', (!empty($flatValues) ? $flatValues : $default)),
'hex' => implode(', ', (!empty($flatHex) ? $flatHex : [])),
'type' => $_Spec->getType(),
];
}
}
}
}
}
// }
if($product->getType() != 2){
if(!empty($product->getSku())){
$specs['sku'] = [
'label' => 'SKU',
'value' => $product->getSku(),
'type' => 'text',
];
}
if(!empty($product->getEan())){
$specs['ean'] = [
'label' => 'EAN',
'value' => $product->getEan(),
'type' => 'text',
];
}
}
$pdata = [
'id' => $product->getId(),
'can_order' => $product->canOrder(),
'label' => $product->getLabel(),
'sub_label' => $product->getLabelSub(),
'number' => $product->getNumber(),
'ean' => $product->getEan(),
'sku' => $product->getSku(),
'intro' => $product->getIntro(),
'intro_stripped' => strip_tags($product->getIntro()),
'description' => $product->getDescription(),
'price' => $product->getPriceIncl($this->WebshopSettings),
'priceblock' => $priceblock,
'specs' => $specs,
'media' => $media,
'media_size' => $media_size,
'media_thumb' => $media_thumb,
];
$list[] = $pdata;
}
return new JsonResponse(['specs' => $returnSpecs, 'keyValue' => $keyValue, 'spec_filter' => $config_spec_filter, 'spec_values' => $config_spec_filter_values, 'options' => $list]);
}
/**
* @Route("/compare", name="webshop_compare")
* @Template()
*/
public function compareAction(Request $request)
{
$this->init($request);
$Webshop = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($this->language, $this->Settings);
$Settings = $Webshop->getSettings();
$Page = $Settings->getPage();
if(empty($Page)){
$Page = new \App\CmsBundle\Entity\Page();
$Page->setOptionBreadcrumbs(false);
$Page->setOptionSubnavigation(false);
$Page->setOptionTitle(false);
}
$Page->setTitle($this->trans('Vergelijken', [], 'webshop'));
$metatags = $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getBySystem(0, (int)$Page->getId(), true);
$systemMetatags = $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getBySystem(1, false, false);
$specData = [];
$products = [];
if(!empty($_GET['compare'])){
foreach($_GET['compare'] as $id){
$p = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($id);
$products[] = $p;
foreach($p->getSpecValues() as $v){
$spec = $v->getSpec();
if(!empty($spec)){
$specData[$spec->getLabel()][$id] = [
'value' => $v->getValue(),
'hex' => $v->getHex(),
'type' => $spec->getType(),
];
}
}
}
}
return $this->attributes([
'Page' => $Page,
'metatags' => $metatags,
'systemMetatags' => $systemMetatags,
'WebshopSettings' => $Settings,
'products' => $products,
'specData' => $specData,
]);
}
/**
* @Route("/webshop-main/reviews/{product_id}/{page}", name="webshop_reviews")
* @Template()
*/
public function reviewsAction(Request $request, $product_id, $page = 1)
{
$this->init($request);
$perpage = 3;
$Product = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($product_id);
$moderate = $this->WebshopSettings->getModerateReviews();
$reviews_count = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->countReviews($product_id, $page, $perpage, $moderate);
$pages = ceil($reviews_count / $perpage);
$reviews = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->fetchReviews($product_id, $page, $perpage, $moderate);
return ['reviews' => $reviews, 'reviews_count' => $reviews_count, 'Product' => $Product, 'product_id' => $product_id, 'WebshopSettings' => $this->WebshopSettings, 'User' => $this->getUser(), 'page' => $page, 'pages' => $pages];
}
/**
* @Route("/profile/orders", name="profile_orders")
* @Template()
*/
public function ordersAction(Request $request)
{
$this->init($request);
$Webshop = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($this->language, $this->Settings);
// $breadcrumbs = $this->get("white_october_breadcrumbs");
// $breadcrumbs->addRouteItem($Webshop->getLabel(), "homepage");
// $this->breadcrumbs->addRouteItem('Mijn Profiel', "profile");
$this->breadcrumbs->addRouteItem('Mijn Bestellingen', "profile_orders");
$orders = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Order')->findBy(array(
'user' => $this->getUser(),
'webshop' => $Webshop
), array(
'date' => 'desc'
));
if(!empty($_GET['pay'])){
$Order = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Order')->find($_GET['pay']);
$mollie = new \Mollie_API_Client;
$mollie->setApiKey(($this->containerInterface->get('kernel')->getEnvironment() == 'dev' ? self::MOLLIE_API_DEV : self::MOLLIE_API_LIVE));
$Payment = $mollie->payments->create(array(
"amount" => $Order->getTotalPrice(),
"description" => "Order " . $Order->getHash(),
"redirectUrl" => $this->generateUrl('cart_finish', array('hash' => $Order->getHash()), UrlGeneratorInterface::ABSOLUTE_URL),
"method" => $Order->getPayment(),
));
$em = $this->getDoctrine()->getManager();
$Order->setPaymentId($Payment->id);
$Order->setPaymentStatus($Payment->status);
$em->persist($Order);
// Payment history
$OrderPayment = new OrderPayment();
$OrderPayment->setOrder($Order);
$OrderPayment->setDate(new \Datetime());
$OrderPayment->setPaymentId($Payment->id);
$OrderPayment->setPaymentStatus($Payment->status);
// Save order
// Add to payment history
$em->persist($OrderPayment);
// Remove cart
// $em->remove($Cart);
$em->flush();
header('Location:' . $Payment->links->paymentUrl);
exit;
}
return $this->attributes(['orders' => $orders]);
}
/**
* @Route("/profile/orders/download-invoice/{id}", name="profile_orders_download_invoice", requirements={"id": "\d+"})
*/
public function downloadInvoiceAction(Request $request, $id)
{
parent::init($request);
$Webshop = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($this->language, $this->Settings);
$Settings = $Webshop->getSettings();
$Invoice = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Invoice')->find($id);
if($Invoice && $Invoice->getOrder()->getUser()->getUser() == $this->getUser()){
$tplPath = '@TrinityWebshop/invoice_template.html.twig';
$customTplPath = preg_replace('/src\/.*?$/', 'templates/invoice_template.html.twig', __DIR__);
if(file_exists($customTplPath)){
$tplPath = '/invoice_template.html.twig';
}
$tpl = $this->renderView($tplPath, $this->attributes([
'Invoice' => $Invoice,
]));
$html = $tpl;
$pdf = new Pdf();
// $pdf->setBrd(true);
$pdf->setInvoice($Invoice);
$pdf->setTranslator($this->translator);
$pdf->setSettings($this->Settings);
$pdf->setWebshopSettings($Settings);
$pdf->setTitle($this->trans('FACTUUR #', [], 'webshop', $Webshop->getLanguage()->getLocale()) . $Invoice->getId());
$pdf->setTitleRight($Invoice->getDate()->format('d-m-Y H:i:s'));
// $pdf->create();
$pdf->AddPage();
$pdf->writeHTML($html, true, false, true, false, '');
$pdf->Output($this->doSluggify($this->Settings->getLabel()) . '_' . $this->trans('Factuur', [], 'webshop', $Webshop->getLanguage()->getLocale()) . '_' . $Invoice->getId() . '.pdf', 'D');
exit;
}
header('Location:/'); exit;
}
/**
* @Route("/profile/orders/download-credit/{id}", name="profile_orders_download_credit", requirements={"id": "\d+"})
*/
public function downloadCreditAction(Request $request, $id)
{
parent::init($request);
$Webshop = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($this->language, $this->Settings);
$Settings = $Webshop->getSettings();
$CmsSettings = $Webshop->getCmsSettings();
$language = $CmsSettings->getLanguage();
$Credit = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Credit')->find($id);
if($Credit && $Credit->getOrder()->getUser()->getUser() == $this->getUser()){
$tplPath = '@TrinityWebshop/credit_template.html.twig';
$customTplPath = preg_replace('/src\/.*?$/', 'templates/credit_template.html.twig', __DIR__);
if(file_exists($customTplPath)){
$tplPath = '/credit_template.html.twig';
}
$tpl = $this->renderView($tplPath, $this->attributes([
'Credit' => $Credit,
'sitename' => $CmsSettings->getLabel(),
'locale' => $language->getLocale(),
]));
$html = $tpl;
$pdf = new Pdf();
// $pdf->setBrd(true);
$pdf->setCredit($Credit);
$pdf->setTranslator($this->translator);
$pdf->setSettings($this->Settings);
$pdf->setWebshopSettings($Settings);
$pdf->setTitle($this->trans('CREDITFACTUUR #', [], 'webshop', $Webshop->getLanguage()->getLocale()) . $Credit->getId());
$pdf->setTitleRight($Credit->getDate()->format('d-m-Y H:i:s'));
// $pdf->create();
$pdf->AddPage();
$pdf->writeHTML($html, true, false, true, false, '');
$pdf->Output($this->doSluggify($this->Settings->getLabel()) . '_' . $this->trans('Creditfactuur', [], 'webshop', $Webshop->getLanguage()->getLocale()) . '_' . $Credit->getId() . '.pdf', 'D');
exit;
}
header('Location:/'); exit;
}
private function doSluggify($str, $replace=array(), $delimiter='-')
{
$str = strtolower($str);
if( !empty($replace) ) {
$str = str_replace((array)$replace, ' ', $str);
}
$slugify = new \Cocur\Slugify\Slugify();
return $slugify->slugify($str, $delimiter);
}
/**
* @Route("/profile/orders/view/{id}", name="profile_orders_view")
* @Template()
*/
public function orderViewAction(Request $request, $id)
{
$this->init($request);
$order = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Order')->find($id);
$tax = [];
$tax_total = 0;
/*if($order->getTotalDelivery() > 0){
$tax[21] = (($order->getTotalDelivery() / 100) * 21);
}*/
if(!empty($order->getProducts())){
foreach($order->getProducts() as $Product){
$Tax = $Product->getProduct()->getTax();
if(empty($Tax)){
$Tax = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Tax')->findOneByPercent(21);
}
$percent = $Tax->getPercent();
$price = $Product->getTotalPrice();
// dump($price);
$_tax = (($price / 100) * $percent);
if(!isset($tax[$percent])) $tax[$percent] = 0;
$tax[$percent] += $_tax;
$tax_total += $_tax;
}
}
$delivery = $order->getTotalDelivery();
if(!empty($delivery)){
$t = (($delivery / 100) * 21);
$tax[21] += $t;
// $tax_total += $t;
}
return [
'order' => $order,
'tax' => $tax,
'tax_total' => $tax_total
];
}
/**
* @Route("/dropfilter/{specid}", name="drop_filter")
* @Template()
*/
public function dropFilter(Request $request, $specid = null){
$this->init($request);
if($specid == 'all'){
$this->get('session')->set('ecomm_spec_query', '');
$this->get('session')->set('ecomm_spec_plate', '');
$this->get('session')->set('ecomm_spec_filter', []);
return new JsonResponse([]);
}
$q = '';
if(preg_match('/_/', $specid)){
$specid = explode('_', $specid);
$q = explode(' ', $this->get('session')->get('ecomm_spec_query'));
foreach($q as $k => $v){
if($specid[1] == $k || empty($v)){
unset($q[$k]);
}
}
$q = implode(' ', $q);
$this->get('session')->set('ecomm_spec_query', $q);
}else{
if($specid == 'q'){
$this->get('session')->set('ecomm_spec_query', '');
}else{
$filters = $this->get('session')->get('ecomm_spec_filter');
if(!empty($filters)){
foreach($filters as $k => $v){
$Spec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->findOneByLabel($k);
if($Spec){
if($Spec->getId() == $specid){
unset($filters[$k]);
}
}
}
}
$this->get('session')->set('ecomm_spec_filter', $filters);
}
}
return new JsonResponse(['q' => $q]);
}
/**
* @Route("/profile/list/{listid}/{articleid}", name="profile_list")
* @Template()
*/
public function listAction(Request $request, $listid = 0, $articleid = null)
{
$this->init($request);
$Product = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->find($articleid);
$addedList = false;
$savedList = false;
$alreadyAdded = false;
$WebshopUser = $this->getDoctrine()->getRepository('TrinityWebshopBundle:User')->findOneByUser($this->getUser());
if(!empty($_POST['listid'])){
if($_POST['listid'] == 'new'){
$ProductList = new \App\Trinity\WebshopBundle\Entity\ProductList();
$ProductList->setUser($WebshopUser);
$ProductList->setLabel($_POST['newList']);
}else{
$ProductList = $this->getDoctrine()->getRepository('TrinityWebshopBundle:ProductList')->find($_POST['listid']);
}
if($ProductList->hasProduct($Product)){
$alreadyAdded = true;
}else{
$Product->addProductlist($ProductList);
$em = $this->getDoctrine()->getManager();
$em->persist($Product);
$em->persist($ProductList);
$em->flush();
if(empty($_POST['listid'])){
$addedList = true;
}else{
$savedList = true;
}
}
}
$ProductLists = $this->getDoctrine()->getRepository('TrinityWebshopBundle:ProductList')->findByUser($WebshopUser);
return [
'Product' => $Product,
'alreadyAdded' => $alreadyAdded,
'addedList' => $addedList,
'savedList' => $savedList,
'lists' => $ProductLists,
'newList' => (!empty($_POST['newList']) ? $_POST['newList'] : '')
];
}
/**
* @Route("/profile/orders/download/{id}", name="profile_orders_download")
* @Template()
*/
public function downloadAction(Request $request, $id)
{
$this->init($request);
$Order = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Order')->find($id);
if($Order->getUser()->getId() != $this->getUser()->getId() && !$this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')){
throw new AccessDeniedHttpException('Invalid order');
}
\App\Trinity\WebshopBundle\Classes\Invoice::generate($request, $Order, $this->container, 'D');
}
/**
* @Route("/ajax/products/{webshopid}", name="products")
*/
public function productsAction(Request $request, Environment $twig, int $webshopid = 0)
{
$this->init($request);
if($webshopid > 0){
$Webshop = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->findOneBy(['id' => $webshopid]);
if(empty($Webshop)){
$Webshop = $this->Webshop;
}
}else{
$Webshop = $this->Webshop;
}
$Settings = $Webshop->getSettings();
$em = $this->getDoctrine()->getManager();
$return = ['count' => 0, 'products' => [], 'checked' => []];
$postValues = $_POST;
if(!empty($_GET['c'])) $postValues = $_GET;
if(!isset($postValues['filter'])){
$postValues['filter'] = [];
}
$this->get('session')->set('ecomm_spec_plate', '');
$this->get('session')->set('ecomm_spec_filter', []);
// Hardwired for licenseplate check
if(!empty($postValues['licenseplate'])){
$api_url = 'https://services.onderdelenlijn.nl/parts/v7.asmx?WSDL';
$user = 'info@beyonit.nl';
$pass = 'fUAJT6!XP';
$Webshop = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($this->language, $this->Settings);
$SOAP_LOCATION_APP = $api_url;
$soapClient = new \SoapClient($SOAP_LOCATION_APP, ["trace" => 1, "exception" => 0, 'cache_wsdl' => WSDL_CACHE_NONE, 'soap_version' => SOAP_1_2]);
$soapMessage = [
'Credentials' => [
'Username' => $user,
'Password' => $pass,
],
'Parameters' => [
'Culture' => "NL",
'TviRequest' => [
'Type' => 'LicensePlate',
'Value' => $postValues['licenseplate']
]
]
];
$soapResult = $soapClient->TviData($soapMessage);
$res = json_decode(json_encode($soapResult), true);
if(!empty($res["TviDataResult"]["Result"])){
$array = $res["TviDataResult"]["Result"];
/*if(isset($array["Aldoc"]["Models"]["AldocModel"]["Images"])){
$img_url = str_replace('demo.', '', $array["Aldoc"]["Models"]["AldocModel"]["Images"]["Root"]["Small"]) . $array["Aldoc"]["Models"]["AldocModel"]["Images"]["Filenames"]["string"][0];
dump($img_url);
} else {
dump("No Images");
}*/
$filters = [];
$model = (!empty($array["Basic"]["MakeModel"]["MakeName"]) ? $array["Basic"]["MakeModel"]["MakeName"] : null);
$type = (!empty($array["Basic"]["MakeModel"]["ModelName"]) ? $array["Basic"]["MakeModel"]["ModelName"] : null);
$year = (!empty($array["Basic"]["Constructed"]['Year']) ? $array["Basic"]["Constructed"]['Year'] : null);
$month = (!empty($array["Basic"]["Constructed"]['Month']) ? $array["Basic"]["Constructed"]['Month'] : null);
if($model){ $filters['Merk'] = $model; }
if($type){ $filters['Model'] = $type; }
if($year){ $filters['Bouwjaar'] = $year; }
// if($month){ $filters['Bouwmaand'] = $month; }
}else{
// Fallback
$filters = [];
$model = 'Mazda';
$type = 'CX-3.';
$year = '2015';
$month = '6';
if($model){ $filters['Merk'] = $model; }
if($type){ $filters['Model'] = $type; }
if($year){ $filters['Bouwjaar'] = $year; }
// if($month){ $filters['Bouwmaand'] = $month; }
}
$this->get('session')->set('ecomm_spec_plate', $postValues['licenseplate']);
$this->get('session')->set('ecomm_spec_filter', $filters);
if(!empty($filters)){
foreach($filters as $k => $v){
$postValues['spec'][$k] = $v;
}
}
}
$filters_visual = [];
if(!empty($postValues['spec'])){
foreach($postValues['spec'] as $specLabel => $value){
if(!preg_match('/Alle/', $value)){
// TMP IGNORE
// if(in_array($specLabel, ['/Model', 'Bouwjaar', 'Bouwmaand'])) continue;
$Spec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->findOneBy(['label' => $specLabel]);
if(!empty($Spec) && !empty($value)){
$postValues['filter'][$Spec->getId()] = $value;
$filters_visual[$Spec->getId()] = $value;
}
}
}
}
unset($postValues['spec']);
/*if(!empty($postValues['filter'])){
foreach($postValues['filter'] as $id => $values){
foreach($values as $ind => $value){
if(strpos($value, '-') !== false){
unset($postValues['filter'][$id][$ind]);
$value = explode('-', $value);
foreach($value as $v){
$postValues['filter'][$id][] = $v;
}
}
}
if(empty($postValues['filter'][$id])){
unset($postValues['filter'][$id]);
}
}
}*/
// die( "<pre>" . print_r( $_POST, 1 ) . "</pre>" );
$filters = [
// 'category' => $Category,
// 'q' => 'red',
/*'filters' => [
7 => [
'Nederland',
'Frankrijk',
]
]*/
'visible' => true
];
if(!empty($postValues['c'])){
$filters['category'] = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->find($postValues['c']);
}
if(!empty($postValues['q'])){
// $this->get('session')->set('ecomm_spec_query', $postValues['q']);
foreach(explode(' ', $postValues['q']) as $q){
if(!isset($filters_visual['q'])){
$filters_visual['q'] = [];
}
$filters_visual['q'][] = '<strong>' . $this->trans('Zoeken', [], 'webshop') . ':</strong> ' . $q;
}
if ($Settings->getSearchMode() && $Settings->getSearchMode() == 'or')
{
/*if(is_string($postValues['q']) && preg_match('/^([a-zA-Z]+)(\d+)$/', $postValues['q'], $m)){
$filters['q'] = [];
$filters['qo'] = [];
// if(strlen($m[1]) > 2){
$filters['q'][] = $m[1];
// }
// if(strlen($m[2]) > 2){
$filters['q'][] = $m[2];
// }
$filters['qo'][] = $m[1] . $m[2];
$filters['qo'][] = $m[1] . '-' . $m[2];
$filters['qo'][] = $m[1] . ' ' . $m[2];
}else{*/
$f = explode(' ', $postValues['q']);
$filters['q'] = [];
$filters['qo'] = [];
foreach($f as $v){
// if(strlen($v) > 2){
$filters['q'][] = $v;
// }
}
$filters['qo'][] = implode($f, '-');
$filters['qo'][] = implode($f, ' ');
//}
} else {
$filters['q'] = explode(' ', $postValues['q']);
}
}
if(!empty($postValues['limit'])){
$filters['limit'] = [
'start' => (!empty($postValues['start']) ? (int)$postValues['start'] : 0),
'limit' => $postValues['limit'],
];
}
if(!empty($postValues['page'])){
$filters['page'] = (int)$postValues['page'];
}else{
$filters['page'] = 1;
}
/*if(!empty($postValues['order'])){
$filters['order'] = $postValues['order'];
}*/
if(!empty($postValues['price']) && isset($postValues['price']['min']) && isset($postValues['price']['max'])){
$filters['price'] = [(float)$postValues['price']['min'], (float)$postValues['price']['max']];
$filters['ignore_pricing'] = ((int)$postValues['ignore_pricing'] == 1);
}
if(!empty($postValues['filter'])){
foreach($postValues['filter'] as $spec_id => $values){
if(!is_array($values)){
$postValues['filter'][$spec_id] = [$values];
}
}
}
$spec_value_link = [];
if(!empty($postValues['filter'])){
foreach($postValues['filter'] as $specid => $f){
$return['checked'] = array_merge($return['checked'], $f);
$spec_value_link[] = [$specid, $f];
}
$filters['filters'] = $postValues['filter'];
}
foreach($spec_value_link as $k => $r){
$Spec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->find($r[0]);
if(!empty($Spec)){
foreach($r[1] as $v){
$allow = true;
if(is_array($v)){
$allow = false;
if(!empty($v[0]) && !empty($v[1])){
$allow = true;
$v = implode(' - ', $v);
}
}
if($allow){
$filters_visual[$Spec->getId()] = '<strong>' . ($Spec->getLabel() == 'Model compatibiliteit' ? 'Bouwjaar' : $Spec->getLabel()) . ':</strong> ' . $v;
}
}
}
}
//$Webshop = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($this->language, $this->Settings);
// dump($filters);
if(!empty($postValues['order'])){
$postValues['order_full'] = $postValues['order'];
if(preg_match('/^price_/', $postValues['order_full'])){
$dir = preg_replace('/^.*? (.*?)$/', '$1', $postValues['order_full']);
$postValues['order_full'] = 'sell_price_incl ' . $dir;
// $postValues['order_full'] = 'price_sale ' . $dir . ', p.' . $postValues['order_full'];
// die( "<pre>" . print_r( $postValues['order_full'], 1 ) . "</pre>" );
}
}
$perPage = $Settings->getPerPage();
if(!empty($postValues['pp'])){
$perPage = $postValues['pp'];
}
$sort = (!empty($postValues['order_full']) ? $postValues['order_full'] : null);
if(preg_match('/price_incl.*?(asc|desc)/', $sort, $m)){
$sort = 'sell_price ' . $m[1];
}
$filters['sliders'] = [];
$filters['sliders_range'] = [];
if(!empty($filters['filters'])){
foreach($filters['filters'] as $s_id => $f_values){
if(is_numeric($s_id)){
// dump($s_id);
$Spec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->find($s_id);
// dump($Spec);die();
if($Spec->getType() == 'slider'){
$filters['sliders'][] = $s_id;
}
if($Spec->getType() == 'slider2'){
$filters['sliders_range'][] = $s_id;
}
}
}
}
$filters['tags'] = [];
if(!empty($postValues['tags']) && is_array($postValues['tags'])){
$filters['tags'] = $postValues['tags'];
}
$products_data = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->search($Webshop, $filters, $sort, 'asc', ($this->WebshopSettings->getPagination() == 'none'), false, 1, $perPage, 0, true);
if(empty($products_data['total']) && !empty($filters['category'])){
// Try to find by underlying categories
if($filters['category']->getChildren()->count()){
$catlist = [];
foreach($filters['category']->getChildren() as $c){
$catlist[] = $c->getId();
}
$filters['category'] = $catlist;
$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), $perPage, 0, true);
}
}
// dump($products_data);die();
$products = $products_data['results'];
$product_return = [];
$product_return_childs = [];
$product_list = [];
// dump($products);
// die();
$prices = [];
foreach ($products as $product) {
$p = $product->getRealPriceIncl($Settings);
// if(!empty($p)){
$prices[] = $p;
// }
}
if(!empty($prices)){
$priceRange = [min($prices), max($prices)];
}else{
$priceRange = [0, 0];
}
$return['count'] = count($products);
$return['priceRange'] = $priceRange;
$defaultImage = $Settings->getDefaultProductImageObject();
foreach($products as $Product){
$Category = null;
if(!empty($Product->getCategory())){
foreach($Product->getCategory() as $_Category){
$Category = $_Category;
}
}
$now = new \DateTime();
$relatedChild = null;
$childProd = null;
$childProductSale = false;
$children = [];
foreach($Product->getLinkedProducts() as $p){
$media = $Product->getMedia()->first();
$secondMedia = null;
if(empty($media)){
$media = $defaultImage;
} else if ($this->WebshopSettings->getImageSwap() and $Product->getMedia()->count() >= 2){
$secondMedia = $Product->getMedia()->next();
}
if(!empty($filters['category'])){
$Category = $filters['category'];
}
if($Category instanceof \App\Trinity\WebshopBundle\Entity\CategoryProduct){
$Category = $Category->getCategory();
}
$matchCount = 0;
if(!empty($filters['filters'])){
foreach($p->getSpecValues() as $sv){
if($sv->getSpec()){
if(array_key_exists($sv->getSpec()->getId(), $filters['filters'])){
$f = $filters['filters'][$sv->getSpec()->getId()];
if(in_array($sv->getValue(), $f)){
$matchCount++;
}
}
}
}
}
if(!empty($filters['filters']) && $matchCount >= count($filters['filters'])){
$relatedChild = $p;
}
$product_list[] = $p;
$childProd = (float)$p->getRealPriceIncl($Settings);
if($p->hasPromotion() || (!empty($p->getPriceSale()) && $p->getPriceSale() > 0)){
$childProductSale = true;
}
$prod = [
'id' => $p->getId(),
'label' => ($p->getBrand() ? $p->getBrand()->getLabel() . ' ' : '') . $p->getLabel(),
'label_sub' => $p->getLabelSub(),
'intro' => $p->getIntro(),
'intro_stripped' => strip_tags($p->getIntro()),
'number' => $p->getNumber(),
'price' => $Settings->getCurrency()->getFormat($p->getPriceIncl($Settings)),
'real_price' => $Settings->getCurrency()->getFormat($p->getRealPriceIncl($Settings)),
'image' => null,
'isNew' => ($p->getNew() && (($p->getNewFrom() <= $now && $p->getNewTill() >= $now) || (empty($p->getNewTill()) && empty($p->getNewFrom())))),
'exclusive' => $p->getExclusive(),
'priceSell' => (float)$p->getSellPrice(),
'priceSellIncl' => (float)$p->getSellPriceIncl(),
'priceSale' => $p->getPriceSale(),
'priceSaleFloat' => (float)$p->getPriceSale(),
'priceSalePercent' => $p->getPriceSalePercent(),
'category_id' => $Category->getId(),
'hasSale' => ((float)$p->getPriceSale() > 0 || $p->hasPromotion()),
'hasPromotion' => $p->hasPromotion(true),
'hasCombi' => $p->hasCombi(),
'canOrder' => $p->canOrder(),
'isChild' => true,
'hasMedia' => !empty($media),
'media' => (!empty($media) ? $media->getWebPath() : 'bundles/trinitywebshop/img/no-product-image.png'),
'mediaWidth' => (!empty($media) ? $media->getWidth() : 800),
'mediaHeight' => (!empty($media) ? $media->getHeight() : 600),
'hasSecondMedia' => !empty($secondMedia),
'secondMedia' => (!empty($secondMedia) ? $secondMedia->getWebPath() : ''),
'secondMediaWidth' => (!empty($secondMedia) ? $secondMedia->getWidth() : ''),
'secondMediaHeight'=> (!empty($secondMedia) ? $secondMedia->getHeight() : ''),
'price_display' => $p->getDisplayPrice($Settings, $this->WebshopCustomer, $this->getUser()),
'review_enabled' => $this->WebshopSettings->getEnableCardReviews(),
'review_count' => $p->getReviews()->count(),
'review_average' => $p->getScore(),
'card_specs' => $p->getProductCardSpecValues(),
];
$children[] = $prod;
$product_return_childs[$p->getId()] = $prod;
}
$media = $Product->getMedia()->first();
$secondMedia = null;
if(empty($media)){
$media = $defaultImage;
} else if ($this->WebshopSettings->getImageSwap() and $Product->getMedia()->count() >= 2){
$secondMedia = $Product->getMedia()->next();
}
if(!empty($filters['category'])){
$Category = $filters['category'];
}
if($Category instanceof \App\Trinity\WebshopBundle\Entity\CategoryProduct){
$Category = $Category->getCategory();
}
if(is_array($Category)){
$Category = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->find(reset($Category));
}
if(empty($Category)){
continue;
}
if(empty($Product->getLanguage())){
$locale = 'nl';
}else{
$locale = $Product->getLanguage()->getLocale();
}
switch($locale)
{
case "de":
$productname = 'produkt';
break;
case "fr":
$productname = 'produit';
break;
default:
$productname = 'product';
}
if((int)$this->WebshopSettings->getUriType() == 1){
$productUrl = '';
$productUrl .= ($Webshop->getSettings()->getUri() ? '/' . $Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
$productUrl .= $productname;
$productUrl .= '/' . $Product->getNumber();
$productUrl .= '/' . $Product->getSlug();
}else{
$productUrl = '';
$productUrl .= ($Webshop->getSettings()->getUri() ? '/' . $Webshop->getSettings()->getUri() : $this->generateUrl('homepage') . ($Webshop->getCmssettings()->getBaseUri() ? $Webshop->getCmssettings()->getBaseUri() . '/' : ''));
//$productUrl .= ($Webshop->getSettings()->getUri() ? '/' . $Webshop->getSettings()->getUri() : $this->generateUrl('homepage'));
$productUrl .= $Category->getUri();
$productUrl .= '/' . $Product->getSlug();
$productUrl = str_replace('//', '/', $productUrl);
}
if($Category){
$product_list[] = $Product;
$prod = [
'id' => $Product->getId(),
'type' => $Product->getType(),
'label' => ($Product->getBrand() ? $Product->getBrand()->getLabel() . ' ' : '') . $Product->getLabel(),
'label_sub' => $Product->getLabelSub(),
'intro' => $Product->getIntro(),
'intro_stripped' => strip_tags($Product->getIntro()),
'number' => $Product->getNumber(),
'url' => $productUrl,
'price' => $Settings->getCurrency()->getFormat((float)$Product->getPriceIncl($Settings)),
'real_price' => ($childProd ? $childProd : $Settings->getCurrency()->getFormat($Product->getRealPriceIncl($Settings))),
'image' => null,
'isNew' => ($Product->getNew() && (($Product->getNewFrom() <= $now && $Product->getNewTill() >= $now) || (empty($Product->getNewTill()) && empty($Product->getNewFrom())))),
'exclusive' => $Product->getExclusive(),
'priceSell' => (float)$Product->getSellPrice(),
'priceSellIncl' => (float)$Product->getSellPriceIncl(),
'priceSale' => $Product->getPriceSale(),
'priceSaleFloat' => (float)$Product->getPriceSale(),
'priceSalePercent' => $Product->getPriceSalePercent(),
'category_id' => $Product->getCategory()->first()->getCategory()->getId(),
'hasSale' => ((float)$Product->getPriceSale() > 0 || $Product->hasPromotion() || $childProductSale),
'hasPromotion' => $Product->hasPromotion(true),
'hasCombi' => $Product->hasCombi(),
'hasFeatured' => $Product->getFeatured() ? true : false,
'canOrder' => $Product->canOrder(),
'isChild' => false,
'hasMedia' => !empty($media),
'media' => (!empty($media) ? $media->getWebPath() : 'bundles/trinitywebshop/img/no-product-image.png'),
'mediaWidth' => (!empty($media) ? $media->getWidth() : 800),
'mediaHeight' => (!empty($media) ? $media->getHeight() : 600),
'hasSecondMedia' => !empty($secondMedia),
'secondMedia' => (!empty($secondMedia) ? $secondMedia->getWebPath() : ''),
'secondMediaWidth' => (!empty($secondMedia) ? $secondMedia->getWidth() : ''),
'secondMediaHeight'=> (!empty($secondMedia) ? $secondMedia->getHeight() : ''),
'products' => $children,
'products_count' => count($children),
'price_display' => $Product->getDisplayPrice($Settings, $this->WebshopCustomer, $this->getUser()),
'review_enabled' => $this->WebshopSettings->getEnableCardReviews(),
'review_count' => $Product->getReviews()->count(),
'review_average' => $Product->getScore(),
'card_specs' => $Product->getProductCardSpecValues(),
// 'discountHtml' => $discountHtml,
];
if(!empty($Product->getMedia())){
foreach($Product->getMedia() as $Media){
$prod['image'] = '/' . $Media->getWebPath();
break;
}
}
if(!empty($relatedChild) && $relatedChild->getMedia()->count()){
$prod['image'] = '/' . $relatedChild->getMedia()->first()->getWebPath();
$prod['media'] = $relatedChild->getMedia()->first()->getWebPath();
}
$product_return[$Product->getId()] = $prod;
// }
$return['products'][] = $prod;
// }
}
}
// dump(array_keys($product_return));
$filter_type = 'up';
// xxx hmmmm?
//$return['products'] = [];
$spec_response = [
'enabled' => [],
'disabled' => [],
'all' => [],
];
/*
Filter products list based on filters
*/
$specs_filters = (!empty($filters['filters']) ? $filters['filters'] : []);
// Remove range filters
foreach($specs_filters as $k => $v){ if(isset($v['range'])){ unset($specs_filters[$k]); } }
if(!empty($filters['category'])){
if(!empty($specs_filters)){
$compatible_specvalues = $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->checkCompatibleValues($specs_filters, (!empty($filters['category']) ? $filters['category'] : null));
if(!is_array($filters['category'])){
$all_category_specs = $filters['category']->getSpecCache();
foreach($all_category_specs as $spec_id => $sdata){
foreach($sdata['value'] as $vdata){
$v = $vdata['value'];
// Capture for all
if(!isset($spec_response['all'][$spec_id])) $spec_response['all'][$spec_id] = [];
$spec_response['all'][$spec_id][] = $v;
if(!empty($compatible_specvalues[$spec_id])){
// Found spec in compatible
if(in_array($v, $compatible_specvalues[$spec_id])){
// Spec + value is compatible
if(!isset($spec_response['enabled'][$spec_id])) $spec_response['enabled'][$spec_id] = [];
$spec_response['enabled'][$spec_id][] = $v;
}else{
// Spec + value is not compatible
if(!isset($spec_response['disabled'][$spec_id])) $spec_response['disabled'][$spec_id] = [];
$spec_response['disabled'][$spec_id][] = $v;
}
}else{
// Spec at all not compatible
if(!isset($spec_response['disabled'][$spec_id])) $spec_response['disabled'][$spec_id] = [];
$spec_response['disabled'][$spec_id][] = $v;
}
}
}
}
}
}
// dump($spec_response);die();
/*
Convert strings to SpecValue IDs
*/
/*$specs_filters_ids = [];
foreach($specs_filters as $spec_id => $strings){
foreach($strings as $string){
$Spec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->find($spec_id);
$SpecValues = $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->findBy(['spec' => $Spec, 'value' => $string]);
foreach($SpecValues as $SpecValue){
$specs_filters_ids[] = $spec_id . '+' . $SpecValue->getId();
}
}
}*/
/*
Collect strict list of spec -> spec_value -> product
*/
/*foreach($product_list as $X){
dump($X->getId() . ' | ' . $X->getLabel());
}*/
/*$checkMatchTarget = count($specs_filters_ids);
// dump($specs_filters_ids);
$filter_productsList = [];
// $simple_productsList = [];
foreach($product_list as $Product){
if(empty($specs_filters_ids)){
if(!empty($product_return[$Product->getId()])){
$ProductObject = $product_return[$Product->getId()];
if(!in_array($ProductObject, $return['products'])){
$return['products'][] = $ProductObject;
}
}
}else{
$checkMatchCount = 0;
foreach($Product->getSpecValues() as $SpecValue){
if($SpecValue instanceof \App\Trinity\WebshopBundle\Entity\SpecValue){
$Spec = $SpecValue->getSpec();
// dump('X ======:' . $Product->getId() . ' | ' . $Product->getLabel() . ' | ' . $Spec->getId() . '+' . $SpecValue->getId());
$checkMatchCount = 0;
if(empty($specs_filters_ids) || in_array($Spec->getId() . '+' . $SpecValue->getId(), $specs_filters_ids)){
$filter_productsList[] = $Product;
// dump('X ======:' . $Product->getId() . ' | ' . $Product->getLabel() . ' | ' . $Spec->getId() . '+' . $SpecValue->getId());
if(!empty($product_return_childs[$Product->getId()])){
// dump('FOUND ======:' . $Product->getId() . ' | ' . $Product->getLabel() . ' | ' . $Spec->getId() . '+' . $SpecValue->getId());
if($Product->getLinkedTo()->count() > 0){
if($Product->getVisible()){
// dump('CHILD VISIBLE =======: ' . $Product->getId() . ' | ' . $Product->getLabel() . ' | ' . $Spec->getId() . '+' . $SpecValue->getId());
$ProductObject = $product_return_childs[$Product->getId()];
if(!in_array($ProductObject, $return['products'])){
$return['products'][] = $ProductObject;
}
}
// dump('CHILD =======: ' . $Product->getId() . ' | ' . $Product->getLabel() . ' | ' . $Spec->getId() . '+' . $SpecValue->getId());
foreach($Product->getLinkedTo() as $ParentProduct){
if(!empty($product_return_childs[$ParentProduct->getId()])){
$ProductObject = $product_return_childs[$ParentProduct->getId()];
if(!in_array($ProductObject, $return['products'])){
$return['products'][] = $ProductObject;
}
}
}
}else{
// dump('ROOT =======: ' . $Product->getId() . ' | ' . $Product->getLabel() . ' | ' . $Spec->getId() . '+' . $SpecValue->getId());
$ProductObject = $product_return_childs[$Product->getId()];
if(!in_array($ProductObject, $return['products'])){
$return['products'][] = $ProductObject;
}
}
}
}
}
}
}
}
// die();
$return['count'] = count($return['products']);
$return['total'] = count($return['products']);
$return['current'] = count($return['products']);
// dump($return);die();
// dump($return['products']);die();
// die();
// dump($simple_productsList);die();
/ *
Setup new specs arrays
* /
$specs_groups = [];
$specs_id_to_obj = [];
$specs_all = [];
$specs_available = [];
$specs_disabled = [];
$specs_all_simple = [];
$specs_available_simple = [];
$specs_disabled_simple = [];
// dump(count($filter_productsList) );die();
foreach($filter_productsList as $Product){
foreach($Product->getSpecValues() as $SpecValue){
if($SpecValue instanceof \App\Trinity\WebshopBundle\Entity\SpecValue){
$Spec = $SpecValue->getSpec();
foreach($Spec->getGroups() as $Group){
$specs_groups[$Group->getId()] = $Group;
}
if($Spec instanceof \App\Trinity\WebshopBundle\Entity\Spec){
$specs_id_to_obj[$SpecValue->getId()] = $SpecValue;
$specs_available_simple[$Spec->getId()][$SpecValue->getPosition() . '_' . $SpecValue->getId()] = $SpecValue->getId();
ksort($specs_available_simple[$Spec->getId()]);
}
}
}
}
foreach($specs_groups as $SpecGroup){
if($SpecGroup instanceof \App\Trinity\WebshopBundle\Entity\SpecGroup){
foreach($SpecGroup->getSpecs() as $Spec){
foreach($Spec->getValues() as $SpecValue){
$specs_id_to_obj[$SpecValue->getId()] = $SpecValue;
$specs_all_simple[$Spec->getId()][$SpecValue->getPosition() . '_' . $SpecValue->getId()] = $SpecValue->getId();
ksort($specs_all_simple[$Spec->getId()]);
}
}
}
}
foreach($specs_all_simple as $spec_id => $values){
if(!isset($specs_available_simple[$spec_id])){
$specs_disabled_simple[$spec_id] = $values;
}else{
$diff = array_diff($values, $specs_available_simple[$spec_id]);
if(!empty($diff)){
$specs_disabled_simple[$spec_id] = $diff;
}
}
}
foreach($specs_all_simple as $spec_id => $values){
foreach($values as $value_id){
$SpecValue = $specs_id_to_obj[$value_id];
$sv_data = [
'id' => $SpecValue->getId(),
'value' => $SpecValue->getValue(),
'hex' => $SpecValue->getHex(),
];
$specs_all[$spec_id][] = $sv_data;
}
}
foreach($specs_available_simple as $spec_id => $values){
foreach($values as $value_id){
$SpecValue = $specs_id_to_obj[$value_id];
$sv_data = [
'id' => $SpecValue->getId(),
'value' => $SpecValue->getValue(),
'hex' => $SpecValue->getHex(),
];
$specs_available[$spec_id][] = $sv_data;
}
}
foreach($specs_disabled_simple as $spec_id => $values){
foreach($values as $value_id){
$SpecValue = $specs_id_to_obj[$value_id];
$sv_data = [
'id' => $SpecValue->getId(),
'value' => $SpecValue->getValue(),
'hex' => $SpecValue->getHex(),
];
$specs_disabled[$spec_id][] = $sv_data;
}
}
$return['specs_all'] = $specs_all;
$return['specs_available'] = $specs_available;
$return['specs_disabled'] = $specs_disabled;*/
// New
$return['specs_disabled'] = $spec_response['disabled'];
$return['specs_available'] = $spec_response['enabled'];
$return['specs_all'] = $spec_response['all'];
if(empty($postValues['order'])){
$postValues['order'] = 'pos asc';
}
$order_pos = explode(' ', $postValues['order']);
/*if($order_pos[0] != 'pos'){
// Sort
$sorted = [];
$new_list = [];
foreach($return['products'] as $prod){
if($order_pos[0] == 'label'){
$sorted[$prod['label']][] = $prod;
}elseif($order_pos[0] == 'price_incl'){
$sorted[$prod['real_price']][] = $prod;
}else{
// $sorted[$prod['pos']][] = $prod;
}
if($order_pos[1] == 'asc'){
ksort($sorted);
}else{
krsort($sorted);
}
}
// dump($sorted);die();
// Reset to list
foreach($sorted as $prods){
foreach($prods as $p){
$new_list[] = $p;
}
}
$return['products'] = $new_list;
}*/
// dump($return['specs']);die();
// Prepare specs for json
/*foreach($return['specs'] as $specId => $spec){
if(is_array($spec['value'])){
$list = [];
foreach($spec['value'] as $v){
$list[] = [
'id' => $v->getId(),
'value' => $v->getValue(),
];
}
$return['specs'][$specId]['value'] = $list;
}
if(is_array($spec['available'])){
$list = [];
foreach($spec['available'] as $v){
$list[] = [
'id' => $v->getId(),
'value' => $v->getValue(),
];
}
$return['specs'][$specId]['available'] = $list;
}
}*/
$return['total'] = $products_data['total'];
$return['current'] = $products_data['current'];
$return['start'] = $products_data['start'];
$return['limit'] = $products_data['limit'];
$return['pages'] = $products_data['pages'];
$return['page'] = $products_data['page'];
$return['filters_visual'] = $filters_visual;
$return['hasmore'] = ($products_data['page'] < $return['pages']);
$return['filters'] = (!empty($postValues['filter']) ? $postValues['filter'] : []);
$allFilters = [];
if(!empty($postValues['q'])){
$allFilters['q'] = $postValues['q'];
}
foreach($return['filters'] as $spec_id => $data){
if(!empty($data['range'])){
if(empty($data['range'][0]) && empty($data['range'][1])){
unset($return['filters'][$spec_id]);
}else{
if(!empty($data[0])){
$Spec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->find($spec_id);
$allFilters[$Spec->getLabel()] = $data[0];
}
}
}else{
if(!empty($data[0])){
$Spec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->find($spec_id);
$allFilters[$Spec->getLabel()] = $data[0];
}
}
}
$route = (!empty($postValues['route']) ? $postValues['route'] : 'homepage');
$return['pagination'] = '<div class="js-pag">' . $twig->render(
'@Cms/pagination_bootstrap.html.twig',
[
'currentFilters' => $allFilters,
'currentPage' => $return['page'],
'paginationPath' => $route,
'lastPage' => $return['pages'],
'showAlwaysFirstAndLast' => true
]
) . '</div>';
// Render pagination HTML
/*{% include '@Cms/pagination_bootstrap.html.twig' with {
currentPage : products_data.page,
paginationPath: app.request.attributes.get('_route'),
lastPage: products_data.pages,
showAlwaysFirstAndLast: true
}
only %}*/
// dump($return['specs']);die();
// Try to find grouped values
/*foreach($return['specs'] as $id => $spec){
foreach($spec['value'] as $n => $value){
$return['specs'][$id]['value'][$n] = explode(' / ', $value);
}
}*/
return new JsonResponse($return);
// return $this->render('@TrinityWebshop/default/category.html.twig', array(
// 'Category' => $Category,
// 'products' => $products,
// 'specs' => $specs,
// ));
}
private function parseEntityPageUrls($entity)
{
if ($entity instanceof \App\Trinity\WebshopBundle\Entity\Product)
{
$intro = $this->parseCmsUrls($entity->getIntro());
$entity->setIntro($intro);
$description = $this->parseCmsUrls($entity->getDescription());
$entity->setDescription($description);
}
if ($entity instanceof \App\Trinity\WebshopBundle\Entity\Category)
{
$description = $this->parseCmsUrls($entity->getDescription());
$entity->setDescription($description);
$blocktext = $this->parseCmsUrls($entity->getBlockText());
$entity->setBlockText($blocktext);
}
return $entity;
}
private function parseSettingsPageUrls($Settings)
{
$intro = $this->parseCmsUrls($Settings->getInfo());
$Settings->setInfo($intro);
$c1 = $this->parseCmsUrls($Settings->getCustom1());
$Settings->setCustom1($c1);
$c2 = $this->parseCmsUrls($Settings->getCustom2());
$Settings->setCustom2($c2);
$c3 = $this->parseCmsUrls($Settings->getCustom3());
$Settings->setCustom3($c3);
$c4 = $this->parseCmsUrls($Settings->getCustom4());
$Settings->setCustom4($c4);
$c5 = $this->parseCmsUrls($Settings->getCustom5());
$Settings->setCustom5($c5);
$c6 = $this->parseCmsUrls($Settings->getCustom6());
$Settings->setCustom6($c6);
$usp = $this->parseCmsUrls($Settings->getUsps());
$Settings->setUsps($usp);
return $Settings;
}
}